@wafertools/wafermap 0.35.0 → 0.35.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/AGENTS.md +7 -1
  2. package/CHANGELOG.md +129 -0
  3. package/README.md +6 -3
  4. package/dist/packages/canvas-adapter/charts/boxplot.js +1 -1
  5. package/dist/packages/canvas-adapter/charts/capability.js +1 -1
  6. package/dist/packages/canvas-adapter/charts/histogram.js +1 -1
  7. package/dist/packages/canvas-adapter/renderWaferGallery.js +1 -1
  8. package/dist/packages/canvas-adapter/renderWaferMap.d.ts +14 -1
  9. package/dist/packages/canvas-adapter/renderWaferMap.js +1 -1
  10. package/dist/packages/canvas-adapter/summaryPanel.d.ts +31 -8
  11. package/dist/packages/canvas-adapter/summaryPanel.js +4 -2
  12. package/dist/packages/canvas-adapter/summaryToggle.d.ts +11 -0
  13. package/dist/packages/canvas-adapter/summaryToggle.js +1 -0
  14. package/dist/packages/canvas-adapter/toolbar.d.ts +8 -0
  15. package/dist/packages/canvas-adapter/toolbar.js +2 -2
  16. package/dist/packages/canvas-adapter/userGuideHtml.d.ts +1 -1
  17. package/dist/packages/canvas-adapter/userGuideHtml.js +37 -21
  18. package/dist/packages/canvas-adapter/version.d.ts +2 -2
  19. package/dist/packages/canvas-adapter/version.js +1 -1
  20. package/dist/packages/canvas-adapter/warnings.js +1 -1
  21. package/dist/packages/core/classify.d.ts +5 -0
  22. package/dist/packages/core/classify.js +1 -1
  23. package/dist/packages/core/dieTable.d.ts +26 -0
  24. package/dist/packages/core/dieTable.js +1 -1
  25. package/dist/packages/core/passBins.d.ts +6 -0
  26. package/dist/packages/core/passBins.js +1 -1
  27. package/dist/packages/renderer/buildView.js +1 -1
  28. package/dist/packages/renderer/buildWaferMap.d.ts +32 -1
  29. package/dist/packages/renderer/buildWaferMap.js +1 -1
  30. package/dist/packages/renderer/spec.d.ts +4 -0
  31. package/dist/packages/renderer/spec.js +1 -1
  32. package/dist/packages/renderer/valueFilter.d.ts +55 -0
  33. package/dist/packages/renderer/valueFilter.js +1 -0
  34. package/dist/packages/stats/analyzeWaferLot.js +1 -1
  35. package/dist/packages/stats/analyzeWaferMap.d.ts +44 -3
  36. package/dist/packages/stats/analyzeWaferMap.js +1 -1
  37. package/dist/packages/stats/capability.d.ts +5 -0
  38. package/dist/packages/stats/capability.js +1 -1
  39. package/dist/packages/stats/clusterDetection.js +1 -1
  40. package/dist/packages/stats/connectedComponents.d.ts +19 -0
  41. package/dist/packages/stats/connectedComponents.js +1 -1
  42. package/dist/packages/stats/lotPattern.js +1 -1
  43. package/dist/packages/stats/math.d.ts +25 -3
  44. package/dist/packages/stats/math.js +1 -1
  45. package/dist/packages/stats/patternClassification.d.ts +44 -18
  46. package/dist/packages/stats/patternClassification.js +1 -1
  47. package/dist/packages/stats/plotData.d.ts +11 -0
  48. package/dist/packages/stats/plotData.js +1 -1
  49. package/dist/packages/stats/regions.d.ts +6 -0
  50. package/dist/packages/stats/regions.js +1 -1
  51. package/dist/packages/stats/renderSummaryReport.js +33 -33
  52. package/dist/packages/stats/reportHtml.d.ts +7 -6
  53. package/dist/packages/stats/reportHtml.js +39 -37
  54. package/dist/packages/stats/synthesis.d.ts +44 -17
  55. package/dist/packages/stats/synthesis.js +1 -1
  56. package/dist/packages/stats/types.d.ts +12 -0
  57. package/llms.txt +2 -2
  58. package/package.json +1 -1
  59. package/dist/packages/canvas-adapter/summaryRail.d.ts +0 -7
  60. package/dist/packages/canvas-adapter/summaryRail.js +0 -1
@@ -1 +1 @@
1
- import{createWafer as U}from"../core/wafer.js";import{isYieldEligibleDie as we,getDieKey as X,hasPosition as F}from"../core/dies.js";import{applyOrientation as te,transformDies as xe,clipDiesToWafer as De}from"../core/transforms.js";import{generateDies as ve}from"../core/dies.js";import{dieHasAnyTestData as Me,dieLink as G,finaliseDie as j,linkDie as Se,recordedVerdict as Ce,recordedVerdictsReader as ke,tableFromRows as Ae,testValue as q,testsPresent as Oe,VERDICT_FAIL as Ne,VERDICT_NONE as $e,VERDICT_PASS as Re}from"../core/dieTable.js";import{isDieColumns as Te,linkColumns as Ee,linkRows as ne,relink as We}from"./columnarInput.js";import{affineRotation as Fe,affineMirror as Ie,affineCompose as _e,affinePoint as Pe}from"../core/transforms.js";import{inferWaferFromXY as Ve}from"../core/inference/wafer.js";import{resolveGridPitch as Be}from"../core/inference/pitch.js";import{assignGridIndices as Le}from"../core/inference/grid.js";import{generateReticleGrid as Ye}from"../core/reticle.js";import{applyDerivedTests as Xe}from"./derivedTests/apply.js";import{isStdfBin as je,isStdfCoord as ie,isStdfTestNumber as se,isStdfSite as Ke,STDF_BIN_MAX as He,STDF_COORD_MAX as re,STDF_TEST_NUM_MAX as ze,STDF_SITE_MAX as Ue}from"../core/stdf.js";import{hasAnyKey as Ge,maxOf as J,minOf as oe,modeOf as qe}from"../core/utils.js";import{aggregateValues as ae,aggregateBinCounts as Je,stackHoldsMeasurements as Qe}from"../core/aggregates.js";import{normalizePassBins as de}from"../core/passBins.js";import{defaultRingCount as Q}from"../core/ringCount.js";export function isParametricTest(t){return t?.testType!=="F"}export function isBuiltMap(t){return"wafer"in t&&"dies"in t&&"dataAxisFlip"in t}function Ze(t){const e=(i,a)=>({ringCount:i,ringCountWarning:{code:"analysis-option-corrected",severity:"warning",message:`ringCount=${String(t)} ${a} (using ${i}).`}});if(t===void 0)return{ringCount:Q(),ringCountWarning:void 0};if(typeof t!="number"||!Number.isFinite(t))return e(Q(),"is not a finite number");const n=Math.max(1,Math.round(t));return n===t?{ringCount:t,ringCountWarning:void 0}:e(n,"is not a whole number of at least 1")}function et(t,e){const n=Array.isArray(t)?{}:t,i={hbin:0,sbin:0,siteNum:0,testValues:0,testPass:0};let a;const o=(u,b)=>{i[u]++,a??=`${u} ${JSON.stringify(b)}`},s={bins:0,positions:0,values:0,sites:0,orientation:0},r=new Set;let m=0;if(e){i.testValues+=e.wrongValues,i.testPass+=e.wrongVerdicts,e.example!==void 0&&(a??=e.example),s.values+=e.nonFinite;for(const u of e.badTestNumbers)r.add(u)}const p=u=>u==null?!0:typeof u!="number"?!1:Number.isNaN(u)?(m++,!1):je(u)?!0:(s.bins++,!1);function d(u){const b=new Set,w=new Set;for(let O=0;O<u.length;O+=O<50?1:100){const k=u[O];if(!(k===null||typeof k!="object")){if(k.testValues&&typeof k.testValues=="object")for(const M of Object.keys(k.testValues))b.add(M);if(k.testPass&&typeof k.testPass=="object")for(const M of Object.keys(k.testPass))w.add(M)}}const g=[...b],y=[...w],A=O=>se(Number(O));for(const O of new Set([...g,...y]))A(O)||r.add(O);const R=g.map(A),v=y.map(A),N=g.map(Number),B=y.map(Number);let I;for(let O=0;O<u.length;O++){const k=u[O];if(k===null||typeof k!="object")continue;const M=k;let Y;const _=()=>Y??={...M};M.hbin!=null&&typeof M.hbin!="number"&&o("hbin",M.hbin),M.sbin!=null&&typeof M.sbin!="number"&&o("sbin",M.sbin),p(M.hbin)||(_().hbin=void 0),p(M.sbin)||(_().sbin=void 0);const L=typeof M.x=="number"&&!ie(M.x),f=typeof M.y=="number"&&!ie(M.y);if(L||f){s.positions+=(L?1:0)+(f?1:0);const S=_();S.x=void 0,S.y=void 0}M.siteNum!=null&&typeof M.siteNum!="number"?(o("siteNum",M.siteNum),_().siteNum=void 0):typeof M.siteNum=="number"&&!Ke(M.siteNum)&&(s.sites++,_().siteNum=void 0);const C=M.testValues;if(C&&typeof C=="object"){let S;for(let $=0;$<g.length;$++){const E=g[$],W=C[N[$]];if(W!=null){if(!R[$]){S??={...C},delete S[E];continue}typeof W!="number"?(o("testValues",W),S??={...C},delete S[E]):Number.isFinite(W)||(s.values++,S??={...C},delete S[E])}}S&&(_().testValues=S)}const T=M.testPass;if(T&&typeof T=="object"){let S;for(let $=0;$<y.length;$++){const E=y[$],W=T[B[$]];if(W!=null){if(!v[$]){S??={...T},delete S[E];continue}typeof W!="boolean"&&(o("testPass",W),S??={...T},delete S[E])}}S&&(_().testPass=S)}Y&&((I??=u.slice())[O]=Y)}return I}const c={warnings:[]};if(Array.isArray(t))c.results=d(t);else{Array.isArray(n.results)&&(c.results=d(n.results)),Array.isArray(n.dies)&&(c.dies=d(n.dies));const u=n.lotStack?.results;if(Array.isArray(u)){const b=u.map(w=>Array.isArray(w)?d(w):void 0);b.some(Boolean)&&(c.stackResults=b.map((w,g)=>w??u[g]))}}if(Array.isArray(n.testDefs)){const u=n.testDefs,b=u.filter(w=>w==null||typeof w.testNumber!="number"||se(w.testNumber));for(const w of u)b.includes(w)||r.add(String(w.testNumber));b.length!==u.length&&(c.testDefs=b)}const h=n.waferConfig?.orientation;if(typeof h=="number"){const u=Number.isFinite(h)?(h%360+360)%360:NaN;u===0||u===90||u===180||u===270?c.orientation=u:(s.orientation++,c.orientation=0)}const l=(u,b,w=`${b}s`)=>`${u} ${u===1?b:w}`,x=[];if(i.hbin&&x.push(l(i.hbin,"hard bin")),i.sbin&&x.push(l(i.sbin,"soft bin")),i.siteNum&&x.push(l(i.siteNum,"site number")),i.testValues&&x.push(l(i.testValues,"test value")),i.testPass&&x.push(l(i.testPass,"pass/fail verdict")),x.length){const u=`buildWaferMap received ${x.join(", ")} of the wrong type (for example ${a}), treated as missing. Bins, sites and test values must be numbers and verdicts true/false \u2014 a bin of "1" is not pass bin 1 \u2014 so those dies have no bin, no site, no value or no verdict, and yield and every chart leave them out. Convert them with Number() (and verdicts to booleans) and rebuild.`;console.warn(`[wafermap] ${u}`),c.warnings.push({code:"input-values-not-numbers",message:u,severity:"error"})}const D=[];if(s.bins&&D.push(`${l(s.bins,"bin")} (legal: whole numbers 0\u2013${He}) \u2014 those dies have no bin`),s.positions&&D.push(`${l(s.positions,"coordinate")} (legal: whole numbers \u2212${re} to ${re}) \u2014 those dies have no position`),r.size&&D.push(`${l(r.size,"test number")} (legal: whole numbers 0\u2013${ze}) \u2014 those tests are left out`),s.values&&D.push(`${l(s.values,"test value")} that ${s.values===1?"is":"are"} not finite \u2014 left out`),s.sites&&D.push(`${l(s.sites,"site number")} (legal: 0\u2013${Ue}) \u2014 those dies have no site`),s.orientation&&D.push("a waferConfig.orientation other than 0, 90, 180 or 270 \u2014 the map is built at 0"),D.length||m){const u=[];D.length&&u.push(`buildWaferMap received values outside the STDF V4 ranges, treated as missing: ${D.join("; ")}.`),m&&u.push(`${l(m,"bin was","bins were")} NaN and ${m===1?"is":"are"} treated as no bin.`);const b=u.join(" ");console.warn(`[wafermap] ${b}`),c.warnings.push({code:"input-values-outside-stdf",message:b,severity:"warning"})}return c}function fe(t){const e=(p,d)=>p!==null&&typeof p=="object"&&p[d]!==void 0,n=Array.isArray(t)?{}:t,i=[],a=(p,d,c)=>{p&&i.push(`\`${d}\` (now \`${c}\`)`)};a(e(n,"data"),"data","results"),a(e(n,"die"),"die","dieConfig"),a(e(n,"stack"),"stack","lotStack"),a(e(n.dieConfig,"origin"),"dieConfig.origin","dieConfig.coordinateOrigin"),a(e(n.waferConfig,"flat"),"waferConfig.flat","waferConfig.notch"),a(e(n.reticleConfig,"anchor"),"reticleConfig.anchor","reticleConfig.anchorDie"),a(e(n.lotStack,"aggr"),"lotStack.aggr","lotStack.method"),a(Array.isArray(n.testDefs)&&n.testDefs.some(p=>e(p,"index")&&!e(p,"testNumber")),"TestDef.index","TestDef.testNumber");const o=e(n.lotStack,"results")?n.lotStack.results:[],s=(Array.isArray(t)?[t]:[n.results,...Array.isArray(o)?o:[]]).filter(p=>Array.isArray(p));if(a(s.some(p=>p.slice(0,100).some(d=>e(d,"values"))),"values","testValues"),!i.length)return;const r=i.length>1,m=`buildWaferMap ignored ${i.join(", ")}: ${r?"these names were":"that name was"} removed in an earlier release, so what ${r?"they":"it"} described is not on this map. Rename and rebuild.`;return console.warn(`[wafermap] ${m}`),{code:"input-field-removed",message:m,severity:"error"}}function tt(t){if(t.results!==void 0||t.lotStack!==void 0)throw new Error("buildWaferMap: pass `layout`, `results` or `lotStack` \u2014 only one.");const e=t.waferConfig?.diameter,n=t.dieConfig?.width,i=t.dieConfig?.height;if(!(e>0&&n>0&&i>0))throw new Error("buildWaferMap: `layout` needs waferConfig.diameter and dieConfig.width and height, all positive.");const a=U({diameter:e,notch:t.waferConfig?.notch,orientation:0}),o=De(ve(a,{width:n,height:i}),a,{width:n,height:i}).filter(d=>!d.partial),{flipX:s,flipY:r}=le(t.dieConfig,{type:"center"}),{layout:m,...p}=t;return{...p,results:o.map(d=>({x:s?-d.x:d.x,y:r?-d.y:d.y})),waferConfig:{...t.waferConfig,center:{x:0,y:0}},dieConfig:{...t.dieConfig,coordinateOrigin:{type:"center"}}}}function nt(t){if(!Array.isArray(t)&&"results"in t&&t.results!==void 0&&"lotStack"in t&&t.lotStack!==void 0)throw new Error("buildWaferMap: pass either `results` or `lotStack`, not both.");const e={wrongVerdicts:0,wrongValues:0,nonFinite:0,badTestNumbers:[]},n=!Array.isArray(t)&&Te(t.results)?{...t,results:Ee(t.results,e).records}:t,i=et(n,e);return Array.isArray(n)?{results:Z(i.results??n),waferOpts:void 0,dieOpts:void 0,explicitDies:void 0,reticleOpts:void 0,lotStackOpts:void 0,passBins:de(void 0),ringCount:Q(),ringCountWarning:void 0,removedFieldWarning:fe(n),inputValueWarnings:i.warnings,standardDiameters:void 0,testDefs:void 0,hbinDefs:void 0,sbinDefs:void 0,metadataFields:void 0,derivedTests:void 0,retestPolicy:"last",edgeDieYieldMode:"exclude"}:{results:Z(i.results??n.results??[]),waferOpts:i.orientation===void 0||n.waferConfig===void 0?n.waferConfig:{...n.waferConfig,orientation:i.orientation},dieOpts:n.dieConfig,explicitDies:i.dies??n.dies,reticleOpts:n.reticleConfig,lotStackOpts:n.lotStack?{...n.lotStack,results:(i.stackResults??n.lotStack.results).map(Z)}:void 0,passBins:de(n.passBins),...Ze(n.ringCount),removedFieldWarning:fe(n),inputValueWarnings:i.warnings,standardDiameters:n.standardDiameters,testDefs:(i.testDefs??n.testDefs)?.length?i.testDefs??n.testDefs:void 0,hbinDefs:n.hbinDefs,sbinDefs:n.sbinDefs,metadataFields:n.metadataFields,derivedTests:n.derivedTests?.length?n.derivedTests:void 0,retestPolicy:n.retestPolicy??"last",edgeDieYieldMode:n.edgeDieYieldMode??"exclude"}}function Z(t){return t.length>0&&G(t[0])!==void 0?t:ne(t).records}function it(t,e){return e?.coordinateOrigin?e.coordinateOrigin:{type:"center"}}function st(t,e,n){if(e.type==="custom"&&e.offset)return{offsetX:e.offset.x,offsetY:e.offset.y};if(e.type!=="center"){let i=1/0,a=-1/0,o=1/0,s=-1/0;for(const r of t)r.x<i&&(i=r.x),r.x>a&&(a=r.x),r.y<o&&(o=r.y),r.y>s&&(s=r.y);return{offsetX:Math.round((a+i)/2),offsetY:Math.round((s+o)/2)}}return{offsetX:n.offsetX,offsetY:n.offsetY}}function rt(t,e,n,i,a,o){if(o)return{colMidX:(Math.round(o.x)-e)*i,colMidY:(Math.round(o.y)-n)*a,anchored:!0};if(t.length===0)return{colMidX:0,colMidY:0,anchored:!1};let s=1/0,r=-1/0,m=1/0,p=-1/0;for(const d of t){const c=Math.round(d.x)-e,h=Math.round(d.y)-n;c<s&&(s=c),c>r&&(r=c),h<m&&(m=h),h>p&&(p=h)}return{colMidX:(s+r)/2*i,colMidY:(m+p)/2*a,anchored:!1}}function ot(t,e,n){let i=1/0,a=-1/0,o=1/0,s=-1/0,r=0,m=0;for(const c of t){const h=Math.round(c.x)-e,l=Math.round(c.y)-n;r+=h,m+=l,h<i&&(i=h),h>a&&(a=h),l<o&&(o=l),l>s&&(s=l)}const p=t.length,d=(c,h,l)=>{const x=(l-h)/2;return x<=0?0:Math.abs(c/p-(h+l)/2)/x};return d(r,i,a)>.11||d(m,o,s)>.11}function le(t,e){let n=t?.xAxisDirection==="left",i=t?.yAxisDirection==="down";return(e.type==="UL"||e.type==="UR")&&(i=!0),(e.type==="LR"||e.type==="UR")&&(n=!0),{flipX:n,flipY:i}}function at(t){const e={...t};return delete e.limitLow,delete e.limitHigh,delete e.limitLowInclusive,delete e.limitHighInclusive,delete e.specLow,delete e.specHigh,e}function dt(t,e){const{method:n,targetBin:i}=t,a=t.results.map(o=>o.filter(F));if(n==="mean"||n==="median"||n==="stddev"||n==="min"||n==="max"||n==="count"){const o=new Set((e??[]).filter(d=>!isParametricTest(d)).map(d=>d.testNumber)),s=new Set;for(const d of a)for(const c of Oe(d,"values"))o.has(c)||s.add(c);if(s.size===0)return ae(a,n);const r=[...s],m=r.map(d=>ae(a,n,d)),p=new Map;for(let d=0;d<r.length;d++){const c=r[d];for(const h of m[d]){const l=X(h);p.has(l)||p.set(l,{template:h,testValues:{}});const x=p.get(l),D=h.testValues?.[0];D!==void 0&&(x.testValues[c]=D)}}return[...p.values()].map(({template:d,testValues:c})=>({...d,testValues:Ge(c)?c:void 0}))}if(n==="countBin"||n==="percent"){if(i===void 0)return[];const o=Je(a,i,"hard");if(n==="countBin")return o;const s=a.length;return o.map(r=>({...r,testValues:{0:s>0?(r.testValues?.[0]??0)/s*100:0}}))}if(n==="mode"){const o=new Map;for(const r of a)for(const m of r){const p=X(m);o.has(p)||o.set(p,[]),o.get(p).push(m)}const s=[];for(const[r,m]of o){const p=r.split(","),d=Number(p[0]),c=Number(p[1]),h=m.map(x=>x.hbin).filter(x=>x!==void 0),l=qe(h);l!==null&&s.push({x:d,y:c,hbin:l})}return s}return[]}function ue(t){const e=t.filter(F),n=e.length,i=e.filter(o=>o.edgeExcluded).length,a=e.filter(o=>o.hbin!==void 0||o.sbin!==void 0||dieHasTestData(o)).length;return{filledDies:a,totalDies:n,edgeExcludedDies:i,unpositionedDies:t.length-e.length,ratio:n>0?a/n:0}}function ce(t,e,n="exclude"){const i=new Set(e),o=t.filter(l=>!l.partial).filter(l=>l.edgeExcluded).length,s=t.filter(l=>l.partial).length;let r=0,m=0,p=!1;for(const l of t){if(!we(l))continue;const x=l.hbin??l.sbin;x!==void 0&&(p=!0,i.has(x)?r++:m++)}const d=r+m,c=p&&d>0?r/d*100:null;let h=null;if(n==="denominator-only"){const l=d+o;h=p&&l>0?r/l*100:null}return{passDies:r,failDies:m,edgeExcludedDies:o,partialDies:s,totalDies:d,yieldPercent:c,yieldPercentGross:h}}function pe(t,e,n,i,a,o=0,s=0,r=0,m=0,p=0,d=!1,c=!1){if(!t)return[];const h=t.anchorDie??{x:0,y:0},l=Ye(e,{width:t.width,height:t.height,diePitchX:i,diePitchY:a,anchorDie:{x:h.x-o,y:h.y-s},gridOrigin:{x:-r,y:-m}}),x=_e(Ie(d,c,e.center.x,e.center.y),Fe(p,e.center.x,e.center.y));return l.filter(D=>{const u=D.width/2,b=D.height/2,w=[[D.x-u,D.y-b],[D.x+u,D.y-b],[D.x+u,D.y+b],[D.x-u,D.y+b]].map(([v,N])=>Pe(x,v,N)),g=oe(w.map(v=>v.x)),y=J(w.map(v=>v.x)),A=oe(w.map(v=>v.y)),R=J(w.map(v=>v.y));return n.some(v=>v.physX>=g&&v.physX<y&&v.physY>=A&&v.physY<R)})}function ft(t,e,n){const a=Math.max(0,e.radius-n)**2;return t.map(o=>{const s=o.physX-e.center.x,r=o.physY-e.center.y;return s*s+r*r>a?{...o,edgeExcluded:!0}:o})}const lt=.2;function ut(t,e,n){const i=new Set(n);function a(g,y){if(e==="last")return!0;if(e==="first")return!1;const A=K(g.hbin),R=K(y.hbin);if(A===void 0||R===void 0)return!1;const v=i.has(A),N=i.has(R);return e==="best"?N!==v?N:R<A:N!==v?v:R>A}const o=(g,y)=>y.supersedes!==void 0||a(g,y),s=g=>{const y=g.partId===void 0?"":String(g.partId).trim();return y===""?void 0:y},r=t.filter(g=>!F(g)),m=new Map;for(const g of r){const y=s(g);y!==void 0&&m.set(y,(m.get(y)??0)+1)}const d=(r.length===0?0:Math.max(0,...m.values())/r.length)<=lt,c=new Map,h=[],l=new Map;let x=0,D=0;for(const g of t){const y=s(g);let A;if(F(g)?A=`p:${X(g)}`:d&&y!==void 0?A=`i:${y}`:A=`u:${D++}`,g.supersedes==="partId"&&y!==void 0){const v=l.get(y);v!==void 0&&v!==A&&c.has(v)&&c.delete(v)}const R=c.get(A);R===void 0?(c.set(A,{winner:g,count:1}),h.push(A)):(R.count++,A.startsWith("i:")&&x++,o(R.winner,g)&&(R.winner=g)),y!==void 0&&l.set(y,A)}const u=[],b=[...h.filter(g=>g.startsWith("p:")),...h.filter(g=>!g.startsWith("p:"))];for(const g of b){const y=c.get(g);y!==void 0&&u.push(y.count>1?{...y.winner,retestCount:y.count}:y.winner)}const w=x>0?{code:"retests-by-part-id",severity:"info",message:`${x} record${x===1?"":"s"} with no position shared a part ID with an earlier record and ${x===1?"was":"were"} treated as a retest of it.`}:void 0;return{results:u,warning:w}}export function getDieTestValue(t,e){return q(t,e)}export function getTestPassStatus(t,e,n){const i=Ce(t,e);return i!==void 0?i:n!==void 0&&!isParametricTest(n)?he(q(t,e)):void 0}function he(t){return t===0||t===1?t===1:void 0}export function testPassStatusReader(t){const e=t.map(a=>a.testNumber),n=ke(e),i=t.map(a=>!isParametricTest(a));return function(o,s){n(o,s);for(let r=0;r<s.length;r++){if(s[r]!==$e||!i[r])continue;const m=he(q(o,e[r]));m!==void 0&&(s[r]=m?Re:Ne)}return s}}export function dieHasTestData(t){return Me(t)}function K(t){return t===void 0||Number.isNaN(t)?void 0:t}function H(t,e){const n={},i=K(e.hbin),a=K(e.sbin);i!==void 0&&(n.hbin=i),a!==void 0&&(n.sbin=a),e.retestCount!==void 0&&(n.retestCount=e.retestCount),e.siteNum!==void 0&&(n.siteNum=e.siteNum),e.partId!==void 0&&(n.partId=e.partId),e.metadata!==void 0&&(n.metadata=e.metadata);const o=G(e);return Se({...t,...n},o.table,o.row)}function me(t){return t.some(dieHasTestData)?"value":"hardBin"}function ge(t,e){return t.map(({code:n,message:i})=>({code:n,message:i,severity:n==="non-standard-diameter"||n==="diameter-exceeds-die-extent"?"warning":"error",confidence:e.wafer.confidence}))}const ct="do not fit inside the supplied",pt="Inferred wafer diameter",ht="The probed dies reach only",mt=.75,gt=20;export const STANDARD_WAFER_DIAMETERS_MM=[100,125,150,200,300];const yt=.02;function ye(t,e){return e.reduce((n,i)=>Math.abs(i-t)<Math.abs(n-t)?i:n)}function bt(t,e){if(!e.length)return!0;const n=ye(t,e);return Math.abs(n-t)/n<=yt}function wt(t){return t===void 0?STANDARD_WAFER_DIAMETERS_MM:t.filter(e=>Number.isFinite(e)&&e>0)}export function buildWaferMap(t){const e=nt(!Array.isArray(t)&&t.layout?tt(t):t),n=[];if(e.derivedTests){const f=new Set(e.passBins),C=$=>{const E=$.length>0?G($[0]):void 0,W=Xe($,E?.table??Ae([]),e.testDefs,e.derivedTests,f);return E&&We($,W.table),W},S=(e.lotStackOpts?e.lotStackOpts.results:[e.results]).map(C);e.testDefs=S[0]?.testDefs??e.testDefs,n.push(...S[0]?.warnings??[])}e.lotStackOpts&&!Qe(e.lotStackOpts.method)&&(e.testDefs=e.testDefs?.map(at));const i=e.lotStackOpts?ne(dt(e.lotStackOpts,e.testDefs)).records:e.results;for(let f=0;f<Math.min(5,i.length);f++){const C=i[f];if(typeof C.x=="string"||typeof C.y=="string")throw new TypeError("buildWaferMap: x and y must be numbers, received strings. Did you forget to cast CSV values? e.g. { x: +row.x, y: +row.y }")}for(const f of i)if(f.x==null!=(f.y==null))throw new TypeError(`buildWaferMap: die has only one of x/y set (x=${String(f.x)}, y=${String(f.y)}). A die must be either fully positioned (both x and y) or fully unpositioned (neither) \u2014 omit both to mark a die as having no reported position.`);const{results:a,warning:o}=ut(i,e.retestPolicy,e.passBins),s={wafer:{confidence:1,method:"provided"},diePitch:{confidence:1,units:"mm"},grid:{confidence:1}},r=[];if(e.explicitDies){let f=e.explicitDies.filter(F);const C=e.explicitDies.filter(V=>!F(V)),T=a.filter(F),S=a.filter(V=>!F(V));if(T.length>0){const V=new Map(T.map(P=>[X(P),P]));f=f.map(P=>{const ee=V.get(X(P));return ee?H(P,ee):P})}const $=e.waferOpts?.diameter??300,E=U({diameter:$,notch:e.waferOpts?.notch,orientation:e.waferOpts?.orientation??0,metadata:e.waferOpts?.metadata,reticle:e.reticleOpts});E.orientation!==0&&(f=te(f,E)),f=f.map(j);const W=pe(e.reticleOpts,E,f,1,1,0,0,0,0,E.orientation),be=S.map((V,P)=>j(H({id:`unpositioned_${P}`,width:f[0]?.width??1,height:f[0]?.height??1},V))),z=[...f,...C,...be];return{wafer:E,dies:z,dataAxisFlip:{x:!1,y:!1},reticleConfig:e.reticleOpts,units:"mm",inference:s,warnings:[...e.removedFieldWarning?[e.removedFieldWarning]:[],...e.inputValueWarnings,...o?[o]:[],...ge(r,s),...n,...e.ringCountWarning?[e.ringCountWarning]:[]],plotMode:me(a),metadata:E.metadata??null,isLotStack:!1,dataCoverage:ue(z),passBins:e.passBins,ringCount:e.ringCount,yield:ce(z,e.passBins,e.edgeDieYieldMode),reticles:W,hbinDefs:e.hbinDefs,sbinDefs:e.sbinDefs,testDefs:e.testDefs,metadataFields:e.metadataFields}}const m=a.filter(F),p=a.filter(f=>!F(f)),d=m.map(f=>({x:f.x,y:f.y})),c=Be(d,e.dieOpts,e.waferOpts?.diameter);s.diePitch={confidence:c.confidence,units:c.units};const{pitchX:h,pitchY:l}=c,x=c.units,D=it(m,e.dieOpts),u=Le(d);s.grid={confidence:u.confidence};const{offsetX:b,offsetY:w}=st(d,D,u),{flipX:g,flipY:y}=le(e.dieOpts,D),{colMidX:A,colMidY:R,anchored:v}=rt(d,b,w,h,l,e.waferOpts?.center);let N=e.waferOpts?.diameter;const B=d.map(f=>({x:(Math.round(f.x)-b)*h-A,y:(Math.round(f.y)-w)*l-R})),I=J(B.map(({x:f,y:C})=>Math.hypot(Math.abs(f)+h/2,Math.abs(C)+l/2)));if(N===void 0)if(d.length>0)if(x==="mm"){const f=Ve(B,{minRadius:I});N=f.diameter,s.wafer={confidence:f.confidence,method:f.method};const C=wt(e.standardDiameters);if(!bt(N,C)){const T=ye(N,C);r.push({code:"non-standard-diameter",message:`${pt} ${N.toFixed(1)} mm is not a standard wafer size (nearest is ${T} mm). The diameter was derived from the die extent, which assumes the probed grid reaches the wafer edge \u2014 a non-standard result usually means it does not, because the outer dies were never probed. Every die is then placed against a wafer that is too small, which moves dies between rings and changes ring and edge findings. Supply waferConfig.diameter.`})}}else N=I*2,s.wafer={confidence:c.confidence*.8,method:"extent"};else N=x==="mm"?300:30,s.wafer={confidence:0,method:"default"};if(!v&&d.length>0&&ot(d,b,w)&&(s.wafer.method="inferred-partial",r.push({code:"partial-coverage",message:"Wafer geometry was inferred from die positions alone. The data does not span a full symmetric wafer, so the inferred diameter and centre may be wrong and dies may be mis-positioned relative to the true wafer boundary. Supply waferConfig.diameter and waferConfig.center (the prober coordinate of the wafer centre) to position partial data correctly."})),e.waferOpts?.diameter!==void 0&&e.waferOpts.center===void 0&&I>0&&d.length>=gt){const f=I/(N/2);f<mt&&r.push({code:"diameter-exceeds-die-extent",message:`${ht} ${(f*100).toFixed(0)}% of the ${N} mm wafer's radius. Either the diameter is larger than the real one, or this is a partial map covering only part of the wafer. Ring bands are equal-radius, so the outer rings are mostly or entirely empty and ring, quadrant and edge findings describe the assumed wafer rather than the probed area. Check waferConfig.diameter, or drop it and let the diameter be inferred from the die extent.`})}if(e.waferOpts?.diameter!==void 0){const f=e.dieOpts?.width!==void 0&&e.dieOpts?.height!==void 0;if(f&&I>N/2+1e-9){const C=B.filter(({x:T,y:S})=>Math.hypot(Math.abs(T)+h/2,Math.abs(S)+l/2)>N/2+1e-9).length;r.push({code:"geometry-conflict",message:`${C} of ${B.length} probed die positions ${ct} ${N} mm wafer at the supplied die pitch of ${h} \xD7 ${l} mm. A die with test results is a real prober position and is always fully on the wafer, so one of the two supplied values must be wrong: containing these dies at this pitch would need a diameter of at least ${(I*2).toFixed(1)} mm. Check waferConfig.diameter and dieConfig.width/height against the real device.`})}}const O=U({diameter:N,notch:e.waferOpts?.notch,orientation:e.waferOpts?.orientation??0,metadata:e.waferOpts?.metadata,reticle:e.reticleOpts});let k=m.map(f=>{const C=Math.round(f.x)-b,T=Math.round(f.y)-w,S={id:`${C}_${T}`,x:C,y:T,physX:C*h-A,physY:T*l-R,width:h,height:l,insideWafer:!0,partial:!1};return H(S,f)});(b!==0||w!==0)&&(k=k.map(f=>({...f,x:f.x+b,y:f.y+w,id:`${f.x+b}_${f.y+w}`}))),k=te(k,O),(g||y)&&(k=xe(k,{flipX:g,flipY:y},O.center));const M=[];e.waferOpts?.edgeExclusion&&e.waferOpts.edgeExclusion>0&&(k=ft(k,O,e.waferOpts.edgeExclusion),e.waferOpts.edgeExclusion>O.radius&&M.push({code:"edge-exclusion-exceeds-radius",message:`edgeExclusion (${e.waferOpts.edgeExclusion}mm) exceeds the resolved wafer radius (${O.radius}mm) \u2014 the entire wafer is excluded.`,severity:"warning"})),k=k.map(j);const Y=pe(e.reticleOpts,O,k,h,l,b,w,A,R,O.orientation,g,y),_=p.map((f,C)=>j(H({id:`unpositioned_${C}`,width:h,height:l},f))),L=[...k,..._];return{wafer:O,dies:L,dataAxisFlip:{x:g,y},reticleConfig:e.reticleOpts,units:x,inference:s,warnings:[...e.removedFieldWarning?[e.removedFieldWarning]:[],...e.inputValueWarnings,...o?[o]:[],...ge(r,s),...M,...n,...e.ringCountWarning?[e.ringCountWarning]:[]],plotMode:me(a),metadata:O.metadata??null,isLotStack:e.lotStackOpts!==void 0,dataCoverage:ue(L),passBins:e.passBins,ringCount:e.ringCount,yield:ce(L,e.passBins,e.edgeDieYieldMode),reticles:Y,hbinDefs:e.hbinDefs,sbinDefs:e.sbinDefs,testDefs:e.testDefs,metadataFields:e.metadataFields,aggrMethod:e.lotStackOpts?.method,lotSize:e.lotStackOpts?.results.length}}
1
+ import{createWafer as q}from"../core/wafer.js";import{isYieldEligibleDie as De,getDieKey as Y,hasPosition as E}from"../core/dies.js";import{applyOrientation as ne,transformDies as ve,clipDiesToWafer as Me}from"../core/transforms.js";import{generateDies as Se}from"../core/dies.js";import{dieHasAnyTestData as Ce,dieLink as K,finaliseDie as H,linkDie as ke,recordedVerdict as Oe,recordedVerdictsReader as Ae,tableFromRows as Ne,testValue as J,testsPresent as $e,VERDICT_FAIL as Fe,VERDICT_NONE as Re,VERDICT_PASS as Te}from"../core/dieTable.js";import{isDieColumns as Ee,linkColumns as We,linkRows as ie,relink as se}from"./columnarInput.js";import{affineRotation as Ie,affineMirror as _e,affineCompose as Pe,affinePoint as Ve}from"../core/transforms.js";import{inferWaferFromXY as Be}from"../core/inference/wafer.js";import{resolveGridPitch as Le}from"../core/inference/pitch.js";import{assignGridIndices as Ye}from"../core/inference/grid.js";import{generateReticleGrid as Xe}from"../core/reticle.js";import{applyDerivedTests as je}from"./derivedTests/apply.js";import{isStdfBin as Ke,isStdfCoord as re,isStdfTestNumber as oe,isStdfSite as He,STDF_BIN_MAX as ze,STDF_COORD_MAX as ae,STDF_TEST_NUM_MAX as Ue,STDF_SITE_MAX as Ge}from"../core/stdf.js";import{hasAnyKey as qe,maxOf as Q,minOf as de,modeOf as Je}from"../core/utils.js";import{aggregateValues as fe,aggregateBinCounts as Qe,stackHoldsMeasurements as Ze}from"../core/aggregates.js";import{normalizePassBins as le}from"../core/passBins.js";import{defaultRingCount as Z}from"../core/ringCount.js";import{applyValueFilter as et,mergeValueFilterTests as tt,valueFilterWarning as nt}from"./valueFilter.js";export function isParametricTest(t){return t?.testType!=="F"}export function isBuiltMap(t){return"wafer"in t&&"dies"in t&&"dataAxisFlip"in t}function it(t){const e=(i,d)=>({ringCount:i,ringCountWarning:{code:"analysis-option-corrected",severity:"warning",message:`ringCount=${String(t)} ${d} (using ${i}).`}});if(t===void 0)return{ringCount:Z(),ringCountWarning:void 0};if(typeof t!="number"||!Number.isFinite(t))return e(Z(),"is not a finite number");const n=Math.max(1,Math.round(t));return n===t?{ringCount:t,ringCountWarning:void 0}:e(n,"is not a whole number of at least 1")}function st(t,e){const n=Array.isArray(t)?{}:t,i={hbin:0,sbin:0,siteNum:0,testValues:0,testPass:0};let d;const r=(c,S)=>{i[c]++,d??=`${c} ${JSON.stringify(S)}`},a={bins:0,positions:0,values:0,sites:0,orientation:0},s=new Set;let h=0;if(e){i.testValues+=e.wrongValues,i.testPass+=e.wrongVerdicts,e.example!==void 0&&(d??=e.example),a.values+=e.nonFinite;for(const c of e.badTestNumbers)s.add(c)}const p=c=>c==null?!0:typeof c!="number"?!1:Number.isNaN(c)?(h++,!1):Ke(c)?!0:(a.bins++,!1);function u(c){const S=new Set,D=new Set;for(let $=0;$<c.length;$+=$<50?1:100){const A=c[$];if(!(A===null||typeof A!="object")){if(A.testValues&&typeof A.testValues=="object")for(const w of Object.keys(A.testValues))S.add(w);if(A.testPass&&typeof A.testPass=="object")for(const w of Object.keys(A.testPass))D.add(w)}}const m=[...S],b=[...D],O=$=>oe(Number($));for(const $ of new Set([...m,...b]))O($)||s.add($);const F=m.map(O),M=b.map(O),W=m.map(Number),T=b.map(Number);let P;for(let $=0;$<c.length;$++){const A=c[$];if(A===null||typeof A!="object")continue;const w=A;let B;const I=()=>B??={...w};w.hbin!=null&&typeof w.hbin!="number"&&r("hbin",w.hbin),w.sbin!=null&&typeof w.sbin!="number"&&r("sbin",w.sbin),p(w.hbin)||(I().hbin=void 0),p(w.sbin)||(I().sbin=void 0);const X=typeof w.x=="number"&&!re(w.x),L=typeof w.y=="number"&&!re(w.y);if(X||L){a.positions+=(X?1:0)+(L?1:0);const x=I();x.x=void 0,x.y=void 0}w.siteNum!=null&&typeof w.siteNum!="number"?(r("siteNum",w.siteNum),I().siteNum=void 0):typeof w.siteNum=="number"&&!He(w.siteNum)&&(a.sites++,I().siteNum=void 0);const o=w.testValues;if(o&&typeof o=="object"){let x;for(let k=0;k<m.length;k++){const R=m[k],N=o[W[k]];if(N!=null){if(!F[k]){x??={...o},delete x[R];continue}typeof N!="number"?(r("testValues",N),x??={...o},delete x[R]):Number.isFinite(N)||(a.values++,x??={...o},delete x[R])}}x&&(I().testValues=x)}const C=w.testPass;if(C&&typeof C=="object"){let x;for(let k=0;k<b.length;k++){const R=b[k],N=C[T[k]];if(N!=null){if(!M[k]){x??={...C},delete x[R];continue}typeof N!="boolean"&&(r("testPass",N),x??={...C},delete x[R])}}x&&(I().testPass=x)}B&&((P??=c.slice())[$]=B)}return P}const l={warnings:[]};if(Array.isArray(t))l.results=u(t);else{Array.isArray(n.results)&&(l.results=u(n.results)),Array.isArray(n.dies)&&(l.dies=u(n.dies));const c=n.lotStack?.results;if(Array.isArray(c)){const S=c.map(D=>Array.isArray(D)?u(D):void 0);S.some(Boolean)&&(l.stackResults=S.map((D,m)=>D??c[m]))}}if(Array.isArray(n.testDefs)){const c=n.testDefs,S=c.filter(D=>D==null||typeof D.testNumber!="number"||oe(D.testNumber));for(const D of c)S.includes(D)||s.add(String(D.testNumber));S.length!==c.length&&(l.testDefs=S)}const g=n.waferConfig?.orientation;if(typeof g=="number"){const c=Number.isFinite(g)?(g%360+360)%360:NaN;c===0||c===90||c===180||c===270?l.orientation=c:(a.orientation++,l.orientation=0)}const f=(c,S,D=`${S}s`)=>`${c} ${c===1?S:D}`,y=[];if(i.hbin&&y.push(f(i.hbin,"hard bin")),i.sbin&&y.push(f(i.sbin,"soft bin")),i.siteNum&&y.push(f(i.siteNum,"site number")),i.testValues&&y.push(f(i.testValues,"test value")),i.testPass&&y.push(f(i.testPass,"pass/fail verdict")),y.length){const c=`buildWaferMap received ${y.join(", ")} of the wrong type (for example ${d}), treated as missing. Bins, sites and test values must be numbers and verdicts true/false \u2014 a bin of "1" is not pass bin 1 \u2014 so those dies have no bin, no site, no value or no verdict, and yield and every chart leave them out. Convert them with Number() (and verdicts to booleans) and rebuild.`;console.warn(`[wafermap] ${c}`),l.warnings.push({code:"input-values-not-numbers",message:c,severity:"error"})}const v=[];if(a.bins&&v.push(`${f(a.bins,"bin")} (legal: whole numbers 0\u2013${ze}) \u2014 those dies have no bin`),a.positions&&v.push(`${f(a.positions,"coordinate")} (legal: whole numbers \u2212${ae} to ${ae}) \u2014 those dies have no position`),s.size&&v.push(`${f(s.size,"test number")} (legal: whole numbers 0\u2013${Ue}) \u2014 those tests are left out`),a.values&&v.push(`${f(a.values,"test value")} that ${a.values===1?"is":"are"} not finite \u2014 left out`),a.sites&&v.push(`${f(a.sites,"site number")} (legal: 0\u2013${Ge}) \u2014 those dies have no site`),a.orientation&&v.push("a waferConfig.orientation other than 0, 90, 180 or 270 \u2014 the map is built at 0"),v.length||h){const c=[];v.length&&c.push(`buildWaferMap received values outside the STDF V4 ranges, treated as missing: ${v.join("; ")}.`),h&&c.push(`${f(h,"bin was","bins were")} NaN and ${h===1?"is":"are"} treated as no bin.`);const S=c.join(" ");console.warn(`[wafermap] ${S}`),l.warnings.push({code:"input-values-outside-stdf",message:S,severity:"warning"})}return l}function ue(t){const e=(p,u)=>p!==null&&typeof p=="object"&&p[u]!==void 0,n=Array.isArray(t)?{}:t,i=[],d=(p,u,l)=>{p&&i.push(`\`${u}\` (now \`${l}\`)`)};d(e(n,"data"),"data","results"),d(e(n,"die"),"die","dieConfig"),d(e(n,"stack"),"stack","lotStack"),d(e(n.dieConfig,"origin"),"dieConfig.origin","dieConfig.coordinateOrigin"),d(e(n.waferConfig,"flat"),"waferConfig.flat","waferConfig.notch"),d(e(n.reticleConfig,"anchor"),"reticleConfig.anchor","reticleConfig.anchorDie"),d(e(n.lotStack,"aggr"),"lotStack.aggr","lotStack.method"),d(Array.isArray(n.testDefs)&&n.testDefs.some(p=>e(p,"index")&&!e(p,"testNumber")),"TestDef.index","TestDef.testNumber");const r=e(n.lotStack,"results")?n.lotStack.results:[],a=(Array.isArray(t)?[t]:[n.results,...Array.isArray(r)?r:[]]).filter(p=>Array.isArray(p));if(d(a.some(p=>p.slice(0,100).some(u=>e(u,"values"))),"values","testValues"),!i.length)return;const s=i.length>1,h=`buildWaferMap ignored ${i.join(", ")}: ${s?"these names were":"that name was"} removed in an earlier release, so what ${s?"they":"it"} described is not on this map. Rename and rebuild.`;return console.warn(`[wafermap] ${h}`),{code:"input-field-removed",message:h,severity:"error"}}function rt(t){if(t.results!==void 0||t.lotStack!==void 0)throw new Error("buildWaferMap: pass `layout`, `results` or `lotStack` \u2014 only one.");const e=t.waferConfig?.diameter,n=t.dieConfig?.width,i=t.dieConfig?.height;if(!(e>0&&n>0&&i>0))throw new Error("buildWaferMap: `layout` needs waferConfig.diameter and dieConfig.width and height, all positive.");const d=q({diameter:e,notch:t.waferConfig?.notch,orientation:0}),r=Me(Se(d,{width:n,height:i}),d,{width:n,height:i}).filter(u=>!u.partial),{flipX:a,flipY:s}=ce(t.dieConfig,{type:"center"}),{layout:h,...p}=t;return{...p,results:r.map(u=>({x:a?-u.x:u.x,y:s?-u.y:u.y})),waferConfig:{...t.waferConfig,center:{x:0,y:0}},dieConfig:{...t.dieConfig,coordinateOrigin:{type:"center"}}}}function ot(t){if(!Array.isArray(t)&&"results"in t&&t.results!==void 0&&"lotStack"in t&&t.lotStack!==void 0)throw new Error("buildWaferMap: pass either `results` or `lotStack`, not both.");const e={wrongVerdicts:0,wrongValues:0,nonFinite:0,badTestNumbers:[]},n=!Array.isArray(t)&&Ee(t.results)?{...t,results:We(t.results,e).records}:t,i=st(n,e);return Array.isArray(n)?{results:ee(i.results??n),waferOpts:void 0,dieOpts:void 0,explicitDies:void 0,reticleOpts:void 0,lotStackOpts:void 0,passBins:le(void 0),ringCount:Z(),valueFilter:"validity",ringCountWarning:void 0,removedFieldWarning:ue(n),inputValueWarnings:i.warnings,standardDiameters:void 0,testDefs:void 0,hbinDefs:void 0,sbinDefs:void 0,metadataFields:void 0,derivedTests:void 0,retestPolicy:"last",edgeDieYieldMode:"exclude"}:{results:ee(i.results??n.results??[]),waferOpts:i.orientation===void 0||n.waferConfig===void 0?n.waferConfig:{...n.waferConfig,orientation:i.orientation},dieOpts:n.dieConfig,explicitDies:i.dies??n.dies,reticleOpts:n.reticleConfig,lotStackOpts:n.lotStack?{...n.lotStack,results:(i.stackResults??n.lotStack.results).map(ee)}:void 0,passBins:le(n.passBins),valueFilter:n.valueFilter??"validity",...it(n.ringCount),removedFieldWarning:ue(n),inputValueWarnings:i.warnings,standardDiameters:n.standardDiameters,testDefs:(i.testDefs??n.testDefs)?.length?i.testDefs??n.testDefs:void 0,hbinDefs:n.hbinDefs,sbinDefs:n.sbinDefs,metadataFields:n.metadataFields,derivedTests:n.derivedTests?.length?n.derivedTests:void 0,retestPolicy:n.retestPolicy??"last",edgeDieYieldMode:n.edgeDieYieldMode??"exclude"}}function ee(t){return t.length>0&&K(t[0])!==void 0?t:ie(t).records}function at(t,e){return e?.coordinateOrigin?e.coordinateOrigin:{type:"center"}}function dt(t,e,n){if(e.type==="custom"&&e.offset)return{offsetX:e.offset.x,offsetY:e.offset.y};if(e.type!=="center"){let i=1/0,d=-1/0,r=1/0,a=-1/0;for(const s of t)s.x<i&&(i=s.x),s.x>d&&(d=s.x),s.y<r&&(r=s.y),s.y>a&&(a=s.y);return{offsetX:Math.round((d+i)/2),offsetY:Math.round((a+r)/2)}}return{offsetX:n.offsetX,offsetY:n.offsetY}}function ft(t,e,n,i,d,r){if(r)return{colMidX:(Math.round(r.x)-e)*i,colMidY:(Math.round(r.y)-n)*d,anchored:!0};if(t.length===0)return{colMidX:0,colMidY:0,anchored:!1};let a=1/0,s=-1/0,h=1/0,p=-1/0;for(const u of t){const l=Math.round(u.x)-e,g=Math.round(u.y)-n;l<a&&(a=l),l>s&&(s=l),g<h&&(h=g),g>p&&(p=g)}return{colMidX:(a+s)/2*i,colMidY:(h+p)/2*d,anchored:!1}}function lt(t,e,n){let i=1/0,d=-1/0,r=1/0,a=-1/0,s=0,h=0;for(const l of t){const g=Math.round(l.x)-e,f=Math.round(l.y)-n;s+=g,h+=f,g<i&&(i=g),g>d&&(d=g),f<r&&(r=f),f>a&&(a=f)}const p=t.length,u=(l,g,f)=>{const y=(f-g)/2;return y<=0?0:Math.abs(l/p-(g+f)/2)/y};return u(s,i,d)>.11||u(h,r,a)>.11}function ce(t,e){let n=t?.xAxisDirection==="left",i=t?.yAxisDirection==="down";return(e.type==="UL"||e.type==="UR")&&(i=!0),(e.type==="LR"||e.type==="UR")&&(n=!0),{flipX:n,flipY:i}}function ut(t){const e={...t};return delete e.limitLow,delete e.limitHigh,delete e.limitLowInclusive,delete e.limitHighInclusive,delete e.specLow,delete e.specHigh,e}function ct(t,e){const{method:n,targetBin:i}=t,d=t.results.map(r=>r.filter(E));if(n==="mean"||n==="median"||n==="stddev"||n==="min"||n==="max"||n==="count"){const r=new Set((e??[]).filter(u=>!isParametricTest(u)).map(u=>u.testNumber)),a=new Set;for(const u of d)for(const l of $e(u,"values"))r.has(l)||a.add(l);if(a.size===0)return fe(d,n);const s=[...a],h=s.map(u=>fe(d,n,u)),p=new Map;for(let u=0;u<s.length;u++){const l=s[u];for(const g of h[u]){const f=Y(g);p.has(f)||p.set(f,{template:g,testValues:{}});const y=p.get(f),v=g.testValues?.[0];v!==void 0&&(y.testValues[l]=v)}}return[...p.values()].map(({template:u,testValues:l})=>({...u,testValues:qe(l)?l:void 0}))}if(n==="countBin"||n==="percent"){if(i===void 0)return[];const r=Qe(d,i,"hard");if(n==="countBin")return r;const a=d.length;return r.map(s=>({...s,testValues:{0:a>0?(s.testValues?.[0]??0)/a*100:0}}))}if(n==="mode"){const r=new Map;for(const s of d)for(const h of s){const p=Y(h);r.has(p)||r.set(p,[]),r.get(p).push(h)}const a=[];for(const[s,h]of r){const p=s.split(","),u=Number(p[0]),l=Number(p[1]),g=h.map(y=>y.hbin).filter(y=>y!==void 0),f=Je(g);f!==null&&a.push({x:u,y:l,hbin:f})}return a}return[]}function pe(t){const e=t.filter(E),n=e.length,i=e.filter(r=>r.edgeExcluded).length,d=e.filter(r=>r.hbin!==void 0||r.sbin!==void 0||dieHasTestData(r)).length;return{filledDies:d,totalDies:n,edgeExcludedDies:i,unpositionedDies:t.length-e.length,ratio:n>0?d/n:0}}function he(t,e,n="exclude"){const i=new Set(e),r=t.filter(f=>!f.partial).filter(f=>f.edgeExcluded).length,a=t.filter(f=>f.partial).length;let s=0,h=0,p=!1;for(const f of t){if(!De(f))continue;const y=f.hbin??f.sbin;y!==void 0&&(p=!0,i.has(y)?s++:h++)}const u=s+h,l=p&&u>0?s/u*100:null;let g=null;if(n==="denominator-only"){const f=u+r;g=p&&f>0?s/f*100:null}return{passDies:s,failDies:h,edgeExcludedDies:r,partialDies:a,totalDies:u,yieldPercent:l,yieldPercentGross:g}}function me(t,e,n,i,d,r=0,a=0,s=0,h=0,p=0,u=!1,l=!1){if(!t)return[];const g=t.anchorDie??{x:0,y:0},f=Xe(e,{width:t.width,height:t.height,diePitchX:i,diePitchY:d,anchorDie:{x:g.x-r,y:g.y-a},gridOrigin:{x:-s,y:-h}}),y=Pe(_e(u,l,e.center.x,e.center.y),Ie(p,e.center.x,e.center.y));return f.filter(v=>{const c=v.width/2,S=v.height/2,D=[[v.x-c,v.y-S],[v.x+c,v.y-S],[v.x+c,v.y+S],[v.x-c,v.y+S]].map(([M,W])=>Ve(y,M,W)),m=de(D.map(M=>M.x)),b=Q(D.map(M=>M.x)),O=de(D.map(M=>M.y)),F=Q(D.map(M=>M.y));return n.some(M=>M.physX>=m&&M.physX<b&&M.physY>=O&&M.physY<F)})}function pt(t,e,n){const d=Math.max(0,e.radius-n)**2;return t.map(r=>{const a=r.physX-e.center.x,s=r.physY-e.center.y;return a*a+s*s>d?{...r,edgeExcluded:!0}:r})}const ht=.2;function mt(t,e,n){const i=new Set(n);function d(m,b){if(e==="last")return!0;if(e==="first")return!1;const O=z(m.hbin),F=z(b.hbin);if(O===void 0||F===void 0)return!1;const M=i.has(O),W=i.has(F);return e==="best"?W!==M?W:F<O:W!==M?M:F>O}const r=(m,b)=>b.supersedes!==void 0||d(m,b),a=m=>{const b=m.partId===void 0?"":String(m.partId).trim();return b===""?void 0:b},s=t.filter(m=>!E(m)),h=new Map;for(const m of s){const b=a(m);b!==void 0&&h.set(b,(h.get(b)??0)+1)}const u=(s.length===0?0:Math.max(0,...h.values())/s.length)<=ht,l=new Map,g=[],f=new Map;let y=0,v=0;for(const m of t){const b=a(m);let O;if(E(m)?O=`p:${Y(m)}`:u&&b!==void 0?O=`i:${b}`:O=`u:${v++}`,m.supersedes==="partId"&&b!==void 0){const M=f.get(b);M!==void 0&&M!==O&&l.has(M)&&l.delete(M)}const F=l.get(O);F===void 0?(l.set(O,{winner:m,count:1}),g.push(O)):(F.count++,O.startsWith("i:")&&y++,r(F.winner,m)&&(F.winner=m)),b!==void 0&&f.set(b,O)}const c=[],S=[...g.filter(m=>m.startsWith("p:")),...g.filter(m=>!m.startsWith("p:"))];for(const m of S){const b=l.get(m);b!==void 0&&c.push(b.count>1?{...b.winner,retestCount:b.count}:b.winner)}const D=y>0?{code:"retests-by-part-id",severity:"info",message:`${y} record${y===1?"":"s"} with no position shared a part ID with an earlier record and ${y===1?"was":"were"} treated as a retest of it.`}:void 0;return{results:c,warning:D}}export function getDieTestValue(t,e){return J(t,e)}export function getTestPassStatus(t,e,n){const i=Oe(t,e);return i!==void 0?i:n!==void 0&&!isParametricTest(n)?ge(J(t,e)):void 0}function ge(t){return t===0||t===1?t===1:void 0}export function testPassStatusReader(t){const e=t.map(d=>d.testNumber),n=Ae(e),i=t.map(d=>!isParametricTest(d));return function(r,a){n(r,a);for(let s=0;s<a.length;s++){if(a[s]!==Re||!i[s])continue;const h=ge(J(r,e[s]));h!==void 0&&(a[s]=h?Te:Fe)}return a}}export function dieHasTestData(t){return Ce(t)}function z(t){return t===void 0||Number.isNaN(t)?void 0:t}function U(t,e){const n={},i=z(e.hbin),d=z(e.sbin);i!==void 0&&(n.hbin=i),d!==void 0&&(n.sbin=d),e.retestCount!==void 0&&(n.retestCount=e.retestCount),e.siteNum!==void 0&&(n.siteNum=e.siteNum),e.partId!==void 0&&(n.partId=e.partId),e.metadata!==void 0&&(n.metadata=e.metadata);const r=K(e);return ke({...t,...n},r.table,r.row)}function ye(t){return t.some(dieHasTestData)?"value":t.some(e=>e.hbin!==void 0&&e.hbin!==null)?"hardBin":t.some(e=>e.sbin!==void 0&&e.sbin!==null)?"softBin":"hardBin"}function be(t,e){return t.map(({code:n,message:i})=>({code:n,message:i,severity:n==="non-standard-diameter"||n==="diameter-exceeds-die-extent"?"warning":"error",confidence:e.wafer.confidence}))}const gt="do not fit inside the supplied",yt="Inferred wafer diameter",bt="The probed dies reach only",wt=.75,xt=20;export const STANDARD_WAFER_DIAMETERS_MM=[100,125,150,200,300];const Dt=.02;function we(t,e){return e.reduce((n,i)=>Math.abs(i-t)<Math.abs(n-t)?i:n)}function vt(t,e){if(!e.length)return!0;const n=we(t,e);return Math.abs(n-t)/n<=Dt}function Mt(t){return t===void 0?STANDARD_WAFER_DIAMETERS_MM:t.filter(e=>Number.isFinite(e)&&e>0)}export function buildWaferMap(t){const e=ot(!Array.isArray(t)&&t.layout?rt(t):t),n=[];let i;if(e.valueFilter!=="none"&&e.testDefs){const o=e.valueFilter,C=(e.lotStackOpts?e.lotStackOpts.results:[e.results]).map(k=>{const R=k.length>0?K(k[0]):void 0;if(!R)return[];const N=et(R.table,e.testDefs,o);return N.tests.length>0&&se(k,N.table),N.tests}),x=tt(C);if(x.length>0){i={mode:o,tests:x};const k=nt(o,x,e.testDefs);k&&n.push(k)}}if(e.derivedTests){const o=new Set(e.passBins),C=R=>{const N=R.length>0?K(R[0]):void 0,j=je(R,N?.table??Ne([]),e.testDefs,e.derivedTests,o);return N&&se(R,j.table),j},k=(e.lotStackOpts?e.lotStackOpts.results:[e.results]).map(C);e.testDefs=k[0]?.testDefs??e.testDefs,n.push(...k[0]?.warnings??[])}e.lotStackOpts&&!Ze(e.lotStackOpts.method)&&(e.testDefs=e.testDefs?.map(ut));const d=e.lotStackOpts?ie(ct(e.lotStackOpts,e.testDefs)).records:e.results;for(let o=0;o<Math.min(5,d.length);o++){const C=d[o];if(typeof C.x=="string"||typeof C.y=="string")throw new TypeError("buildWaferMap: x and y must be numbers, received strings. Did you forget to cast CSV values? e.g. { x: +row.x, y: +row.y }")}for(const o of d)if(o.x==null!=(o.y==null))throw new TypeError(`buildWaferMap: die has only one of x/y set (x=${String(o.x)}, y=${String(o.y)}). A die must be either fully positioned (both x and y) or fully unpositioned (neither) \u2014 omit both to mark a die as having no reported position.`);const{results:r,warning:a}=mt(d,e.retestPolicy,e.passBins),s={wafer:{confidence:1,method:"provided"},diePitch:{confidence:1,units:"mm"},grid:{confidence:1}},h=[];if(e.explicitDies){let o=e.explicitDies.filter(E);const C=e.explicitDies.filter(V=>!E(V)),x=r.filter(E),k=r.filter(V=>!E(V));if(x.length>0){const V=new Map(x.map(_=>[Y(_),_]));o=o.map(_=>{const te=V.get(Y(_));return te?U(_,te):_})}const R=e.waferOpts?.diameter??300,N=q({diameter:R,notch:e.waferOpts?.notch,orientation:e.waferOpts?.orientation??0,metadata:e.waferOpts?.metadata,reticle:e.reticleOpts});N.orientation!==0&&(o=ne(o,N)),o=o.map(H);const j=me(e.reticleOpts,N,o,1,1,0,0,0,0,N.orientation),xe=k.map((V,_)=>H(U({id:`unpositioned_${_}`,width:o[0]?.width??1,height:o[0]?.height??1},V))),G=[...o,...C,...xe];return{wafer:N,dies:G,dataAxisFlip:{x:!1,y:!1},reticleConfig:e.reticleOpts,units:"mm",inference:s,warnings:[...e.removedFieldWarning?[e.removedFieldWarning]:[],...e.inputValueWarnings,...a?[a]:[],...be(h,s),...n,...e.ringCountWarning?[e.ringCountWarning]:[]],plotMode:ye(r),metadata:N.metadata??null,isLotStack:!1,dataCoverage:pe(G),passBins:e.passBins,...i?{valueFilter:i}:{},ringCount:e.ringCount,yield:he(G,e.passBins,e.edgeDieYieldMode),reticles:j,hbinDefs:e.hbinDefs,sbinDefs:e.sbinDefs,testDefs:e.testDefs,metadataFields:e.metadataFields}}const p=r.filter(E),u=r.filter(o=>!E(o)),l=p.map(o=>({x:o.x,y:o.y})),g=Le(l,e.dieOpts,e.waferOpts?.diameter);s.diePitch={confidence:g.confidence,units:g.units};const{pitchX:f,pitchY:y}=g,v=g.units,c=at(p,e.dieOpts),S=Ye(l);s.grid={confidence:S.confidence};const{offsetX:D,offsetY:m}=dt(l,c,S),{flipX:b,flipY:O}=ce(e.dieOpts,c),{colMidX:F,colMidY:M,anchored:W}=ft(l,D,m,f,y,e.waferOpts?.center);let T=e.waferOpts?.diameter;const P=l.map(o=>({x:(Math.round(o.x)-D)*f-F,y:(Math.round(o.y)-m)*y-M})),$=Q(P.map(({x:o,y:C})=>Math.hypot(Math.abs(o)+f/2,Math.abs(C)+y/2)));if(T===void 0)if(l.length>0)if(v==="mm"){const o=Be(P,{minRadius:$});T=o.diameter,s.wafer={confidence:o.confidence,method:o.method};const C=Mt(e.standardDiameters);if(!vt(T,C)){const x=we(T,C);h.push({code:"non-standard-diameter",message:`${yt} ${T.toFixed(1)} mm is not a standard wafer size (nearest is ${x} mm). The diameter was derived from the die extent, which assumes the probed grid reaches the wafer edge \u2014 a non-standard result usually means it does not, because the outer dies were never probed. Every die is then placed against a wafer that is too small, which moves dies between rings and changes ring and edge findings. Supply waferConfig.diameter.`})}}else T=$*2,s.wafer={confidence:g.confidence*.8,method:"extent"};else T=v==="mm"?300:30,s.wafer={confidence:0,method:"default"};if(!W&&l.length>0&&lt(l,D,m)&&(s.wafer.method="inferred-partial",h.push({code:"partial-coverage",message:"Wafer geometry was inferred from die positions alone. The data does not span a full symmetric wafer, so the inferred diameter and centre may be wrong and dies may be mis-positioned relative to the true wafer boundary. Supply waferConfig.diameter and waferConfig.center (the prober coordinate of the wafer centre) to position partial data correctly."})),e.waferOpts?.diameter!==void 0&&e.waferOpts.center===void 0&&$>0&&l.length>=xt){const o=$/(T/2);o<wt&&h.push({code:"diameter-exceeds-die-extent",message:`${bt} ${(o*100).toFixed(0)}% of the ${T} mm wafer's radius. Either the diameter is larger than the real one, or this is a partial map covering only part of the wafer. Ring bands are equal-radius, so the outer rings are mostly or entirely empty and ring, quadrant and edge findings describe the assumed wafer rather than the probed area. Check waferConfig.diameter, or drop it and let the diameter be inferred from the die extent.`})}if(e.waferOpts?.diameter!==void 0){const o=e.dieOpts?.width!==void 0&&e.dieOpts?.height!==void 0;if(o&&$>T/2+1e-9){const C=P.filter(({x,y:k})=>Math.hypot(Math.abs(x)+f/2,Math.abs(k)+y/2)>T/2+1e-9).length;h.push({code:"geometry-conflict",message:`${C} of ${P.length} probed die positions ${gt} ${T} mm wafer at the supplied die pitch of ${f} \xD7 ${y} mm. A die with test results is a real prober position and is always fully on the wafer, so one of the two supplied values must be wrong: containing these dies at this pitch would need a diameter of at least ${($*2).toFixed(1)} mm. Check waferConfig.diameter and dieConfig.width/height against the real device.`})}}const A=q({diameter:T,notch:e.waferOpts?.notch,orientation:e.waferOpts?.orientation??0,metadata:e.waferOpts?.metadata,reticle:e.reticleOpts});let w=p.map(o=>{const C=Math.round(o.x)-D,x=Math.round(o.y)-m,k={id:`${C}_${x}`,x:C,y:x,physX:C*f-F,physY:x*y-M,width:f,height:y,insideWafer:!0,partial:!1};return U(k,o)});(D!==0||m!==0)&&(w=w.map(o=>({...o,x:o.x+D,y:o.y+m,id:`${o.x+D}_${o.y+m}`}))),w=ne(w,A),(b||O)&&(w=ve(w,{flipX:b,flipY:O},A.center));const B=[];e.waferOpts?.edgeExclusion&&e.waferOpts.edgeExclusion>0&&(w=pt(w,A,e.waferOpts.edgeExclusion),e.waferOpts.edgeExclusion>A.radius&&B.push({code:"edge-exclusion-exceeds-radius",message:`edgeExclusion (${e.waferOpts.edgeExclusion}mm) exceeds the resolved wafer radius (${A.radius}mm) \u2014 the entire wafer is excluded.`,severity:"warning"})),w=w.map(H);const I=me(e.reticleOpts,A,w,f,y,D,m,F,M,A.orientation,b,O),X=u.map((o,C)=>H(U({id:`unpositioned_${C}`,width:f,height:y},o))),L=[...w,...X];return{wafer:A,dies:L,dataAxisFlip:{x:b,y:O},reticleConfig:e.reticleOpts,units:v,inference:s,warnings:[...e.removedFieldWarning?[e.removedFieldWarning]:[],...e.inputValueWarnings,...a?[a]:[],...be(h,s),...B,...n,...e.ringCountWarning?[e.ringCountWarning]:[]],plotMode:ye(r),metadata:A.metadata??null,isLotStack:e.lotStackOpts!==void 0,dataCoverage:pe(L),passBins:e.passBins,...i?{valueFilter:i}:{},ringCount:e.ringCount,yield:he(L,e.passBins,e.edgeDieYieldMode),reticles:I,hbinDefs:e.hbinDefs,sbinDefs:e.sbinDefs,testDefs:e.testDefs,metadataFields:e.metadataFields,aggrMethod:e.lotStackOpts?.method,lotSize:e.lotStackOpts?.results.length}}
@@ -45,6 +45,10 @@ export interface SpecLimits {
45
45
  /** A value equal to `limitHigh` passes. Default `true`; STDF `PARM_FLG` bit 7. */
46
46
  limitHighInclusive?: boolean;
47
47
  }
48
+ /** True when `value` sits below `low` (a value equal to `low` is below only when `inclusive` is `false`). */
49
+ export declare function belowLow(value: number, low: number, inclusive?: boolean): boolean;
50
+ /** True when `value` sits above `high` (a value equal to `high` is above only when `inclusive` is `false`). */
51
+ export declare function aboveHigh(value: number, high: number, inclusive?: boolean): boolean;
48
52
  /**
49
53
  * Classify `value` against `limits`. Returns `null` when no verdict is possible:
50
54
  * no value, a non-finite value, or a test with neither limit defined.
@@ -1 +1 @@
1
- export function classifySpec(n,i){return n===void 0||!Number.isFinite(n)||i===void 0||i.limitLow===void 0&&i.limitHigh===void 0?null:i.limitLow!==void 0&&(i.limitLowInclusive===!1?n<=i.limitLow:n<i.limitLow)?"failLow":i.limitHigh!==void 0&&(i.limitHighInclusive===!1?n>=i.limitHigh:n>i.limitHigh)?"failHigh":"pass"}export function isOutOfSpec(n){return n==="failLow"||n==="failHigh"}export function countOutOfSpec(n,i){let f=0;for(let e=0;e<n.length;e++)isOutOfSpec(classifySpec(n[e],i))&&f++;return f}export function hasSpecLimits(n){return n!==void 0&&(n.limitLow!==void 0||n.limitHigh!==void 0)}
1
+ export function belowLow(n,e,i){return i===!1?n<=e:n<e}export function aboveHigh(n,e,i){return i===!1?n>=e:n>e}export function classifySpec(n,e){return n===void 0||!Number.isFinite(n)||e===void 0||e.limitLow===void 0&&e.limitHigh===void 0?null:e.limitLow!==void 0&&belowLow(n,e.limitLow,e.limitLowInclusive)?"failLow":e.limitHigh!==void 0&&aboveHigh(n,e.limitHigh,e.limitHighInclusive)?"failHigh":"pass"}export function isOutOfSpec(n){return n==="failLow"||n==="failHigh"}export function countOutOfSpec(n,e){let i=0;for(let f=0;f<n.length;f++)isOutOfSpec(classifySpec(n[f],e))&&i++;return i}export function hasSpecLimits(n){return n!==void 0&&(n.limitLow!==void 0||n.limitHigh!==void 0)}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The value filter: take values that lie outside a limit set out of a wafer's
3
+ * data, so every map, statistic and chart reads the same population.
4
+ *
5
+ * Runs once, on the raw probe records at the start of `buildWaferMap` (before
6
+ * derived tests, which would otherwise be computed from a clamped reading). An
7
+ * excluded value becomes no value for that test on that die; the value itself is
8
+ * kept in `DieTable.excluded` so the tooltip can say what was excluded and why.
9
+ *
10
+ * Only values change. `die.testPass` and the bins are the tester's own verdict
11
+ * and are left alone.
12
+ */
13
+ import type { DieTable } from '../core/dieTable.js';
14
+ import { type DieData } from '../core/dieTable.js';
15
+ import type { TestDef, WaferWarning } from './buildWaferMap.js';
16
+ /**
17
+ * Which limit set a value must lie inside to be kept.
18
+ * `'validity'` excludes values outside the validity limits (tester clamps) and
19
+ * only affects tests that have them. `'spec'` and `'test'` keep only values
20
+ * inside the specification or test limits. `'none'` filters nothing.
21
+ */
22
+ export type ValueFilterMode = 'validity' | 'spec' | 'test' | 'none';
23
+ /** Per-test outcome of the value filter, carried on `WaferMapResult.valueFilter`. */
24
+ export interface ValueFilterTest {
25
+ testNumber: number;
26
+ /** Values excluded across the wafer (or across every wafer of a lot). */
27
+ excluded: number;
28
+ /** Values the test had before filtering. */
29
+ total: number;
30
+ }
31
+ export interface ValueFilterSummary {
32
+ mode: Exclude<ValueFilterMode, 'none'>;
33
+ /** Tests with at least one excluded value. */
34
+ tests: ValueFilterTest[];
35
+ }
36
+ /** Display name of a limit set, as the UI and the log name it. */
37
+ export declare function limitSetName(mode: Exclude<ValueFilterMode, 'none'>): string;
38
+ /**
39
+ * `table` with out-of-range values taken out, and the per-test counts.
40
+ * Parametric tests only: a functional test has no measured value to be out of range.
41
+ */
42
+ export declare function applyValueFilter(table: DieTable, testDefs: readonly TestDef[] | undefined, mode: ValueFilterMode): {
43
+ table: DieTable;
44
+ tests: ValueFilterTest[];
45
+ };
46
+ /**
47
+ * The caption fragment for `testNumber` over `dies`: " · 3 values outside validity limits excluded", or ''
48
+ * when the filter took nothing out of them. One wording for every chart caption.
49
+ */
50
+ export declare function excludedNote(dies: readonly DieData[], testNumber: number): string;
51
+ /** Sums per-wafer outcomes into one (a lot is filtered wafer by wafer). */
52
+ export declare function mergeValueFilterTests(parts: readonly ValueFilterTest[][]): ValueFilterTest[];
53
+ /** The log line for an outcome: what was excluded, per test, and under which limits. */
54
+ export declare function valueFilterWarning(mode: Exclude<ValueFilterMode, 'none'>, tests: readonly ValueFilterTest[], defs: readonly TestDef[] | undefined): WaferWarning | undefined;
55
+ //# sourceMappingURL=valueFilter.d.ts.map
@@ -0,0 +1 @@
1
+ import{excludedCounts as m,withExcluded as p}from"../core/dieTable.js";import{aboveHigh as v,belowLow as N}from"./spec.js";export function limitSetName(e){return e==="validity"?"validity limits":e==="spec"?"specification limits":"test limits"}function w(e,t){const n=t==="validity"?{low:e.validLow,high:e.validHigh}:t==="spec"?{low:e.specLow,high:e.specHigh}:{low:e.limitLow,high:e.limitHigh,lowInclusive:e.limitLowInclusive,highInclusive:e.limitHighInclusive};return n.low===void 0&&n.high===void 0?void 0:n}export function applyValueFilter(e,t,n){if(n==="none"||!t)return{table:e,tests:[]};const i=new Map,l=new Map,s=[];for(const o of t){if(o.testType==="F")continue;const u=w(o,n),c=e.values.get(o.testNumber);if(u===void 0||c===void 0)continue;let r,a,h=0,g=0;for(let d=0;d<c.length;d++){const f=c[d];Number.isNaN(f)||(h++,!(u.low!==void 0&&N(f,u.low,u.lowInclusive)||u.high!==void 0&&v(f,u.high,u.highInclusive)))||(r===void 0&&(r=c.slice(),a=new c.constructor(c.length).fill(NaN)),r[d]=NaN,a[d]=f,g++)}r===void 0||a===void 0||(i.set(o.testNumber,r),l.set(o.testNumber,a),s.push({testNumber:o.testNumber,excluded:g,total:h}))}return s.length===0?{table:e,tests:s}:{table:p(e,i,l,n),tests:s}}export function excludedNote(e,t){const n=m(e),i=n?.counts.get(t)??0;return n&&i>0?` \xB7 ${i.toLocaleString("en-GB")} value${i===1?"":"s"} outside ${limitSetName(n.by)} excluded`:""}export function mergeValueFilterTests(e){const t=new Map;for(const n of e)for(const i of n){const l=t.get(i.testNumber);l?(l.excluded+=i.excluded,l.total+=i.total):t.set(i.testNumber,{...i})}return[...t.values()].sort((n,i)=>n.testNumber-i.testNumber)}export function valueFilterWarning(e,t,n){if(t.length===0)return;const i=o=>n?.find(u=>u.testNumber===o)?.name??`test ${o}`,l=t.reduce((o,u)=>o+u.excluded,0),s=t.slice(0,5).map(o=>`${i(o.testNumber)}: ${o.excluded} of ${o.total}`).join("; ")+(t.length>5?`; and ${t.length-5} more tests`:"");return{code:"values-excluded",message:`${l} value${l===1?"":"s"} outside the ${limitSetName(e)} treated as missing (${s}).`,severity:"info"}}
@@ -1 +1 @@
1
- import{requireRingCount as se}from"../core/ringCount.js";import{analyzeWaferMap as H,candidatesOf as U,describeRegional as Q,resolveOptions as ae,adjustPValues as re,twoProportionZ as X,zPValue as W,welchOfSums as Z,rateRelativeEffect as oe,passesRateGate as ce,severityForFinding as J,severityForScore as ee,collapseRedundantFindings as le,findContiguousRuns as fe,mergedRegionLabel as de}from"./analyzeWaferMap.js";import{normalizeInput as ue}from"./normalizeInput.js";import{poolCapability as me,poolRegionYield as ge,poolPassRates as pe}from"./summaryFigures.js";import{mergeTestDefs as he}from"./mergeTestDefs.js";import{findingPatternKey as ye}from"./filterFindings.js";import{median as te}from"../core/utils.js";import{robustFence as ne}from"./math.js";import{findLotPattern as be}from"./lotPattern.js";import{buildDriftFindings as we}from"./lotDrift.js";import{claimForPattern as ve,weakestMultiplier as Se}from"./analyzeWaferMap.js";import{PATTERN_LABELS as ze}from"./patternClassification.js";import{describeWaferPopulation as Ie,populationStat as ke}from"./population.js";const T=8,Me={3:[.97,.994],4:[.829,.926],5:[.71,.821],6:[.625,.74],7:[.568,.68]},Re=3;export function outlierWafers(i){const o=i.length;if(o<3)return null;const r=te([...i]),s=e=>Math.abs(e-r)>=Re;if(o>=T){const e=ne(i,1.5,T),l=ne(i,3,T);if(!e||!l)return null;const f=(e.hi-e.lo)/4,a=[];return i.forEach((d,h)=>{if(d>=e.lo&&d<=e.hi||!s(d))return;const t=d<l.lo||d>l.hi?"unusual":"notable";a.push({index:h,severity:t,statistic:(d-r)/f})}),{method:"tukey-fence",outliers:a}}const u=i.map((e,l)=>l).sort((e,l)=>i[e]-i[l]),p=i[u[o-1]]-i[u[0]];if(p===0)return null;const[n,c]=Me[o],g=[],y=(e,l)=>{const f=Math.abs(i[e]-i[l])/p;f>n&&s(i[e])&&g.push({index:e,severity:f>c?"unusual":"notable",statistic:f})};return y(u[0],u[1]),y(u[o-1],u[o-2]),{method:"dixon-q",outliers:g}}const A=2;function _(i,o){const r={info:0,notable:1,unusual:2};return r[i]>=r[o]?i:o}const Pe=new Set(["ring","quadrant","sector"]),xe=new Set(["ring","quadrant","sector","reticle-position","test-site"]),$e=new Set(["yield","hardBin","softBin","functionalTest","test"]);function Be(i){return xe.has(i.comparison.family)&&$e.has(i.variable.kind)}function De(i,o){const r=i.map(n=>n.facts);if(!r.length||r.some(n=>!n))return{coincident:new Set,yieldSoftBin:void 0,passBins:[],sectorCount:o};const[s,...u]=r,p=u.every(n=>n.passBins.length===s.passBins.length&&n.passBins.every(c=>s.passBins.includes(c)));return{coincident:new Set([...s.coincident].filter(n=>u.every(c=>c.coincident.has(n)))),yieldSoftBin:u.every(n=>n.yieldSoftBin===s.yieldSoftBin)?s.yieldSoftBin:void 0,passBins:p?s.passBins:[],sectorCount:o}}function j(i,o){let r=0,s=0,u=0,p=0,n=0,c=0,g=0,y=0,e=0,l=!0,f=0;for(const{waferIndex:h,c:t}of i){const m=o(h,t),S=t.rate??t.mean,M=Math.sqrt(S.n+m.n);if(t.rate)r+=M*X(t.rate.hits,t.rate.n,m.hits,m.n),u+=t.rate.hits,p+=t.rate.n,n+=m.hits,c+=m.n;else{const z=Z(t.mean,m.n,m.sum,m.sq);r+=M*z.z,g+=t.mean.n*z.effectSize,y+=t.mean.n*z.delta,f+=t.mean.n,t.relativeDelta===void 0?l=!1:e+=t.mean.n*t.relativeDelta}s+=M*M}const a=s>0?r/Math.sqrt(s):0,d=i[0].c;if(d.rate){const h=n/c,t=u/p-h;return{z:a,delta:t,relativeDelta:h===0?void 0:t/h,size:oe({hits:u,n:p,restHits:n,restN:c,passRate:d.rate.passRate})}}return{z:a,delta:y/f,relativeDelta:l?e/f:void 0,size:g/f}}function O(i,o,r,s){return i.rate?ce(o,r.delta,r.size,s):o<=s.significanceLevel&&Math.abs(r.size)>=s.minimumEffectSize}function Ee(i,o,r,s){const u=new Map;for(const{waferIndex:a,byKey:d}of i)for(const h of d.values())(u.get(h.key)??u.set(h.key,[]).get(h.key)).push({waferIndex:a,c:h});const p=new Map(i.map(a=>[a.waferIndex,a.byKey])),n=(a,d)=>d.rate?{hits:d.rate.restHits,n:d.rate.restN,sum:0,sq:0}:{hits:0,n:d.mean.restN,sum:d.mean.restSum,sq:d.mean.restSq},c=[];for(const[a,d]of u){if(d.length<A)continue;const h=j(d,n);if(h.z===0)continue;const t=d[0].c;c.push({key:a,entries:d,combined:h,finding:{id:`lot-region:${a}`,level:"lot",severity:"info",variable:{...t.variable,label:t.label},comparison:{...t.comparison},effect:{direction:h.z>0?"higher":"lower",absoluteDelta:h.delta,relativeDelta:h.relativeDelta,effectSize:t.rate?h.delta:h.size},stats:{method:"stouffer-z",pValue:W(h.z),sampleSizeLeft:0,sampleSizeRight:0},summary:"",highlight:{kind:"wafer",waferIndices:[]}}})}re(c.map(a=>a.finding));const g=c.filter(a=>O(a.entries[0].c,a.finding.stats.adjustedPValue??1,a.combined,o)),y=(a,d)=>{const h=a.entries[0].c,t=d.entries[0].c;return h.source===t.source&&h.variable.kind===t.variable.kind&&h.variable.bin===t.variable.bin&&h.variable.index===t.variable.index&&h.region.family===t.region.family},e=[],l=new Map;for(const a of g){const d=a.finding.stats.pValue??1,h=g.filter(b=>b!==a&&y(a,b)&&b.finding.effect.direction!==a.finding.effect.direction&&(b.finding.stats.pValue??1)<d);if(h.length){const b=($,v)=>{const I=n($,v);for(const B of h){const k=p.get($)?.get(B.key);k&&(k.rate?(I.hits-=k.rate.hits,I.n-=k.rate.n):(I.n-=k.mean.n,I.sum-=k.mean.sum,I.sq-=k.mean.sq))}return I},R=a.entries.filter($=>b($.waferIndex,$.c).n>=o.minimumSampleSize);if(!R.length)continue;const x=j(R,b),L=d>0?(a.finding.stats.adjustedPValue??d)/d:1;if(Math.sign(x.z)!==Math.sign(a.combined.z)||!O(a.entries[0].c,Math.min(1,W(x.z)*L),x,o))continue}const t=Math.sign(a.combined.z),m=a.entries.filter(b=>Math.sign(b.c.delta)===t),S=i.length,M=a.entries[0].c,z=a.finding.stats.adjustedPValue??d,K=M.rate?J(z,a.combined.delta,a.combined.size):ee(z,a.combined.size),w=_(K,m.length/S>=.6?"unusual":"info"),N={};for(const b of m)N[b.waferIndex]=[...b.c.region.dieKeys];const E={...a.finding,severity:w,stats:{...a.finding.stats,sampleSizeLeft:m.length,sampleSizeRight:S-m.length},summary:`${Q(M,a.combined.delta,a.combined.relativeDelta)} \u2014 ${a.finding.effect.direction} on ${m.length}/${S} wafers, all wafers' data combined`,highlight:{kind:"wafer",waferIndices:m.map(b=>b.waferIndex),dieKeysByWafer:N}};e.push(E),l.set(E,a)}const f=Le(l,p,i.length,o,s,n);return e.splice(0,e.length,...e.filter(a=>!f.replaced.has(a)),...f.findings),le(e,r),e}function Le(i,o,r,s,u,p){const n=new Map;for(const[y,e]of i){const l=e.entries[0].c;if(!Pe.has(l.region.family))continue;const f=[l.source,l.variable.kind,l.variable.bin??"",l.variable.index??"",l.region.family,y.effect.direction].join("|");(n.get(f)??n.set(f,[]).get(f)).push({finding:y,c:l,key:e.key})}const c=[],g=new Set;for(const y of n.values()){if(y.length<2)continue;const e=y[0].c.region.family;for(const l of fe(y,e,s.sectorCount,f=>f.c.region.key)){if(l.length<2)continue;const f=qe(l,o,r,s,u,p);if(f){c.push(f);for(const a of l)g.add(a.finding)}}}return{findings:c,replaced:g}}function qe(i,o,r,s,u,p){const n=i[0].c,c=i[0].finding.effect.direction==="higher"?1:-1,g=de(n.region.family,i.map(w=>w.c.region.key),u),y=[];for(const[w,N]of o){const E=i.map(v=>N.get(v.key));if(E.some(v=>!v))continue;const b=E,R=b[0];let x,L;if(R.rate){const v=b.reduce((P,D)=>P+D.rate.hits,0),I=b.reduce((P,D)=>P+D.rate.n,0),B=R.rate.hits+R.rate.restHits-v,k=R.rate.n+R.rate.restN-I;if(I<s.minimumSampleSize||k<s.minimumSampleSize)continue;x={...R,rate:{hits:v,n:I,restHits:B,restN:k,passRate:R.rate.passRate}},L=X(v,I,B,k)}else{const v=R.mean,I=b.reduce((q,F)=>q+F.mean.n,0),B=b.reduce((q,F)=>q+F.mean.sum,0),k=b.reduce((q,F)=>q+F.mean.sq,0),P=v.n+v.restN-I,D=v.sum+v.restSum-B,C=v.sq+v.restSq-k;if(I<s.minimumSampleSize||P<s.minimumSampleSize)continue;const V={n:I,sum:B,sq:k,restN:P,restSum:D,restSq:C,shift:v.shift},Y=Z(V,P,D,C),G=D/P+v.shift;x={...R,mean:V,relativeDelta:G!==0?Y.delta/Math.abs(G):void 0},L=Y.z}const $=[...new Set(b.flatMap(v=>[...v.region.dieKeys]))];y.push({waferIndex:w,c:x,z:L,dieKeys:$})}if(y.length<A)return;const e=j(y,p);if(e.z===0||Math.sign(e.z)!==c)return;const l=W(e.z),f=Se(i.map(w=>w.finding)),a=Math.min(1,l*f);if(!O(n,a,e,s))return;const d=y.filter(w=>Math.sign(w.z)===c&&W(w.z)<=s.significanceLevel);if(!d.length)return;const h=n.rate?J(a,e.delta,e.size):ee(a,e.size),t=_(h,d.length/r>=.6?"unusual":"info"),m={};for(const w of d)m[w.waferIndex]=w.dieKeys;const S=i.map(w=>w.c.region.key.slice(w.c.region.key.indexOf(":")+1)).join("-"),M={...n,comparison:{...n.comparison,left:g}},z=i[0].finding,K=z.effect.direction;return{...z,id:`lot-region:${i[0].key.split("|").slice(0,-1).join("|")}|${n.region.family}:${S}`,severity:t,comparison:{...z.comparison,left:g},effect:{direction:K,absoluteDelta:e.delta,relativeDelta:e.relativeDelta,effectSize:n.rate?e.delta:e.size},stats:{method:"stouffer-z",pValue:l,adjustedPValue:a,sampleSizeLeft:d.length,sampleSizeRight:r-d.length},summary:`${Q(M,e.delta,e.relativeDelta)} \u2014 ${K} on ${d.length}/${r} wafers, all wafers' data combined`,highlight:{kind:"wafer",waferIndices:d.map(w=>w.waferIndex),dieKeysByWafer:m},relatedIds:i.map(w=>w.finding.id)}}const ie={"Edge-ring":"edge","Edge-local":"edge","Center cluster":"centre or donut",Donut:"centre or donut"};function Fe(i,o){const r=new Map,s=n=>{const c=n.variable.kind==="spatialPattern"?ie[n.comparison.left]:void 0;return c?`spatialPattern|${c}`:ye(n)};for(const n of i){const c=new Set,g=new Map;for(const e of n.summary.findings)if(e.variable.kind==="spatialPattern")for(const l of e.relatedIds??[])g.set(l,s(e));const y=new Set(n.summary.findings.flatMap(e=>e.absorbedIds??[]));for(const e of n.summary.findings){if(y.has(e.id)||Be(e)||e.variable.kind==="spatialPattern"&&o?.carriers.has(n.waferIndex))continue;const l=s(e);if(c.has(l))continue;c.add(l);const f=r.get(l)??{finding:e,waferIndices:[],severity:e.severity,labels:new Map,dieKeysByWafer:{},explainedBy:new Map};f.waferIndices.push(n.waferIndex);const a=g.get(e.id);if(a&&f.explainedBy.set(a,(f.explainedBy.get(a)??0)+1),e.variable.kind==="spatialPattern"){f.labels.set(e.comparison.left,(f.labels.get(e.comparison.left)??0)+1);const d=e.highlight.dieKeys;d&&(f.dieKeysByWafer[n.waferIndex]=d)}f.severity=_(f.severity,e.severity),r.set(l,f)}}const u=[];for(const[n,c]of r){if(c.waferIndices.length<A)continue;const g=c.waferIndices.length/Math.max(1,i.length),y=g>=.6||c.severity==="unusual"?"unusual":"notable",e=c.finding;u.push({id:`lot-repeat:${n}`,level:"lot",severity:y,variable:{...e.variable},comparison:{...e.comparison},effect:{direction:e.effect.direction,absoluteDelta:e.effect.absoluteDelta,relativeDelta:e.effect.relativeDelta,effectSize:e.effect.effectSize},stats:{method:"wafer-finding-frequency",sampleSizeLeft:c.waferIndices.length,sampleSizeRight:i.length-c.waferIndices.length},summary:`${We(e,c.labels)} \u2014 seen on ${c.waferIndices.length}/${i.length} wafers (${Math.round(g*100)}%)`,highlight:{kind:"wafer",waferIndices:c.waferIndices,...c.labels.size?{dieKeysByWafer:c.dieKeysByWafer}:{}}})}const p=new Map(u.map(n=>[n.id,n]));for(const[n,c]of r){const g=p.get(`lot-repeat:${n}`);if(g)for(const[y,e]of c.explainedBy){const l=p.get(`lot-repeat:${y}`);!l||e!==c.waferIndices.length||(l.relatedIds??=[]).push(g.id)}}return u}function Ke(i,o){const{classification:r,carriers:s}=i,u=ze[r.pattern],p=s.size/Math.max(1,o),n={};for(const[c,g]of s)n[c]=g;return{id:"lot-repeat:spatialPattern|lot",level:"lot",severity:p>=.6||r.confidence==="high"?"unusual":"notable",variable:{kind:"spatialPattern",label:u},comparison:{family:"spatial-pattern",left:u,right:"Wafer"},effect:{direction:"different",effectSize:r.features.globalRdd},stats:{method:"wafer-finding-frequency",sampleSizeLeft:s.size,sampleSizeRight:o-s.size},summary:`Spatial pattern: ${u.toLowerCase()} \u2014 seen on ${s.size}/${o} wafers (${Math.round(p*100)}%)`,highlight:{kind:"wafer",waferIndices:[...s.keys()].sort((c,g)=>c-g),dieKeysByWafer:n}}}function Ne(i){const o=/^Rings? (\d+)(?:\s*[–-]\s*(\d+))?/.exec(i.comparison.left);if(!o)return[];const r=+o[1],s=o[2]?+o[2]:r;return Array.from({length:Math.max(0,s-r+1)},(u,p)=>r+p)}function We(i,o){if(!o.size)return i.summary;const r=p=>p.toLowerCase();if(o.size===1)return`Spatial pattern: ${r([...o.keys()][0])}`;const s=ie[i.comparison.left],u=[...o].sort((p,n)=>n[1]-p[1]).map(([p,n])=>`${r(p)} on ${n}`);return`Spatial pattern: ${s} (${u.join(", ")})`}function Ae(i,o){const r=ke(o,"median"),s=i.map(g=>({waferIndex:g.waferIndex,yieldPercent:g.summary.stats.yieldPercent})).filter(g=>g.yieldPercent!==null),u=s.map(g=>g.yieldPercent),p=outlierWafers(u);if(!p)return[];const n=te(u),c=[];for(const{index:g,severity:y,statistic:e}of p.outliers){const l=s[g],f=l.yieldPercent-n;c.push({id:`inter-wafer:yield:${l.waferIndex}`,level:"inter-wafer",severity:y,variable:{kind:"yield",label:"Yield"},comparison:{family:"wafer",left:`Wafer ${l.waferIndex+1}`,right:r.charAt(0).toUpperCase()+r.slice(1)},effect:{direction:f>0?"higher":"lower",absoluteDelta:f/100,relativeDelta:n===0?void 0:f/n,effectSize:e},stats:{method:p.method,sampleSizeLeft:1,sampleSizeRight:s.length-1},summary:`Wafer ${l.waferIndex+1} yield is ${Math.abs(f).toFixed(1)} percentage points ${f>0?"higher":"lower"} than the ${r}`,highlight:{kind:"wafer",waferIndices:[l.waferIndex]}})}return c}export function analyzeWaferLot(i,o={}){const r=i.map(ue),s=r.map((t,m)=>({waferIndex:m,summary:o.perWaferSummaries?.[m]??H(t,o)})),u=s.map(({waferIndex:t,summary:m})=>U(m)??U(H(r[t],o))),p=u.map((t,m)=>({waferIndex:m,byKey:new Map(t.candidates.map(S=>[S.key,S]))})),n=ae(o).resolved,c=r.length>0?se(r[0],"analyzeWaferLot"):void 0,g=be(r,n),y=g&&g.carriers.size>=A?g:null,e=[...c===void 0?[]:Ee(p,n,De(u,n.sectorCount),c),...Fe(s,y),...Ae(s,Ie(s.map(t=>t.summary.wafer))),...we(s,n.significanceLevel)];if(y&&c!==void 0){const t=Ke(y,s.length);t.relatedIds=ve([y.classification.pattern],t.severity,e,Ne,c),t.relatedIds.length||delete t.relatedIds,e.push(t)}e.sort((t,m)=>{const S=t.severity==="unusual"?2:t.severity==="notable"?1:0,M=m.severity==="unusual"?2:m.severity==="notable"?1:0;return S!==M?M-S:t.summary.localeCompare(m.summary,"en")});const l=s.map(t=>t.summary.wafer).filter(t=>!!t),f={},a=[];if(l.length>0){const t=new Set;for(const m of l)for(const S of Object.keys(m))t.add(S);t.delete("wafer"),t.delete("waferId");for(const m of t){const S=l.filter(z=>m in z).map(z=>z[m]);S.every(z=>z===S[0])?f[m]=S[0]:a.push(m)}}const d=s.map(({waferIndex:t,summary:m})=>({waferIndex:t,yieldPercent:m.stats.yieldPercent})),h=s.map(({waferIndex:t,summary:m})=>m.stats.perTestStats?.length?{waferIndex:t,tests:m.stats.perTestStats}:null).filter(t=>t!==null);return{level:"lot",hasNotableFindings:e.some(t=>t.severity!=="info")||s.some(t=>t.summary.hasNotableFindings),findings:e,lot:Object.keys(f).length>0?f:void 0,...a.length>0?{mixedIdentityFields:a}:{},stats:{waferCount:i.length,...Te(r,s.map(t=>t.summary))},lotYieldSeries:d,perWafer:s,...h.length>0?{perWaferTestStats:h}:{}}}function Te(i,o){const r={...pe(o)},s=me(o,he(i).defs);s&&(r.capability=s);const u=ge(o,i.map(p=>p.ringCount));return u&&(r.regionYield=u),r}
1
+ import{waferDisplayLabel as se}from"../core/waferLabel.js";import{requireRingCount as ae}from"../core/ringCount.js";import{analyzeWaferMap as G,candidatesOf as H,describeRegional as U,resolveOptions as re,adjustPValues as oe,twoProportionZ as Q,welchOfSums as X,rateRelativeEffect as ce,passesRateGate as le,severityForFinding as Z,severityForScore as J,collapseRedundantFindings as fe,findContiguousRuns as de,mergedRegionLabel as ue}from"./analyzeWaferMap.js";import{normalizeInput as me}from"./normalizeInput.js";import{poolCapability as ge,poolRegionYield as pe,poolPassRates as he}from"./summaryFigures.js";import{mergeTestDefs as ye}from"./mergeTestDefs.js";import{findingPatternKey as be}from"./filterFindings.js";import{median as ee}from"../core/utils.js";import{robustFence as te,zPValue as K}from"./math.js";import{findLotPattern as we}from"./lotPattern.js";import{buildDriftFindings as ve}from"./lotDrift.js";import{claimForPattern as Se,confirmRegionalFindings as ze,weakestMultiplier as Ie}from"./analyzeWaferMap.js";import{PATTERN_LABELS as ke}from"./patternClassification.js";import{describeWaferPopulation as Re,populationStat as Me}from"./population.js";const W=8,Pe={3:[.97,.994],4:[.829,.926],5:[.71,.821],6:[.625,.74],7:[.568,.68]},xe=3;export function outlierWafers(i){const o=i.length;if(o<3)return null;const r=ee([...i]),s=t=>Math.abs(t-r)>=xe;if(o>=W){const t=te(i,1.5,W),f=te(i,3,W);if(!t||!f)return null;const d=(t.hi-t.lo)/4,b=[];return i.forEach((y,a)=>{if(y>=t.lo&&y<=t.hi||!s(y))return;const e=y<f.lo||y>f.hi?"unusual":"notable";b.push({index:a,severity:e,statistic:(y-r)/d})}),{method:"tukey-fence",outliers:b}}const u=i.map((t,f)=>f).sort((t,f)=>i[t]-i[f]),g=i[u[o-1]]-i[u[0]];if(g===0)return null;const[n,c]=Pe[o],m=[],p=(t,f)=>{const d=Math.abs(i[t]-i[f])/g;d>n&&s(i[t])&&m.push({index:t,severity:d>c?"unusual":"notable",statistic:d})};return p(u[0],u[1]),p(u[o-1],u[o-2]),{method:"dixon-q",outliers:m}}const N=2;function T(i,o){const r={info:0,notable:1,unusual:2};return r[i]>=r[o]?i:o}const $e=new Set(["ring","quadrant","sector"]),Be=new Set(["ring","quadrant","sector","reticle-position","test-site"]),De=new Set(["yield","hardBin","softBin","functionalTest","test"]);function Le(i){return Be.has(i.comparison.family)&&De.has(i.variable.kind)}function Ee(i,o){const r=i.map(n=>n.facts);if(!r.length||r.some(n=>!n))return{coincident:new Set,yieldSoftBin:void 0,passBins:[],sectorCount:o};const[s,...u]=r,g=u.every(n=>n.passBins.length===s.passBins.length&&n.passBins.every(c=>s.passBins.includes(c)));return{coincident:new Set([...s.coincident].filter(n=>u.every(c=>c.coincident.has(n)))),yieldSoftBin:u.every(n=>n.yieldSoftBin===s.yieldSoftBin)?s.yieldSoftBin:void 0,passBins:g?s.passBins:[],sectorCount:o}}function _(i,o){let r=0,s=0,u=0,g=0,n=0,c=0,m=0,p=0,t=0,f=!0,d=0;for(const{waferIndex:a,c:e}of i){const l=o(a,e),h=e.rate??e.mean,S=Math.sqrt(h.n+l.n);if(e.rate)r+=S*Q(e.rate.hits,e.rate.n,l.hits,l.n),u+=e.rate.hits,g+=e.rate.n,n+=l.hits,c+=l.n;else{const v=X(e.mean,l.n,l.sum,l.sq);r+=S*v.z,m+=e.mean.n*v.effectSize,p+=e.mean.n*v.delta,d+=e.mean.n,e.relativeDelta===void 0?f=!1:t+=e.mean.n*e.relativeDelta}s+=S*S}const b=s>0?r/Math.sqrt(s):0,y=i[0].c;if(y.rate){const a=n/c,e=u/g-a;return{z:b,delta:e,relativeDelta:a===0?void 0:e/a,size:ce({hits:u,n:g,restHits:n,restN:c,passRate:y.rate.passRate})}}return{z:b,delta:p/d,relativeDelta:f?t/d:void 0,size:m/d}}function j(i,o,r,s){return i.rate?le(o,r.delta,r.size,s):o<=s.significanceLevel&&Math.abs(r.size)>=s.minimumEffectSize}function qe(i,o,r,s){const u=new Map;for(const{waferIndex:a,byKey:e}of i)for(const l of e.values())(u.get(l.key)??u.set(l.key,[]).get(l.key)).push({waferIndex:a,c:l});const g=new Map(i.map(a=>[a.waferIndex,a.byKey])),n=(a,e)=>e.rate?{hits:e.rate.restHits,n:e.rate.restN,sum:0,sq:0}:{hits:0,n:e.mean.restN,sum:e.mean.restSum,sq:e.mean.restSq},c=[];for(const[a,e]of u){if(e.length<N)continue;const l=_(e,n);if(l.z===0)continue;const h=e[0].c;c.push({key:a,entries:e,combined:l,finding:{id:`lot-region:${a}`,level:"lot",severity:"info",variable:{...h.variable,label:h.label},comparison:{...h.comparison},effect:{direction:l.z>0?"higher":"lower",absoluteDelta:l.delta,relativeDelta:l.relativeDelta,effectSize:h.rate?l.delta:l.size},stats:{method:"stouffer-z",pValue:K(l.z),sampleSizeLeft:0,sampleSizeRight:0},summary:"",highlight:{kind:"wafer",waferIndices:[]}}})}oe(c.map(a=>a.finding));const m=c.filter(a=>j(a.entries[0].c,a.finding.stats.adjustedPValue??1,a.combined,o)),f=ze(m,a=>{const e=a.entries[0].c;return[e.source,e.variable.kind,e.variable.bin??"",e.variable.index??"",e.region.family].join("\0")},(a,e)=>{const l=(M,B)=>{const k=n(M,B);for(const z of e){const R=g.get(M)?.get(z.key);R&&(R.rate?(k.hits-=R.rate.hits,k.n-=R.rate.n):(k.n-=R.mean.n,k.sum-=R.mean.sum,k.sq-=R.mean.sq))}return k},h=a.entries.filter(M=>l(M.waferIndex,M.c).n>=o.minimumSampleSize);if(!h.length)return"baseline-too-small";const S=_(h,l),v=a.finding.stats.pValue??1,$=v>0?(a.finding.stats.adjustedPValue??v)/v:1,w=Math.min(1,K(S.z)*$);return{pValue:w,passes:Math.sign(S.z)===Math.sign(a.combined.z)&&j(a.entries[0].c,w,S,o)}},a=>{const e=a.entries[0].c.rate;return e!==void 0&&(e.passRate?a.combined.z<0:a.combined.z>0)},c),d=[],b=new Map;for(const a of m){if(!f.has(a))continue;const e=a.finding.stats.pValue??1,l=Math.sign(a.combined.z),h=a.entries.filter(z=>Math.sign(z.c.delta)===l),S=i.length,v=a.entries[0].c,$=a.finding.stats.adjustedPValue??e,w=v.rate?Z($,a.combined.delta,a.combined.size):J($,a.combined.size),M=T(w,h.length/S>=.6?"unusual":"info"),B={};for(const z of h)B[z.waferIndex]=[...z.c.region.dieKeys];const k={...a.finding,severity:M,stats:{...a.finding.stats,sampleSizeLeft:h.length,sampleSizeRight:S-h.length},summary:`${U(v,a.combined.delta,a.combined.relativeDelta)} \u2014 ${a.finding.effect.direction} on ${h.length}/${S} wafers, all wafers' data combined`,highlight:{kind:"wafer",waferIndices:h.map(z=>z.waferIndex),dieKeysByWafer:B}};d.push(k),b.set(k,a)}const y=Fe(b,g,i.length,o,s,n);return d.splice(0,d.length,...d.filter(a=>!y.replaced.has(a)),...y.findings),fe(d,r),d}function Fe(i,o,r,s,u,g){const n=new Map;for(const[p,t]of i){const f=t.entries[0].c;if(!$e.has(f.region.family))continue;const d=[f.source,f.variable.kind,f.variable.bin??"",f.variable.index??"",f.region.family,p.effect.direction].join("|");(n.get(d)??n.set(d,[]).get(d)).push({finding:p,c:f,key:t.key})}const c=[],m=new Set;for(const p of n.values()){if(p.length<2)continue;const t=p[0].c.region.family;for(const f of de(p,t,s.sectorCount,d=>d.c.region.key)){if(f.length<2)continue;const d=Ke(f,o,r,s,u,g);if(d){c.push(d);for(const b of f)m.add(b.finding)}}}return{findings:c,replaced:m}}function Ke(i,o,r,s,u,g){const n=i[0].c,c=i[0].finding.effect.direction==="higher"?1:-1,m=ue(n.region.family,i.map(w=>w.c.region.key),u),p=[];for(const[w,M]of o){const B=i.map(I=>M.get(I.key));if(B.some(I=>!I))continue;const k=B,z=k[0];let R,A;if(z.rate){const I=k.reduce((x,D)=>x+D.rate.hits,0),P=k.reduce((x,D)=>x+D.rate.n,0),E=z.rate.hits+z.rate.restHits-I,L=z.rate.n+z.rate.restN-P;if(P<s.minimumSampleSize||L<s.minimumSampleSize)continue;R={...z,rate:{hits:I,n:P,restHits:E,restN:L,passRate:z.rate.passRate}},A=Q(I,P,E,L)}else{const I=z.mean,P=k.reduce((q,F)=>q+F.mean.n,0),E=k.reduce((q,F)=>q+F.mean.sum,0),L=k.reduce((q,F)=>q+F.mean.sq,0),x=I.n+I.restN-P,D=I.sum+I.restSum-E,O=I.sq+I.restSq-L;if(P<s.minimumSampleSize||x<s.minimumSampleSize)continue;const V={n:P,sum:E,sq:L,restN:x,restSum:D,restSq:O,shift:I.shift},C=X(V,x,D,O),Y=D/x+I.shift;R={...z,mean:V,relativeDelta:Y!==0?C.delta/Math.abs(Y):void 0},A=C.z}const ie=[...new Set(k.flatMap(I=>[...I.region.dieKeys]))];p.push({waferIndex:w,c:R,z:A,dieKeys:ie})}if(p.length<N)return;const t=_(p,g);if(t.z===0||Math.sign(t.z)!==c)return;const f=K(t.z),d=Ie(i.map(w=>w.finding)),b=Math.min(1,f*d);if(!j(n,b,t,s))return;const y=p.filter(w=>Math.sign(w.z)===c&&K(w.z)<=s.significanceLevel);if(!y.length)return;const a=n.rate?Z(b,t.delta,t.size):J(b,t.size),e=T(a,y.length/r>=.6?"unusual":"info"),l={};for(const w of y)l[w.waferIndex]=w.dieKeys;const h=i.map(w=>w.c.region.key.slice(w.c.region.key.indexOf(":")+1)).join("-"),S={...n,comparison:{...n.comparison,left:m}},v=i[0].finding,$=v.effect.direction;return{...v,id:`lot-region:${i[0].key.split("|").slice(0,-1).join("|")}|${n.region.family}:${h}`,severity:e,comparison:{...v.comparison,left:m},effect:{direction:$,absoluteDelta:t.delta,relativeDelta:t.relativeDelta,effectSize:n.rate?t.delta:t.size},stats:{method:"stouffer-z",pValue:f,adjustedPValue:b,sampleSizeLeft:y.length,sampleSizeRight:r-y.length},summary:`${U(S,t.delta,t.relativeDelta)} \u2014 ${$} on ${y.length}/${r} wafers, all wafers' data combined`,highlight:{kind:"wafer",waferIndices:y.map(w=>w.waferIndex),dieKeysByWafer:l},relatedIds:i.map(w=>w.finding.id)}}const ne={"Edge-ring":"edge","Edge-local":"edge","Center cluster":"centre or donut",Donut:"centre or donut"};function Ne(i,o){const r=new Map,s=n=>{const c=n.variable.kind==="spatialPattern"?ne[n.comparison.left]:void 0;return c?`spatialPattern|${c}`:be(n)};for(const n of i){const c=new Set,m=new Map;for(const t of n.summary.findings)if(t.variable.kind==="spatialPattern")for(const f of t.relatedIds??[])m.set(f,s(t));const p=new Set(n.summary.findings.flatMap(t=>t.absorbedIds??[]));for(const t of n.summary.findings){if(p.has(t.id)||Le(t)||t.variable.kind==="spatialPattern"&&o?.carriers.has(n.waferIndex))continue;const f=s(t);if(c.has(f))continue;c.add(f);const d=r.get(f)??{finding:t,waferIndices:[],severity:t.severity,labels:new Map,dieKeysByWafer:{},explainedBy:new Map};d.waferIndices.push(n.waferIndex);const b=m.get(t.id);if(b&&d.explainedBy.set(b,(d.explainedBy.get(b)??0)+1),t.variable.kind==="spatialPattern"){d.labels.set(t.comparison.left,(d.labels.get(t.comparison.left)??0)+1);const y=t.highlight.dieKeys;y&&(d.dieKeysByWafer[n.waferIndex]=y)}d.severity=T(d.severity,t.severity),r.set(f,d)}}const u=[];for(const[n,c]of r){if(c.waferIndices.length<N)continue;const m=c.waferIndices.length/Math.max(1,i.length),p=m>=.6||c.severity==="unusual"?"unusual":"notable",t=c.finding;u.push({id:`lot-repeat:${n}`,level:"lot",severity:p,variable:{...t.variable},comparison:{...t.comparison},effect:{direction:t.effect.direction,absoluteDelta:t.effect.absoluteDelta,relativeDelta:t.effect.relativeDelta,effectSize:t.effect.effectSize},stats:{method:"wafer-finding-frequency",sampleSizeLeft:c.waferIndices.length,sampleSizeRight:i.length-c.waferIndices.length},summary:`${Te(t,c.labels)} \u2014 seen on ${c.waferIndices.length}/${i.length} wafers (${Math.round(m*100)}%)`,highlight:{kind:"wafer",waferIndices:c.waferIndices,...c.labels.size?{dieKeysByWafer:c.dieKeysByWafer}:{}}})}const g=new Map(u.map(n=>[n.id,n]));for(const[n,c]of r){const m=g.get(`lot-repeat:${n}`);if(m)for(const[p,t]of c.explainedBy){const f=g.get(`lot-repeat:${p}`);!f||t!==c.waferIndices.length||(f.relatedIds??=[]).push(m.id)}}return u}function Ae(i,o){const{classification:r,carriers:s}=i,u=ke[r.pattern],g=s.size/Math.max(1,o),n={};for(const[c,m]of s)n[c]=m;return{id:"lot-repeat:spatialPattern|lot",level:"lot",severity:g>=.6||r.confidence==="high"?"unusual":"notable",variable:{kind:"spatialPattern",label:u},comparison:{family:"spatial-pattern",left:u,right:"Wafer"},effect:{direction:"different",effectSize:r.features.globalRdd},stats:{method:"wafer-finding-frequency",sampleSizeLeft:s.size,sampleSizeRight:o-s.size},summary:`Spatial pattern: ${u.toLowerCase()} \u2014 seen on ${s.size}/${o} wafers (${Math.round(g*100)}%)`,highlight:{kind:"wafer",waferIndices:[...s.keys()].sort((c,m)=>c-m),dieKeysByWafer:n}}}function We(i){const o=/^Rings? (\d+)(?:\s*[–-]\s*(\d+))?/.exec(i.comparison.left);if(!o)return[];const r=+o[1],s=o[2]?+o[2]:r;return Array.from({length:Math.max(0,s-r+1)},(u,g)=>r+g)}function Te(i,o){if(!o.size)return i.summary;const r=g=>g.toLowerCase();if(o.size===1)return`Spatial pattern: ${r([...o.keys()][0])}`;const s=ne[i.comparison.left],u=[...o].sort((g,n)=>n[1]-g[1]).map(([g,n])=>`${r(g)} on ${n}`);return`Spatial pattern: ${s} (${u.join(", ")})`}function _e(i,o){const r=Me(o,"median"),s=i.map(m=>({waferIndex:m.waferIndex,yieldPercent:m.summary.stats.yieldPercent})).filter(m=>m.yieldPercent!==null),u=s.map(m=>m.yieldPercent),g=outlierWafers(u);if(!g)return[];const n=ee(u),c=[];for(const{index:m,severity:p,statistic:t}of g.outliers){const f=s[m],d=f.yieldPercent-n,b=se({wafer:{metadata:i.find(y=>y.waferIndex===f.waferIndex)?.summary.wafer}},f.waferIndex);c.push({id:`inter-wafer:yield:${f.waferIndex}`,level:"inter-wafer",severity:p,variable:{kind:"yield",label:"Yield"},comparison:{family:"wafer",left:b,right:r.charAt(0).toUpperCase()+r.slice(1)},effect:{direction:d>0?"higher":"lower",absoluteDelta:d/100,relativeDelta:n===0?void 0:d/n,effectSize:t},stats:{method:g.method,sampleSizeLeft:1,sampleSizeRight:s.length-1},summary:`${b} yield is ${Math.abs(d).toFixed(1)} percentage points ${d>0?"higher":"lower"} than the ${r}`,highlight:{kind:"wafer",waferIndices:[f.waferIndex]}})}return c}export function analyzeWaferLot(i,o={}){const r=i.map(me),s=r.map((e,l)=>({waferIndex:l,summary:o.perWaferSummaries?.[l]??G(e,o)})),u=s.map(({waferIndex:e,summary:l})=>H(l)??H(G(r[e],o))),g=u.map((e,l)=>({waferIndex:l,byKey:new Map(e.candidates.map(h=>[h.key,h]))})),n=re(o).resolved,c=r.length>0?ae(r[0],"analyzeWaferLot"):void 0,m=we(r,n),p=m&&m.carriers.size>=N?m:null,t=[...c===void 0?[]:qe(g,n,Ee(u,n.sectorCount),c),...Ne(s,p),..._e(s,Re(s.map(e=>e.summary.wafer))),...ve(s,n.significanceLevel)];if(p&&c!==void 0){const e=Ae(p,s.length);e.relatedIds=Se([p.classification.pattern],e.severity,t,We,c),e.relatedIds.length||delete e.relatedIds,t.push(e)}t.sort((e,l)=>{const h=e.severity==="unusual"?2:e.severity==="notable"?1:0,S=l.severity==="unusual"?2:l.severity==="notable"?1:0;return h!==S?S-h:e.summary.localeCompare(l.summary,"en")});const f=s.map(e=>e.summary.wafer).filter(e=>!!e),d={},b=[];if(f.length>0){const e=new Set;for(const l of f)for(const h of Object.keys(l))e.add(h);e.delete("wafer"),e.delete("waferId");for(const l of e){const h=f.filter(v=>l in v).map(v=>v[l]);h.every(v=>v===h[0])?d[l]=h[0]:b.push(l)}}const y=s.map(({waferIndex:e,summary:l})=>({waferIndex:e,yieldPercent:l.stats.yieldPercent})),a=s.map(({waferIndex:e,summary:l})=>l.stats.perTestStats?.length?{waferIndex:e,tests:l.stats.perTestStats}:null).filter(e=>e!==null);return{level:"lot",hasNotableFindings:t.some(e=>e.severity!=="info")||s.some(e=>e.summary.hasNotableFindings),findings:t,lot:Object.keys(d).length>0?d:void 0,...b.length>0?{mixedIdentityFields:b}:{},stats:{waferCount:i.length,...je(r,s.map(e=>e.summary))},lotYieldSeries:y,perWafer:s,...a.length>0?{perWaferTestStats:a}:{}}}function je(i,o){const r={...he(o)},s=ge(o,ye(i).defs);s&&(r.capability=s);const u=pe(o,i.map(g=>g.ringCount));return u&&(r.regionYield=u),r}
@@ -40,11 +40,19 @@ export declare function resolveOptions(options: AnalyzeWaferMapOptions): {
40
40
  * verdict for the test (read via `getTestPassStatus`, so legacy 0/1-encoded
41
41
  * functional data is counted identically); dies never tested count as neither.
42
42
  */
43
- export declare function computeFunctionalYield(dies: Die[], testDefs: TestDef[] | undefined): StatsSummary['stats']['functionalYield'];
43
+ export declare function computeFunctionalYield(dies: Die[], testDefs: TestDef[] | undefined,
44
+ /** Called for each die failing a test. */
45
+ onFail?: (testNumber: number, die: Die) => void): StatsSummary['stats']['functionalYield'];
44
46
  /** The two-proportion z statistic, signed as left − right; 0 when untestable. */
45
47
  export declare function twoProportionZ(leftPass: number, leftTotal: number, rightPass: number, rightTotal: number): number;
46
- /** Two-sided p-value of a z statistic. */
47
- export declare function zPValue(z: number): number;
48
+ /**
49
+ * Benjamini–Hochberg over the findings given, as ONE family. Callers pass every comparison of one kind
50
+ * of test that one analysis makes — every rate comparison on a wafer (each region family, each of yield,
51
+ * hard bins, soft bins, functional tests and limit failures), every regional comparison of a lot — so the
52
+ * false-discovery rate holds for what the analysis reports as a whole. Corrected per (variable, region
53
+ * family) group instead, a clean wafer with some twenty such groups reports a false finding more often
54
+ * than not.
55
+ */
48
56
  export declare function adjustPValues(findings: RawFinding[]): RawFinding[];
49
57
  /**
50
58
  * A rate finding's counts: hits and dies in its region and in the rest of the
@@ -121,6 +129,39 @@ export declare function passesRateGate(adjustedP: number, delta: number, relEffe
121
129
  * p-value, an exact die count) and are supporting detail, not a restatement.
122
130
  */
123
131
  export declare function claimForPattern<F extends StatsFinding>(patterns: PatternLabel[], severity: StatsSeverity, candidates: readonly F[], ringsOf: (f: F) => number[], ringCount: number): string[];
132
+ /** A re-test of a regional finding against a reduced rest: its p-value (BH multiplier applied) and whether it still passes. */
133
+ export type RegionRetest = {
134
+ pValue: number;
135
+ passes: boolean;
136
+ } | 'baseline-too-small';
137
+ /**
138
+ * Which of the significant regional findings stand when each is compared with the rest of the wafer WITHOUT the
139
+ * others. A region compared with "the rest" looks deviant whenever the rest holds a stronger deviation: with four
140
+ * rings, a large failing area makes its complement look as significant in the other direction, and one failing
141
+ * quadrant makes every other sector look good. Findings are grouped by `groupKey` (same variable, same region
142
+ * family); within a group:
143
+ *
144
+ * 1. Forward: the first finding stands; each further one is re-tested against the rest without those that stand so
145
+ * far, and the first that still passes stands next, until none does. "First" is a loss before a gain where
146
+ * `isLoss` says which direction is a loss (a lower pass rate, more of a fail bin or of a limit failure), then the
147
+ * smallest re-tested p-value: when a failing block and its complement are equally significant, the block is the
148
+ * finding ("Rings 2–3 lower pass rate"), never the complement ("Rings 1 and 4 higher"). A test value has no such
149
+ * direction and is taken strongest first.
150
+ * 2. Backward: each finding that stands is re-tested against the rest without every other one that stands, whatever
151
+ * its direction; the weakest that no longer passes is dropped, until all pass. A finding whose reduced rest is too
152
+ * small to test keeps its place.
153
+ *
154
+ * The baseline is never "the regions that were not significant": a region half inside a failing quadrant is raised
155
+ * but not significant, and against it the clean regions look good. For the same reason a gain (a region better than
156
+ * its rest) is re-tested without every region of its group that leans towards a loss, significant or not (`all`
157
+ * holds the group's comparisons before the gate): a region is better only than the regions that are not worse.
158
+ *
159
+ * `retest` uses the finding's own test, Benjamini–Hochberg multiplier, gates and direction. Shared by the wafer's rate
160
+ * and test-value findings and the lot's pooled findings.
161
+ */
162
+ export declare function confirmRegionalFindings<T>(findings: readonly T[], groupKey: (t: T) => string, retest: (t: T, without: readonly T[]) => RegionRetest, isLoss?: (t: T) => boolean, all?: readonly T[]): Set<T>;
163
+ /** Whether a rate's region is worse than its rest: a lower pass rate, or a higher fail rate (a fail bin, a limit failure). */
164
+ export declare function isRateLoss(c: RateCounts): boolean;
124
165
  /** A test-value finding's per-region sums, in the builder's shifted space. */
125
166
  export interface MeanStats {
126
167
  n: number;
@@ -1 +1 @@
1
- import{normalizeInput as Ge}from"./normalizeInput.js";import{computeCapability as Xe,computeTestFlagYield as Ze,computeRegionYield as Je}from"./summaryFigures.js";import{binPassSets as Me}from"../renderer/binColors.js";import{diePassStatus as Be,isYieldEligibleDie as de,getDieKey as Ne,isPositionedDie as Fe,positionKey as me}from"../core/dies.js";import{dieHasValues as et,testsPresent as Pe,testValue as j}from"../core/dieTable.js";import{getTestPassStatus as se,isParametricTest as W}from"../renderer/buildWaferMap.js";import{markedTestLabel as T,derivedFields as oe}from"../renderer/testLabel.js";import{buildQuadrantRegions as tt,buildReticlePositionRegions as nt,buildRingRegions as it,buildSectorRegions as st,buildTestSiteRegions as ot,sectorCompassNames as xe,areQuadrantsAdjacent as at,parseRegionKey as Y,QUADRANT_CYCLE as pe,regionAngleBins as rt}from"./regions.js";import{buildClusterFindings as ft}from"./clusterDetection.js";import{classifyPattern as lt,patternExplains as ct,patternFailVerdict as ut,PATTERN_LABELS as dt}from"./patternClassification.js";import{requirePassBins as mt}from"../core/passBins.js";import{requireRingCount as pt}from"../core/ringCount.js";import{benjaminiHochberg as ht,fiveNumberSummary as gt,normalCdf as Ce,sampleVariance as he}from"./math.js";import{mean as ae,clamp01 as Ve,maxOf as bt}from"../core/utils.js";import{classifySpec as re,isOutOfSpec as ge}from"../renderer/spec.js";const yt={significanceLevel:{min:1e-6,max:1},minimumEffectSize:{min:0,max:1},minimumRelativeEffect:{min:0,max:Number.MAX_SAFE_INTEGER}},Le=[4,8,16];export function resolveOptions(t){const i=Object.fromEntries(Object.entries(t).filter(([,f])=>f!==void 0)),s={...X,...i},n=[],e=[];for(const f of["significanceLevel","minimumEffectSize","minimumRelativeEffect"]){const{min:c,max:o}=yt[f],u=s[f];if(typeof u!="number"||!Number.isFinite(u)){e.push(`${f}=${String(u)} is not a finite number (using ${X[f]})`),s[f]=X[f];continue}const a=Math.min(o,Math.max(c,u));a!==u&&(e.push(`${f}=${u} is outside ${c}\u2013${o} (using ${a})`),s[f]=a)}if(Le.includes(s.sectorCount)||(e.push(`sectorCount=${s.sectorCount} is not one of ${Le.join(", ")} (using ${X.sectorCount})`),s.sectorCount=X.sectorCount),e.length){const f=`analyzeWaferMap: ${e.join("; ")}. The analysis ran with the corrected values.`;console.warn(`[wafermap] ${f}`),n.push({code:"analysis-option-corrected",message:f,severity:"warning"})}const l=["passBins","ringCount"].filter(f=>i[f]!==void 0);if(l.length){const f=`analyzeWaferMap: ${l.join(" and ")} ${l.length>1?"are":"is"} no longer an analysis option and was ignored. Set ${l.length>1?"them":"it"} on buildWaferMap; the analysis used the value the map was built with.`;console.warn(`[wafermap] ${f}`),n.push({code:"analysis-option-corrected",message:f,severity:"warning"})}const r=["enableYieldAnalysis","enableHardBinAnalysis","enableSoftBinAnalysis","enableReticlePositionAnalysis","enableTestSiteAnalysis","enableClusterAnalysis","enableAngularAnalysis","enablePatternClassification"].filter(f=>i[f]!==void 0);if(r.length){const f=`analyzeWaferMap: ${r.join(", ")} ${r.length>1?"are":"is"} no longer an option and was ignored: every analysis now runs. Filter the findings (filterFindings) to show fewer.`;console.warn(`[wafermap] ${f}`),n.push({code:"analysis-option-corrected",message:f,severity:"warning"})}return{resolved:s,warnings:n}}const X={significanceLevel:.05,minimumEffectSize:.2,minimumRelativeEffect:1,minimumSampleSize:5,enableTestValueAnalysis:!1,computePerTestStats:!1,sectorCount:8,minimumClusterSize:5};function St(t,i){const s={...t};return s.minimumClusterSize=Math.max(5,Math.round(i*.003)),s}function wt(t){return de(t)?t.hbin!==void 0||t.sbin!==void 0||et(t):!1}function vt(t,i,s){if(!t||i)return;const n=(s??[]).filter(e=>W(e)&&(e.limitLow!==void 0||e.limitHigh!==void 0));if(n.length!==0)return e=>{for(const l of n)if(ge(re(j(e,l.testNumber),l)))return!0;return!1}}function $t(t,i,s){const n=new Set,e=new Set,l=new Set,r=new Map,f=new Map;for(const c of Pe(t))n.add(c);for(const c of t)c.hbin!==void 0&&e.add(c.hbin),c.sbin!==void 0&&l.add(c.sbin),de(c)&&(c.hbin!==void 0&&r.set(c.hbin,(r.get(c.hbin)??0)+1),c.sbin!==void 0&&f.set(c.sbin,(f.get(c.sbin)??0)+1));return{totalDies:t.length,analyzedDies:i,excludedDies:t.length-i,yieldPercent:s,testsConsidered:[...n].sort((c,o)=>c-o),hardBinsConsidered:[...e].sort((c,o)=>c-o),softBinsConsidered:[...l].sort((c,o)=>c-o),...r.size?{hardBinCounts:Object.fromEntries(r)}:{},...f.size?{softBinCounts:Object.fromEntries(f)}:{}}}function zt(t,i){if(!i?.length)return;const s=i.filter(e=>W(e)&&(e.limitLow!==void 0||e.limitHigh!==void 0));if(!s.length)return;const n=[];for(const e of s){const l=e.testNumber;let r=0,f=0,c=0,o=0;for(const u of t){if(u.partial||u.edgeExcluded)continue;const a=re(j(u,l),e);a!==null&&(o++,a==="failLow"?f++:a==="failHigh"?c++:r++)}n.push({testNumber:l,label:e.name,passDies:r,failLowDies:f,failHighDies:c,totalDies:o,yieldPercent:o>0?r/o*100:null})}return n.length?n:void 0}export function computeFunctionalYield(t,i){if(!i?.length)return;const s=i.filter(e=>!W(e));if(!s.length)return;const n=[];for(const e of s){const l=e.testNumber;let r=0,f=0;for(const o of t){if(o.partial||o.edgeExcluded)continue;const u=se(o,l,e);u!==void 0&&(u?r++:f++)}const c=r+f;n.push({testNumber:l,label:T(e,l),...oe(e),passDies:r,failDies:f,totalDies:c,passRatePercent:c>0?r/c*100:null})}return n.length?n:void 0}function kt(t,i,s,n){const e=[];for(const l of i){const r=[];for(const a of t){if(a.partial||a.edgeExcluded)continue;const h=j(a,l);h!==void 0&&Number.isFinite(h)&&r.push(h)}if(r.length<n)continue;const f=ae(r),c=Math.sqrt(he(r,f)),o=gt(Float64Array.from(r)),u=s?.find(a=>a.testNumber===l)?.name??String(l);e.push({testNumber:l,label:u,count:r.length,min:o.min,max:o.max,mean:f,stddev:c,median:o.median,q1:o.q1,q3:o.q3})}return e.length?e:void 0}export function twoProportionZ(t,i,s,n){const e=(t+s)/(i+n),l=e*(1-e)*(1/i+1/n);return!Number.isFinite(l)||l<=0?0:(t/i-s/n)/Math.sqrt(l)}export function zPValue(t){return Ve(2*(1-Ce(Math.abs(t))))}function O(t,i,s,n){const e=twoProportionZ(t,i,s,n);return e===0?1:zPValue(e)}export function adjustPValues(t){const i=new Map;for(const s of t){const n=`${s.variable.kind}:${s.comparison.family}`,e=i.get(n)??[];e.push(s),i.set(n,e)}for(const s of i.values()){const n=s.filter(l=>l.stats.pValue!==void 0),e=ht(n.map(l=>l.stats.pValue));n.forEach((l,r)=>{l.stats.adjustedPValue=e[r]})}return t}export function rateRelativeEffect(t){const i=(t.passRate?t.n-t.hits:t.hits)/t.n,s=(t.passRate?t.restN-t.restHits:t.restHits)/t.restN;return s===0?i===0?0:1/0:Math.abs(i-s)/s}export function severityForFinding(t,i,s){const n=Math.abs(i),e=s;return t<=.01&&(n>=.3||e>=2.5)?"unusual":t<=.05&&(n>=.2||e>=1.5)?"notable":"info"}export function severityForScore(t,i){return t<=.01&&Math.abs(i)>=.5?"unusual":t<=.05&&Math.abs(i)>=.15?"notable":"info"}function fe(t){return t==="reticle-position"?"other reticle positions":t==="test-site"?"other test sites":"the rest of the map"}function _(t){return t==="reticle-position"?"Other reticle positions":t==="test-site"?"Other test sites":"Rest of map"}function be(t,i,s){const n=(Math.abs(i)*100).toFixed(1);return`${t} yield is ${n} percentage points ${i>0?"higher":"lower"} than ${fe(s)}`}function ye(t,i){return i==="quadrant"&&!t.startsWith("Quadrant")?`quadrant ${t}`:t}function Ke(t){return/^(Rings|Sectors|Quadrants)\b/.test(t)?"have":"has"}function Se(t,i,s,n){const e=ye(t,n),l=(Math.abs(s)*100).toFixed(1);return`${e} ${Ke(e)} ${i} occurrence ${l} percentage points ${s>0?"higher":"lower"} than ${fe(n)}`}function we(t,i,s,n){const e=ye(t,n),l=(Math.abs(s)*100).toFixed(1);return`${e} ${Ke(e)} ${i} pass rate ${l} percentage points ${s>0?"higher":"lower"} than ${fe(n)}`}function ve(t,i,s,n,e,l){const r=ye(t,e),f=fe(e),c=s>0?"higher":"lower";if(n!==void 0&&Number.isFinite(n)){const u=(Math.abs(n)*100).toFixed(1);return`${r} mean ${i} is ${u}% ${c} than ${f}`}const o=l?` ${l}`:"";return`${r} mean ${i} is ${Math.abs(s).toPrecision(3)}${o} ${c} than ${f}`}function Ee(t,i,s){const n=i?.find(e=>e.bin===t);return n?.name?`${s} ${t} (${n.name})`:`${s} ${t}`}function Dt(t,i){const s=i?.find(n=>n.testNumber===t);return{label:T(s,t),unit:s?.unit,...oe(s)}}const Oe=new WeakMap,Te=new WeakMap,qe=new WeakMap;function Z(t,i){const s=i.highlight.dieKeys;return s&&qe.set(s,t),i}let Q=null,J;const He=new WeakMap;export function candidatesOf(t){return He.get(t)}function Ae(t,i,s,n){if(!Q)return;const e=je(t);if(!e)return;const l=t.id.slice(0,t.id.indexOf(":")),r=l==="specLimit"?"limitFail":l,{kind:f,bin:c,index:o}=t.variable;Q.push({key:[r,f,c??"",o??"",e.family,e.key].join("|"),source:r,variable:t.variable,label:t.variable.label,comparison:t.comparison,region:e,z:i,delta:t.effect.absoluteDelta??0,effectSize:t.effect.effectSize??0,relativeDelta:t.effect.relativeDelta,rate:s,mean:n})}export function describeRegional(t,i,s){const n=t.comparison.left,e=t.region.family;switch(t.source){case"yield":return be(n,i,e);case"hardBin":case"softBin":return Se(n,t.label,i,e);case"functional":return we(n,t.label.replace(/ pass rate$/,""),i,e);case"limitFail":return $e(n,t.label,i);case"test":return ve(n,t.label,i,s,e,t.variable.unit)}}function $e(t,i,s){return`${t} limit fail rate for ${i} is ${(Math.abs(s)*100).toFixed(1)} pp ${s>0?"higher":"lower"} than the rest of the wafer`}const U=new WeakMap;function le(t,i){return U.set(t,i),t}function je(t){const i=t.highlight.dieKeys;return i?qe.get(i):void 0}const Ie=new WeakMap;function I(t){let i=Ie.get(t);return i||Ie.set(t,i=t.map(me)),i}function Rt(t){let i=Oe.get(t);return i||Oe.set(t,i=t.map(Ne)),i}function ce(t,i){let s=Te.get(t);s||Te.set(t,s={members:new Set(t),byFamily:new WeakMap});const n=s.byFamily.get(i);if(n)return n;const{members:e}=s,l=new Map;for(const r of i)l.set(r.key,r.dies.filter(f=>e.has(f)));return s.byFamily.set(i,l),l}function ue(t,i){adjustPValues(t);for(const n of t){const e=U.get(n);Ae(n,twoProportionZ(e.hits,e.n,e.restHits,e.restN),e)}const s=t.filter(n=>passesRateGate(n.stats.adjustedPValue??n.stats.pValue??1,n.effect.absoluteDelta??0,rateRelativeEffect(U.get(n)),i));return s.filter(n=>!Mt(n,s,i)).map(n=>({...n,severity:severityForFinding(n.stats.adjustedPValue??n.stats.pValue??1,n.effect.absoluteDelta??0,rateRelativeEffect(U.get(n)))}))}export function passesRateGate(t,i,s,n){return t<=n.significanceLevel&&(Math.abs(i)>=n.minimumEffectSize||s>=n.minimumRelativeEffect)}export function claimForPattern(t,i,s,n,e){const l=[];for(const r of s){const f=r.comparison.family,c=f==="ring"?n(r):[];t.some(o=>ct(o,f,c,e))&&(l.push(r.id),i!=="info"&&(f==="ring"||f==="quadrant"||f==="sector")&&(r.severity="info"))}return l}function Mt(t,i,s){const n=U.get(t);if(!n)return!1;const e=t.stats.pValue??1;let{restHits:l,restN:r}=n;for(const u of We(t,i)){const a=U.get(u);a&&(l-=a.hits,r-=a.n)}if(r===n.restN)return!1;if(r<s.minimumSampleSize)return!0;const f=n.hits/n.n-l/r;if(Math.sign(f)!==Math.sign(t.effect.absoluteDelta??0))return!0;const c=e>0?(t.stats.adjustedPValue??e)/e:1,o=Math.min(1,O(n.hits,n.n,l,r)*c);return!passesRateGate(o,f,rateRelativeEffect({...n,restHits:l,restN:r}),s)}function We(t,i){const s=t.stats.pValue??1;return i.filter(n=>n!==t&&n.effect.direction!==t.effect.direction&&n.variable.kind===t.variable.kind&&n.variable.bin===t.variable.bin&&n.variable.index===t.variable.index&&n.comparison.family===t.comparison.family&&(n.stats.pValue??1)<s)}const ze=new WeakMap;export function welchOfSums(t,i,s,n){const e=(l,r,f)=>f>1?Math.max(0,l-r*r/f)/(f-1):0;return welchFromStats(t.n,t.sum/t.n,e(t.sq,t.sum,t.n),i,s/i,e(n,s,i))}function Bt(t,i,s){const n=ze.get(t);if(!n)return!1;let{restN:e,restSum:l,restSq:r}=n;for(const h of We(t,i)){const g=ze.get(h);g&&(e-=g.n,l-=g.sum,r-=g.sq)}if(e===n.restN)return!1;if(e<s.minimumSampleSize)return!0;const{pValue:f,effectSize:c,delta:o}=welchOfSums(n,e,l,r);if(Math.sign(o)!==Math.sign(t.effect.absoluteDelta??0))return!0;const u=t.stats.pValue??1,a=u>0?(t.stats.adjustedPValue??u)/u:1;return!(Math.min(1,f*a)<=s.significanceLevel&&Math.abs(c)>=s.minimumEffectSize)}function ee(t,i,s,n){const e=new Set(s),l=ce(t,i),r=new Map,f=new Map;for(const[o,u]of l){let a=0,h=0;for(const g of u)g.hbin!==void 0&&(h++,e.has(g.hbin)&&a++);r.set(o,a),f.set(o,h)}const c=[];for(const o of i){const u=f.get(o.key)??0,a=r.get(o.key)??0;let h=0,g=0;for(const[k,S]of f)k!==o.key&&(h+=S,g+=r.get(k)??0);if(u<n.minimumSampleSize||h<n.minimumSampleSize)continue;const p=a/u,d=g/h,y=p-d,w=O(a,u,g,h);c.push(le(Z(o,{id:`yield:${o.key}`,level:"wafer",severity:"info",variable:{kind:"yield",label:"Yield"},comparison:{family:o.family,left:o.label,right:_(o.family)},effect:{direction:y===0?"different":y>0?"higher":"lower",absoluteDelta:y,relativeDelta:d===0?void 0:y/d,effectSize:y},stats:{method:"two-proportion-z",pValue:w,sampleSizeLeft:u,sampleSizeRight:h},summary:be(o.label,y,o.family),highlight:{kind:"region",regionFamily:o.family,regionKeys:[o.key],dieKeys:[...o.dieKeys]}}),{hits:a,n:u,restHits:g,restN:h,passRate:!0}))}return ue(c,n)}function E(t,i,s,n,e,l){const r=p=>s==="soft"?p.sbin:p.hbin,f=[...new Set(t.map(r).filter(p=>p!==void 0))].sort((p,d)=>p-d),c=ce(t,i),o=new Map,u=new Map;for(const[p,d]of c){const y=new Map;for(const w of d){const k=r(w);k!==void 0&&y.set(k,(y.get(k)??0)+1)}o.set(p,y),u.set(p,d.length)}const a=[],h=e==="hardBin"?"HBin":"SBin",g=s==="hard"?new Set(l.passBins):l.softPassBins??Me(t,l.passBins).soft;for(const p of i){const d=u.get(p.key)??0,y=o.get(p.key);let w=0;const k=new Map;for(const[S,$]of o)if(S!==p.key){w+=u.get(S)??0;for(const[N,F]of $)k.set(N,(k.get(N)??0)+F)}if(!(d<l.minimumSampleSize||w<l.minimumSampleSize))for(const S of f){const $=y.get(S)??0,N=k.get(S)??0,F=$/d,b=N/w,v=F-b,M=O($,d,N,w),z=Ee(S,n,h);a.push(le(Z(p,{id:`${e}:${S}:${p.key}`,level:"wafer",severity:"info",variable:{kind:e,bin:S,label:z},comparison:{family:p.family,left:p.label,right:_(p.family)},effect:{direction:v===0?"different":v>0?"higher":"lower",absoluteDelta:v,relativeDelta:b===0?void 0:v/b,effectSize:v},stats:{method:"two-proportion-z",pValue:M,sampleSizeLeft:d,sampleSizeRight:w},summary:Se(p.label,z,v,p.family),highlight:{kind:"bin",bin:S,regionKeys:[p.key],dieKeys:[...p.dieKeys]}}),{hits:$,n:d,restHits:N,restN:w,passRate:g.has(S)}))}}return ue(a,l)}function te(t,i,s,n){const e=(s??[]).filter(u=>!W(u));if(!e.length)return[];const l=e.map(u=>u.testNumber),r=ce(t,i),f=new Map,c=new Map;for(const[u,a]of r){const h=new Uint32Array(e.length),g=new Uint32Array(e.length);for(const p of a)for(let d=0;d<e.length;d++){const y=se(p,l[d],e[d]);y!==void 0&&(g[d]++,y&&h[d]++)}f.set(u,h),c.set(u,g)}const o=[];for(const u of i){const a=f.get(u.key),h=c.get(u.key);for(let g=0;g<e.length;g++){let p=0,d=0;for(const[b,v]of c)b!==u.key&&(d+=v[g],p+=f.get(b)[g]);const y=h[g],w=a[g];if(y<n.minimumSampleSize||d<n.minimumSampleSize)continue;const k=w/y,S=p/d,$=k-S,N=O(w,y,p,d),F=l[g];o.push(le(Z(u,{id:`functional:${F}:${u.key}`,level:"wafer",severity:"info",variable:{kind:"functionalTest",index:F,label:`${T(e[g],F)} pass rate`,...oe(e[g])},comparison:{family:u.family,left:u.label,right:_(u.family)},effect:{direction:$===0?"different":$>0?"higher":"lower",absoluteDelta:$,relativeDelta:S===0?void 0:$/S,effectSize:$},stats:{method:"two-proportion-z",pValue:N,sampleSizeLeft:y,sampleSizeRight:d},summary:we(u.label,T(e[g],F),$,u.family),highlight:{kind:"region",regionFamily:u.family,regionKeys:[u.key],dieKeys:[...u.dieKeys]}}),{hits:w,n:y,restHits:p,restN:d,passRate:!0}))}}return ue(o,n)}export function welchFromStats(t,i,s,n,e,l){const r=Math.sqrt(s/t+l/n),f=i-e;if(!Number.isFinite(r)||r===0)return{pValue:1,effectSize:0,delta:f,z:0};const c=f/r,o=Math.sqrt(Math.max(0,(s+l)/2)),u=o===0?f:f/o;return{pValue:Ve(2*(1-Ce(Math.abs(c)))),effectSize:u,delta:f,z:c}}function Nt(t,i){const s=ae(t),n=ae(i);return welchFromStats(t.length,s,he(t,s),i.length,n,he(i,n))}const Ye=250;function _e(t,i,s){const n=r=>r.filter(f=>W(s?.find(c=>c.testNumber===f)));if(i)return{testNumbers:n(i.slice().sort((r,f)=>r-f))};const e=Pe(t,"values");if(e.length>Ye){const r=`Test-value analysis was skipped: more than ${Ye} tests were found in the die data, so no test findings were computed. Pass testNumbers: [...] to analyse specific tests.`;return console.warn(`[wafermap] analyzeWaferMap: ${r}`),{testNumbers:[],warning:{code:"test-count-capped",message:r,severity:"warning"}}}return{testNumbers:n(e)}}function ne(t,i,s,n){const e=_e(t,n.testNumbers,s);if(e.warning)return{findings:[],warning:e.warning};const l=e.testNumbers,r=new Map;for(let d=0;d<i.length;d++)for(const y of I(i[d].dies))r.set(y,d);const f=i.length,c=[],o=[];for(const d of t){const y=r.get(me(d));y!==void 0&&(c.push(d),o.push(y))}const u=[],a=new Float64Array(f),h=new Float64Array(f),g=new Float64Array(f);for(const d of l){a.fill(0),h.fill(0),g.fill(0);let y=0,w=0,k=0,S;for(let $=0;$<c.length;$++){const N=c[$],F=j(N,d);if(F===void 0)continue;S===void 0&&(S=F);const b=F-S,v=o[$];a[v]+=1,h[v]+=b,g[v]+=b*b,y+=1,w+=b,k+=b*b}if(S!==void 0)for(let $=0;$<f;$++){const N=a[$],F=y-N;if(N<n.minimumSampleSize||F<n.minimumSampleSize)continue;const b=h[$]/N,M=(w-h[$])/F,z=b+S,D=M+S,C=N>1?Math.max(0,g[$]-N*b*b)/(N-1):0,m=F>1?Math.max(0,k-g[$]-F*M*M)/(F-1):0,{pValue:R,effectSize:P,delta:B,z:x}=welchFromStats(N,z,C,F,D,m),V=i[$],{label:L,unit:q,...H}=Dt(d,s),K=D!==0?B/Math.abs(D):void 0,A=Z(V,{id:`test:${d}:${V.key}`,level:"wafer",severity:"info",variable:{kind:"test",index:d,label:L,unit:q,...H},comparison:{family:V.family,left:V.label,right:_(V.family)},effect:{direction:B===0?"different":B>0?"higher":"lower",absoluteDelta:B,relativeDelta:K,effectSize:P},stats:{method:"welch-z-approx",pValue:R,sampleSizeLeft:N,sampleSizeRight:F},summary:ve(V.label,L,B,K,V.family,q),highlight:{kind:"region",regionFamily:V.family,regionKeys:[V.key],dieKeys:[...V.dieKeys]}}),Re={n:N,sum:h[$],sq:g[$],restN:F,restSum:w-h[$],restSq:k-g[$],shift:S};ze.set(A,Re),Ae(A,x,void 0,Re),u.push(A)}}adjustPValues(u);const p=u.filter(d=>{const y=d.stats.adjustedPValue??d.stats.pValue??1,w=Math.abs(d.effect.effectSize??0);return y<=n.significanceLevel&&w>=n.minimumEffectSize});return{activeTestNumbers:l,findings:p.filter(d=>!Bt(d,p,n)).map(d=>({...d,severity:severityForScore(d.stats.adjustedPValue??d.stats.pValue??1,d.effect.effectSize??0)}))}}function Ft(t,i,s,n){if(!s?.length)return[];const e=s.filter(r=>W(r)&&(r.limitLow!==void 0||r.limitHigh!==void 0));if(!e.length)return[];const l=[];for(const r of e){const f=r.testNumber;for(const c of i){const o=ce(t,c),u=[],a=new Map;let h=0,g=0;for(const[p,d]of o){let y=0,w=0;for(const k of d){const S=j(k,f);S!==void 0&&(y++,ge(re(S,r))&&w++)}a.set(p,{valid:y,fail:w}),h+=y,g+=w}for(const p of c){const d=a.get(p.key),y=d.valid,w=h-d.valid;if(y<n.minimumSampleSize||w<n.minimumSampleSize)continue;const k=d.fail,S=g-d.fail,$=k/y,N=S/w,F=$-N,b=O(k,y,S,w);u.push(le(Z(p,{id:`specLimit:${f}:${p.key}`,level:"wafer",severity:"info",variable:{kind:"test",index:f,label:T(r,f),unit:r.unit,...oe(r)},comparison:{family:p.family,left:p.label,right:_(p.family)},effect:{direction:F===0?"different":F>0?"higher":"lower",absoluteDelta:F,relativeDelta:N===0?void 0:F/N,effectSize:F},stats:{method:"two-proportion-z",pValue:b,sampleSizeLeft:y,sampleSizeRight:w},summary:$e(p.label,T(r,f),F),highlight:{kind:"region",regionFamily:p.family,regionKeys:[p.key],dieKeys:[...p.dieKeys]}}),{hits:k,n:y,restHits:S,restN:w,passRate:!1}))}l.push(...ue(u,n))}}return l}function ke(t,i){return t==="softBin"?i.softEligibleDies:t==="test"?i.testDies:i.eligibleDies}function Pt(t){return t.id.startsWith("specLimit:")}function ie(t){return t.highlight.regionKeys??[]}function xt(t){const i=t.variable.bin??t.variable.index??"";return`${t.comparison.family}\0${Qe(t)}\0${t.variable.kind}\0${i}\0${t.effect.direction}`}function Ct(t,i){const s=Y(t);return s.family==="ring"?s.ring??0:s.family==="sector"?xe(i).indexOf(s.sector??""):0}export function inQuadrantOrder(t){const i=new Set(t),s=pe.findIndex((e,l)=>i.has(e)&&!i.has(pe[(l+3)%4])),n=s<0?0:s;return Array.from({length:4},(e,l)=>pe[(n+l)%4]).filter(e=>i.has(e))}export function findContiguousRuns(t,i,s,n){if(i==="quadrant"){const c=new Map;for(const h of t){const g=Y(n(h)).quadrant;g&&c.set(g,h)}const o=[...c.keys()],u=new Set,a=[];for(const h of o){if(u.has(h))continue;const g=[],p=[h];for(u.add(h);p.length;){const d=p.pop();g.push(d);for(const y of o)!u.has(y)&&at(d,y)&&(u.add(y),p.push(y))}a.push(inQuadrantOrder(g).map(d=>c.get(d)))}return a}const e=c=>Ct(n(c),s),l=[...t].sort((c,o)=>e(c)-e(o)),r=[];let f=[];for(const c of l){if(f.length===0){f.push(c);continue}const o=e(f[f.length-1]);e(c)-o===1?f.push(c):(r.push(f),f=[c])}if(f.length&&r.push(f),i==="sector"&&r.length>1){const o=xe(s).length,u=e(r[0][0]),a=e(r[r.length-1][r[r.length-1].length-1]);if(u===0&&a===o-1){const h=r.pop();r[0]=[...h,...r[0]]}}return r}export function mergedRegionLabel(t,i,s){if(t==="ring"){const e=i.map(c=>Y(c).ring).filter(c=>c!==void 0).sort((c,o)=>c-o),l=e[0],r=e[e.length-1];let f="";return l===r&&l===1&&s>1?f=" (core)":l===r&&l===s&&s>1&&(f=" (edge)"),l===r?`Ring ${l}${f}`:`Rings ${l}\u2013${r}`}if(t==="sector"){const e=i.map(l=>Y(l).sector??"");return e.length===1?`Sector ${e[0]}`:`Sectors ${e[0]}\u2013${e[e.length-1]}`}const n=i.map(e=>Y(e).quadrant??"");return n.length===1?n[0]:n.length===2?`Quadrants ${n[0]} & ${n[1]}`:`Quadrants ${n.slice(0,-1).join(", ")} & ${n[n.length-1]}`}function De(t){return[...new Set(t)]}export function weakestMultiplier(t){return bt(t.map(i=>{const s=i.stats.pValue??1;return s>0?(i.stats.adjustedPValue??s)/s:1}))}function G(t,i){return Math.min(1,t*i)}function Vt(t,i){const s=t[0],n=s.comparison.family,e=s.variable.kind,l=De(t.flatMap(ie));let r,f;const c=t.map(je);if(c.every(b=>b!==void 0)){const b=new Set;r=[];for(const M of c){const z=I(M.dies);for(let D=0;D<z.length;D++)b.has(z[D])||(b.add(z[D]),r.push(M.dieKeys[D]))}const v=I(ke(s.variable.kind,i));f=M=>b.has(v[M])}else{r=De(t.flatMap(M=>M.highlight.dieKeys??[]));const b=new Set(r),v=Rt(ke(s.variable.kind,i));f=M=>b.has(v[M])}const o=mergedRegionLabel(n,t.map(b=>ie(b)[0]??""),i.ringCount),u=ke(e,i),a=i.regionDies[n],h=I(u),g=[],p=[];for(let b=0;b<u.length;b++)a.has(h[b])&&(f(b)?g:p).push(u[b]);const d=weakestMultiplier(t);let y,w,k,S,$;if(Pt(s)){const b=s.variable.index,v=i.testDefs?.find(x=>x.testNumber===b),M=x=>{let V=0,L=0;for(const q of x){const H=j(q,b);H!==void 0&&(V++,v&&ge(re(H,v))&&L++)}return{valid:V,fail:L}},z=M(g),D=M(p),C=z.valid>0?z.fail/z.valid:0,m=D.valid>0?D.fail/D.valid:0,R=C-m,P=O(z.fail,z.valid,D.fail,D.valid);y={direction:R===0?"different":R>0?"higher":"lower",absoluteDelta:R,relativeDelta:m===0?void 0:R/m,effectSize:R},w={method:"two-proportion-z",pValue:P,sampleSizeLeft:z.valid,sampleSizeRight:D.valid};const B=G(P,d);k=severityForFinding(B,R,rateRelativeEffect({hits:z.fail,n:z.valid,restHits:D.fail,restN:D.valid,passRate:!1})),S=$e(o,T(v,b),R),$=`specLimit:${b}`}else if(e==="test"){const b=s.variable.index,v=x=>j(x,b),M=g.map(v).filter(x=>x!==void 0),z=p.map(v).filter(x=>x!==void 0),{pValue:D,effectSize:C,delta:m}=Nt(M,z),R=ae(z),P=R!==0?m/Math.abs(R):void 0;y={direction:m===0?"different":m>0?"higher":"lower",absoluteDelta:m,relativeDelta:P,effectSize:C},w={method:"welch-z-approx",pValue:D,sampleSizeLeft:M.length,sampleSizeRight:z.length};const B=G(D,d);k=severityForScore(B,C),S=ve(o,s.variable.label,m,P,n,s.variable.unit),$=`test:${b}`}else if(e==="yield"){const b=new Set(i.passBins),v=g.filter(L=>L.hbin!==void 0),M=p.filter(L=>L.hbin!==void 0),z=v.length,D=M.length,C=v.filter(L=>b.has(L.hbin)).length,m=M.filter(L=>b.has(L.hbin)).length,R=z>0?C/z:0,P=D>0?m/D:0,B=R-P,x=O(C,z,m,D);y={direction:B===0?"different":B>0?"higher":"lower",absoluteDelta:B,relativeDelta:P===0?void 0:B/P,effectSize:B},w={method:"two-proportion-z",pValue:x,sampleSizeLeft:z,sampleSizeRight:D};const V=G(x,d);k=severityForFinding(V,B,rateRelativeEffect({hits:C,n:z,restHits:m,restN:D,passRate:!0})),S=be(o,B,n),$="yield"}else if(e==="functionalTest"){const b=s.variable.index,v=i.testDefs?.find(V=>V.testNumber===b);let M=0,z=0,D=0,C=0;for(const V of g){const L=se(V,b,v);L!==void 0&&(z++,L&&M++)}for(const V of p){const L=se(V,b,v);L!==void 0&&(C++,L&&D++)}const m=z>0?M/z:0,R=C>0?D/C:0,P=m-R,B=O(M,z,D,C);y={direction:P===0?"different":P>0?"higher":"lower",absoluteDelta:P,relativeDelta:R===0?void 0:P/R,effectSize:P},w={method:"two-proportion-z",pValue:B,sampleSizeLeft:z,sampleSizeRight:C};const x=G(B,d);k=severityForFinding(x,P,rateRelativeEffect({hits:M,n:z,restHits:D,restN:C,passRate:!0})),S=we(o,T(v,b),P,n),$=`functional:${b}`}else{const b=s.variable.bin,v=x=>e==="softBin"?x.sbin:x.hbin,M=g.filter(x=>v(x)===b).length,z=p.filter(x=>v(x)===b).length,D=M/g.length,C=z/p.length,m=D-C,R=O(M,g.length,z,p.length);y={direction:m===0?"different":m>0?"higher":"lower",absoluteDelta:m,relativeDelta:C===0?void 0:m/C,effectSize:m},w={method:"two-proportion-z",pValue:R,sampleSizeLeft:g.length,sampleSizeRight:p.length};const P=G(R,d);k=severityForFinding(P,m,rateRelativeEffect({hits:M,n:g.length,restHits:z,restN:p.length,passRate:!1}));const B=e==="softBin"?i.sbinDefs:i.hbinDefs;S=Se(o,Ee(b,B,e==="softBin"?"SBin":"HBin"),m,n),$=`${e}:${b}`}w={...w,adjustedPValue:G(w.pValue??1,d)};const N=De(l.map(b=>b.replace(`${n}:`,""))).join("-"),F=e==="hardBin"||e==="softBin"?{kind:"bin",bin:s.variable.bin,regionKeys:l,dieKeys:r}:{kind:"region",regionFamily:n,regionKeys:l,dieKeys:r};return{...s,id:`${$}:${n}:${N}`,severity:k,comparison:{family:n,left:o,right:_(n)},effect:y,stats:w,summary:S,highlight:F,relatedIds:t.map(b=>b.id)}}function Lt(t,i){const s=new Set(["ring","quadrant","sector"]),n=[],e=new Map;for(const r of t){if(!s.has(r.comparison.family)){n.push(r);continue}const f=xt(r),c=e.get(f)??[];c.push(r),e.set(f,c)}const l=[];for(const r of e.values()){if(r.length===1){l.push(r[0]);continue}const f=r[0].comparison.family;for(const c of findContiguousRuns(r,f,i.sectorCount,o=>ie(o)[0]??""))l.push(c.length===1?c[0]:Vt(c,i))}return[...n,...l]}function Kt(t){const i=new Map,s=new Map;for(const e of t){const l=me(e);e.hbin!==void 0&&e.hbin!==null&&(i.get(e.hbin)??i.set(e.hbin,new Set).get(e.hbin)).add(l),e.sbin!==void 0&&e.sbin!==null&&(s.get(e.sbin)??s.set(e.sbin,new Set).get(e.sbin)).add(l)}const n=new Set;for(const[e,l]of i)for(const[r,f]of s){if(l.size!==f.size)continue;let c=!0;for(const o of l)if(!f.has(o)){c=!1;break}c&&n.add(`${e}:${r}`)}return n}function Et(t,i){const s=new Set(i);let n;for(const e of t){const l=Be(e,s);if(l!==void 0&&l){if(e.sbin==null||n!==void 0&&e.sbin!==n)return;n=e.sbin}}if(n!==void 0){for(const e of t)if(e.sbin===n&&Be(e,s)!==!0)return;return n}}function Ot(t){return`${t.comparison.family}\0${t.comparison.left}`}export function redundancyFacts(t,i,s){return{coincident:Kt(t),yieldSoftBin:Et(t,i),passBins:i,sectorCount:s}}const Tt=3/5;function Qe(t){return/^(?:lot-region:)?([^:|]+)/.exec(t.id)?.[1]??t.id}function qt(t){const i=ie(t);if(i.length)return i;const s=/(ring|sector|quadrant):([^:|]+)$/.exec(t.id);return s?s[2].split("-").map(n=>`${s[1]}:${n}`):[]}function Ue(t,i){const s=new Set;for(const n of qt(t)){const e=rt(n,i);if(!e)return;for(const l of e)s.add(l)}return s.size?s:void 0}export function collapseRedundantFindings(t,i){const{coincident:s,yieldSoftBin:n,passBins:e}=i,l=(o,u)=>{o.absorbedIds=[...o.absorbedIds??[],u.id]},r=new Map;for(const o of t){const u=Ot(o);(r.get(u)??r.set(u,[]).get(u)).push(o)}const f=new Set;for(const o of r.values()){for(const a of o)if(!(a.variable.kind!=="hardBin"||a.variable.bin===void 0))for(const h of o){if(h.variable.kind!=="softBin"||h.variable.bin===void 0||f.has(h.id)||!s.has(`${a.variable.bin}:${h.variable.bin}`)||h.effect.direction!==a.effect.direction)continue;l(a,h),f.add(h.id);const g=a.variable.label.replace(/^HBin\s+/,""),p=h.variable.label.replace(/^SBin\s+/,""),d=g===p?`HBin and SBin ${g} (same dies)`:`${a.variable.label} and ${h.variable.label} (same dies)`;a.summary=a.summary.replace(a.variable.label,d),a.variable.label=d;break}const u=o.find(a=>a.variable.kind==="yield");if(u){for(const a of o)if(!(a===u||f.has(a.id)||!(a.variable.kind==="hardBin"&&e.length===1&&a.variable.bin===e[0]||a.variable.kind==="softBin"&&a.variable.bin===n))){l(u,a),f.add(a.id);for(const g of a.absorbedIds??[])u.absorbedIds=[...u.absorbedIds??[],g]}}}const c=new Map;for(const o of t){if(f.has(o.id)||o.comparison.family!=="sector"&&o.comparison.family!=="quadrant")continue;const u=[Qe(o),o.variable.kind,o.variable.bin??"",o.variable.index??"",o.effect.direction].join("\0");(c.get(u)??c.set(u,[]).get(u)).push(o)}for(const o of c.values()){const u=[];for(const a of o.filter(h=>h.comparison.family==="sector")){const h=Ue(a,i.sectorCount);if(h)for(const g of o.filter(p=>p.comparison.family==="quadrant")){const p=Ue(g,i.sectorCount);if(!p)continue;let d=0;for(const w of h)p.has(w)&&d++;const y=h.size+p.size-d;d/y>=Tt-1e-9&&u.push({sector:a,quadrant:g,overlap:d/y})}}u.sort((a,h)=>h.overlap-a.overlap);for(const{sector:a,quadrant:h}of u){if(f.has(a.id)||f.has(h.id))continue;const g=(h.stats.pValue??1)<(a.stats.pValue??1),[p,d]=g?[h,a]:[a,h];l(p,d),f.add(d.id),p.absorbedIds=[...p.absorbedIds??[],...d.absorbedIds??[]]}}}export function analyzeWaferMap(t,i={}){const s=Q,n=J,e=[];Q=e,J=void 0;try{const l=Ht(t,i);return He.set(l,{candidates:e,facts:J}),l}finally{Q=s,J=n}}function Ht(t,i){const{resolved:s,warnings:n}=resolveOptions(i),e=Ge(t),l={...s,passBins:[...mt(e,"analyzeWaferMap")],ringCount:pt(e,"analyzeWaferMap")},r=e.isLotStack,f=e.aggrMethod,c=!r||f==="mode"||f==="countBin"||f==="percent",o=e.dies.filter(m=>wt(m)),u=o.filter(Fe),a=St(l,o.length);a.softPassBins=Me(o,a.passBins).soft;const h=e.dies.filter(m=>de(m)),g=h.filter(Fe),p=it(g,e.wafer,a.ringCount),d=tt(g,e.wafer,a.ringCount),y=nt(g,e.reticleConfig),w=ot(h,!1),k=st(g,e.wafer,a.sectorCount),S=[];c&&S.push(...ee(o,p,a.passBins,a),...ee(o,d,a.passBins,a),...ee(o,y,a.passBins,a),...ee(o,w,a.passBins,a),...ee(o,k,a.passBins,a)),c&&S.push(...E(o,p,"hard",e.hbinDefs,"hardBin",a),...E(o,d,"hard",e.hbinDefs,"hardBin",a),...E(o,y,"hard",e.hbinDefs,"hardBin",a),...E(o,w,"hard",e.hbinDefs,"hardBin",a),...E(o,k,"hard",e.hbinDefs,"hardBin",a));{const m=o.filter(R=>R.sbin!==void 0);S.push(...E(m,p,"soft",e.sbinDefs,"softBin",a),...E(m,d,"soft",e.sbinDefs,"softBin",a),...E(m,y,"soft",e.sbinDefs,"softBin",a),...E(m,w,"soft",e.sbinDefs,"softBin",a),...E(m,k,"soft",e.sbinDefs,"softBin",a))}const $=[...n];let N;if(a.enableTestValueAnalysis){const m=ne(o,p,e.testDefs,a),R=ne(o,d,e.testDefs,a),P=ne(o,y,e.testDefs,a),B=ne(o,w,e.testDefs,a),x=ne(o,k,e.testDefs,a);S.push(...m.findings,...R.findings,...P.findings,...B.findings,...x.findings),m.warning&&$.push(m.warning),N=m.activeTestNumbers,S.push(...Ft(o,[p,d,y,w,k],e.testDefs,a)),S.push(...te(o,p,e.testDefs,a),...te(o,d,e.testDefs,a),...te(o,y,e.testDefs,a),...te(o,w,e.testDefs,a),...te(o,k,e.testDefs,a))}{const m=vt(r,c,e.testDefs);(!r||c||m!==void 0)&&S.push(...ft(u,e.wafer,{...a,isFailingDie:m}))}const F=Lt(S,{eligibleDies:o,softEligibleDies:o.filter(m=>m.sbin!==void 0),testDies:o,passBins:a.passBins,ringCount:a.ringCount,sectorCount:a.sectorCount,regionDies:{ring:new Set(p.flatMap(m=>I(m.dies))),quadrant:new Set(d.flatMap(m=>I(m.dies))),sector:new Set(k.flatMap(m=>I(m.dies)))},hbinDefs:e.hbinDefs,sbinDefs:e.sbinDefs,testDefs:e.testDefs});S.length=0,S.push(...F);let b;if(c){const m=lt(u,e.wafer,{passBins:a.passBins,ringCount:a.ringCount});if(b=m??void 0,m!==null&&m.pattern!=="random"&&m.pattern!=="none"){const R=dt[m.pattern],P=m.confidence==="high"?"unusual":m.confidence==="medium"?"notable":"info",B=m.features,x=K=>`${(K*100).toFixed(0)}%`,V=m.pattern==="edge-ring"||m.pattern==="edge-local"?`${x(B.edgeRdd)} of edge dies failing`:m.pattern==="center"||m.pattern==="donut"?`centroid at ${x(B.centroidDistNorm)} of wafer radius from centre`:m.pattern==="scratch"?`linear score ${B.linearScore.toFixed(2)}, eccentricity ${B.eccentricity.toFixed(2)}`:`${x(B.globalRdd)} of dies failing`,L=new Set(a.passBins),q=o.filter(K=>ut(K,L)===!0),H=claimForPattern([m.pattern],P,S,K=>ie(K).map(A=>Y(A).ring).filter(A=>A!==void 0),a.ringCount);S.push({id:`spatial-pattern:${m.pattern}`,level:"wafer",severity:P,variable:{kind:"spatialPattern",label:R},comparison:{family:"spatial-pattern",left:R,right:"Wafer"},effect:{direction:"different",effectSize:B.globalRdd},stats:{method:"geometry",sampleSizeLeft:q.length,sampleSizeRight:o.length},summary:`Spatial pattern: ${R.toLowerCase()} (${m.confidence} confidence) \u2014 ${V}${m.note?` [${m.note}]`:""}`,highlight:{kind:"dies",dieKeys:q.map(K=>Ne(K))},relatedIds:H.length>0?H:void 0})}}S.sort((m,R)=>{const P=m.stats.adjustedPValue??m.stats.pValue??1,B=R.stats.adjustedPValue??R.stats.pValue??1;return P!==B?P-B:Math.abs(R.effect.absoluteDelta??0)-Math.abs(m.effect.absoluteDelta??0)});const v=$t(e.dies,o.length,e.yield.yieldPercent);r&&(v.isLotStack=!0,f&&(v.aggregationMethod=f));const M=zt(e.dies,e.testDefs);M&&(v.testSpecYield=M);const z=computeFunctionalYield(e.dies,e.testDefs);if(z&&(v.functionalYield=z),b&&(v.spatialPattern=b),N===void 0&&a.computePerTestStats){const m=_e(o,a.testNumbers,e.testDefs);m.warning&&$.push(m.warning),N=m.testNumbers}if(N?.length){const m=kt(e.dies,N,e.testDefs,a.minimumSampleSize);m&&(v.perTestStats=m);const R=Xe([{dies:e.dies}],e.testDefs,N);R&&(v.capability=R)}Object.assign(v,Ze(e.dies,e.testDefs));const D=Je([{dies:e.dies,wafer:e.wafer,passBins:a.passBins,ringCount:a.ringCount}]);D&&(v.regionYield=D),$.length>0&&(v.warnings=$);const C=redundancyFacts(o,a.passBins,a.sectorCount);return collapseRedundantFindings(S,C),Q&&(J=C),{level:"wafer",hasNotableFindings:S.some(m=>m.severity==="notable"||m.severity==="unusual"),findings:S,wafer:e.wafer.metadata??void 0,stats:v}}
1
+ import{normalizeInput as Ze}from"./normalizeInput.js";import{computeCapability as Je,computeTestFlagYield as et,computeRegionYield as tt}from"./summaryFigures.js";import{binPassSets as xe}from"../renderer/binColors.js";import{diePassStatus as pe,isYieldEligibleDie as ge,getDieKey as be,isPositionedDie as Pe,positionKey as ye}from"../core/dies.js";import{dieHasValues as nt,testsPresent as Ce,testValue as j}from"../core/dieTable.js";import{getTestPassStatus as re,isParametricTest as _}from"../renderer/buildWaferMap.js";import{markedTestLabel as T,derivedFields as fe}from"../renderer/testLabel.js";import{buildQuadrantRegions as it,buildReticlePositionRegions as st,buildRingRegions as ot,buildSectorRegions as at,buildTestSiteRegions as rt,sectorCompassNames as Ve,areQuadrantsAdjacent as ft,parseRegionKey as Q,QUADRANT_CYCLE as Se,regionAngleBins as lt}from"./regions.js";import{buildClusterFindings as ct}from"./clusterDetection.js";import{classifyPattern as ut,patternExplains as dt,patternFailVerdict as mt,PATTERN_LABELS as ht}from"./patternClassification.js";import{requirePassBins as pt}from"../core/passBins.js";import{requireRingCount as gt}from"../core/ringCount.js";import{benjaminiHochberg as bt,fisherExact as yt,fiveNumberSummary as St,sampleVariance as we,zPValue as Ee}from"./math.js";import{mean as le,maxOf as wt}from"../core/utils.js";import{classifySpec as ce,isOutOfSpec as ve}from"../renderer/spec.js";const vt={significanceLevel:{min:1e-6,max:1},minimumEffectSize:{min:0,max:1},minimumRelativeEffect:{min:0,max:Number.MAX_SAFE_INTEGER}},Le=[4,8,16];export function resolveOptions(t){const n=Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)),i={...J,...n},s=[],e=[];for(const r of["significanceLevel","minimumEffectSize","minimumRelativeEffect"]){const{min:c,max:o}=vt[r],u=i[r];if(typeof u!="number"||!Number.isFinite(u)){e.push(`${r}=${String(u)} is not a finite number (using ${J[r]})`),i[r]=J[r];continue}const f=Math.min(o,Math.max(c,u));f!==u&&(e.push(`${r}=${u} is outside ${c}\u2013${o} (using ${f})`),i[r]=f)}if(Le.includes(i.sectorCount)||(e.push(`sectorCount=${i.sectorCount} is not one of ${Le.join(", ")} (using ${J.sectorCount})`),i.sectorCount=J.sectorCount),e.length){const r=`analyzeWaferMap: ${e.join("; ")}. The analysis ran with the corrected values.`;console.warn(`[wafermap] ${r}`),s.push({code:"analysis-option-corrected",message:r,severity:"warning"})}const a=["passBins","ringCount"].filter(r=>n[r]!==void 0);if(a.length){const r=`analyzeWaferMap: ${a.join(" and ")} ${a.length>1?"are":"is"} no longer an analysis option and was ignored. Set ${a.length>1?"them":"it"} on buildWaferMap; the analysis used the value the map was built with.`;console.warn(`[wafermap] ${r}`),s.push({code:"analysis-option-corrected",message:r,severity:"warning"})}const l=["enableYieldAnalysis","enableHardBinAnalysis","enableSoftBinAnalysis","enableReticlePositionAnalysis","enableTestSiteAnalysis","enableClusterAnalysis","enableAngularAnalysis","enablePatternClassification"].filter(r=>n[r]!==void 0);if(l.length){const r=`analyzeWaferMap: ${l.join(", ")} ${l.length>1?"are":"is"} no longer an option and was ignored: every analysis now runs. Filter the findings (filterFindings) to show fewer.`;console.warn(`[wafermap] ${r}`),s.push({code:"analysis-option-corrected",message:r,severity:"warning"})}return{resolved:i,warnings:s}}const J={significanceLevel:.05,minimumEffectSize:.2,minimumRelativeEffect:1,minimumSampleSize:5,enableTestValueAnalysis:!1,computePerTestStats:!1,sectorCount:8,minimumClusterSize:5};function $t(t,n){const i={...t};return i.minimumClusterSize=Math.max(5,Math.round(n*.003)),i}function kt(t){return ge(t)?t.hbin!==void 0||t.sbin!==void 0||nt(t):!1}function Rt(t,n,i){if(!t||n)return;const s=(i??[]).filter(e=>_(e)&&(e.limitLow!==void 0||e.limitHigh!==void 0));if(s.length!==0)return e=>{for(const a of s)if(ve(ce(j(e,a.testNumber),a)))return!0;return!1}}function Dt(t,n,i){const s=new Set,e=new Set,a=new Set,l=new Map,r=new Map;for(const c of Ce(t))s.add(c);for(const c of t)c.hbin!==void 0&&e.add(c.hbin),c.sbin!==void 0&&a.add(c.sbin),ge(c)&&(c.hbin!==void 0&&l.set(c.hbin,(l.get(c.hbin)??0)+1),c.sbin!==void 0&&r.set(c.sbin,(r.get(c.sbin)??0)+1));return{totalDies:t.length,analyzedDies:n,excludedDies:t.length-n,yieldPercent:i,testsConsidered:[...s].sort((c,o)=>c-o),hardBinsConsidered:[...e].sort((c,o)=>c-o),softBinsConsidered:[...a].sort((c,o)=>c-o),...l.size?{hardBinCounts:Object.fromEntries(l)}:{},...r.size?{softBinCounts:Object.fromEntries(r)}:{}}}function Mt(t,n,i){if(!n?.length)return;const s=n.filter(a=>_(a)&&(a.limitLow!==void 0||a.limitHigh!==void 0));if(!s.length)return;const e=[];for(const a of s){const l=a.testNumber;let r=0,c=0,o=0,u=0;for(const f of t){if(f.partial||f.edgeExcluded)continue;const h=ce(j(f,l),a);if(h!==null){if(u++,h==="failLow")c++;else if(h==="failHigh")o++;else{r++;continue}i?.(l,f)}}e.push({testNumber:l,label:a.name,passDies:r,failLowDies:c,failHighDies:o,totalDies:u,yieldPercent:u>0?r/u*100:null})}return e.length?e:void 0}export function computeFunctionalYield(t,n,i){if(!n?.length)return;const s=n.filter(a=>!_(a));if(!s.length)return;const e=[];for(const a of s){const l=a.testNumber;let r=0,c=0;for(const u of t){if(u.partial||u.edgeExcluded)continue;const f=re(u,l,a);if(f!==void 0){if(f){r++;continue}c++,i?.(l,u)}}const o=r+c;e.push({testNumber:l,label:T(a,l),...fe(a),passDies:r,failDies:c,totalDies:o,passRatePercent:o>0?r/o*100:null})}return e.length?e:void 0}function zt(t,n,i,s){const e=[];for(const a of n){const l=[];for(const f of t){if(f.partial||f.edgeExcluded)continue;const h=j(f,a);h!==void 0&&Number.isFinite(h)&&l.push(h)}if(l.length<s)continue;const r=le(l),c=Math.sqrt(we(l,r)),o=St(Float64Array.from(l)),u=i?.find(f=>f.testNumber===a)?.name??String(a);e.push({testNumber:a,label:u,count:l.length,min:o.min,max:o.max,mean:r,stddev:c,median:o.median,q1:o.q1,q3:o.q3})}return e.length?e:void 0}export function twoProportionZ(t,n,i,s){const e=(t+i)/(n+s),a=e*(1-e)*(1/n+1/s);return!Number.isFinite(a)||a<=0?0:(t/n-i/s)/Math.sqrt(a)}const Bt=5;function q(t,n,i,s){const e=n+s,a=t+i;if((e>0?Math.min(a,e-a)*Math.min(n,s)/e:0)<Bt)return{pValue:yt(t,n-t,i,s-i),method:"fisher-exact"};const r=twoProportionZ(t,n,i,s);return{pValue:r===0?1:Ee(r),method:"two-proportion-z"}}function Ft(t,n,i,s){return q(t,n,i,s).pValue}export function adjustPValues(t){const n=t.filter(s=>s.stats.pValue!==void 0),i=bt(n.map(s=>s.stats.pValue));return n.forEach((s,e)=>{s.stats.adjustedPValue=i[e]}),t}export function rateRelativeEffect(t){const n=(t.passRate?t.n-t.hits:t.hits)/t.n,i=(t.passRate?t.restN-t.restHits:t.restHits)/t.restN;return i===0?n===0?0:1/0:Math.abs(n-i)/i}export function severityForFinding(t,n,i){const s=Math.abs(n),e=i;return t<=.01&&(s>=.3||e>=2.5)?"unusual":t<=.05&&(s>=.2||e>=1.5)?"notable":"info"}export function severityForScore(t,n){return t<=.01&&Math.abs(n)>=.5?"unusual":t<=.05&&Math.abs(n)>=.15?"notable":"info"}function ue(t){return t==="reticle-position"?"other reticle positions":t==="test-site"?"other test sites":"the rest of the map"}function U(t){return t==="reticle-position"?"Other reticle positions":t==="test-site"?"Other test sites":"Rest of map"}function $e(t,n,i){const s=(Math.abs(n)*100).toFixed(1);return`${t} yield is ${s} percentage points ${n>0?"higher":"lower"} than ${ue(i)}`}function ke(t,n){return n==="quadrant"&&!t.startsWith("Quadrant")?`quadrant ${t}`:t}function Ke(t){return/^(Rings|Sectors|Quadrants)\b/.test(t)?"have":"has"}function Re(t,n,i,s){const e=ke(t,s),a=(Math.abs(i)*100).toFixed(1);return`${e} ${Ke(e)} ${n} occurrence ${a} percentage points ${i>0?"higher":"lower"} than ${ue(s)}`}function De(t,n,i,s){const e=ke(t,s),a=(Math.abs(i)*100).toFixed(1);return`${e} ${Ke(e)} ${n} pass rate ${a} percentage points ${i>0?"higher":"lower"} than ${ue(s)}`}function Me(t,n,i,s,e,a){const l=ke(t,e),r=ue(e),c=i>0?"higher":"lower";if(s!==void 0&&Number.isFinite(s)){const u=(Math.abs(s)*100).toFixed(1);return`${l} mean ${n} is ${u}% ${c} than ${r}`}const o=a?` ${a}`:"";return`${l} mean ${n} is ${Math.abs(i).toPrecision(3)}${o} ${c} than ${r}`}function Oe(t,n,i){const s=n?.find(e=>e.bin===t);return s?.name?`${i} ${t} (${s.name})`:`${i} ${t}`}function Nt(t,n){const i=n?.find(s=>s.testNumber===t);return{label:T(i,t),unit:i?.unit,...fe(i)}}const qe=new WeakMap,Te=new WeakMap,Ae=new WeakMap;function ee(t,n){const i=n.highlight.dieKeys;return i&&Ae.set(i,t),n}let G=null,te;const je=new WeakMap;export function candidatesOf(t){return je.get(t)}function He(t,n,i,s){if(!G)return;const e=Ie(t);if(!e)return;const a=t.id.slice(0,t.id.indexOf(":")),l=a==="specLimit"?"limitFail":a,{kind:r,bin:c,index:o}=t.variable;G.push({key:[l,r,c??"",o??"",e.family,e.key].join("|"),source:l,variable:t.variable,label:t.variable.label,comparison:t.comparison,region:e,z:n,delta:t.effect.absoluteDelta??0,effectSize:t.effect.effectSize??0,relativeDelta:t.effect.relativeDelta,rate:i,mean:s})}export function describeRegional(t,n,i){const s=t.comparison.left,e=t.region.family;switch(t.source){case"yield":return $e(s,n,e);case"hardBin":case"softBin":return Re(s,t.label,n,e);case"functional":return De(s,t.label.replace(/ pass rate$/,""),n,e);case"limitFail":return ze(s,t.label,n);case"test":return Me(s,t.label,n,i,e,t.variable.unit)}}function ze(t,n,i){return`${t} limit fail rate for ${n} is ${(Math.abs(i)*100).toFixed(1)} pp ${i>0?"higher":"lower"} than the rest of the wafer`}const H=new WeakMap;function de(t,n){return H.set(t,n),t}function Ie(t){const n=t.highlight.dieKeys;return n?Ae.get(n):void 0}const We=new WeakMap;function I(t){let n=We.get(t);return n||We.set(t,n=t.map(ye)),n}function xt(t){let n=qe.get(t);return n||qe.set(t,n=t.map(be)),n}function me(t,n){let i=Te.get(t);i||Te.set(t,i={members:new Set(t),byFamily:new WeakMap});const s=i.byFamily.get(n);if(s)return s;const{members:e}=i,a=new Map;for(const l of n)a.set(l.key,l.dies.filter(r=>e.has(r)));return i.byFamily.set(n,a),a}function Pt(t,n){adjustPValues(t);for(const e of t){const a=H.get(e);He(e,twoProportionZ(a.hits,a.n,a.restHits,a.restN),a)}const i=t.filter(e=>passesRateGate(e.stats.adjustedPValue??e.stats.pValue??1,e.effect.absoluteDelta??0,rateRelativeEffect(H.get(e)),n)),s=confirmRegionalFindings(i,Ye,(e,a)=>Ct(e,a,n),e=>isRateLoss(H.get(e)),t);return i.filter(e=>s.has(e)).map(e=>({...e,severity:severityForFinding(e.stats.adjustedPValue??e.stats.pValue??1,e.effect.absoluteDelta??0,rateRelativeEffect(H.get(e)))}))}export function passesRateGate(t,n,i,s){return t<=s.significanceLevel&&(Math.abs(n)>=s.minimumEffectSize||i>=s.minimumRelativeEffect)}export function claimForPattern(t,n,i,s,e){const a=[];for(const l of i){const r=l.comparison.family,c=r==="ring"?s(l):[];t.some(o=>dt(o,r,c,e))&&(a.push(l.id),n!=="info"&&(r==="ring"||r==="quadrant"||r==="sector")&&(l.severity="info"))}return a}export function confirmRegionalFindings(t,n,i,s,e=t){const a=new Map;for(const c of t)(a.get(n(c))??a.set(n(c),[]).get(n(c))).push(c);const l=new Map;if(s)for(const c of e)s(c)&&(l.get(n(c))??l.set(n(c),[]).get(n(c))).push(c);const r=new Set;for(const[c,o]of a){const u=l.get(c)??[],f=(d,p)=>s&&!s(d)?i(d,[...new Set([...p,...u])].filter(m=>m!==d)):i(d,p);if(o.length===1){r.add(o[0]);continue}const h=[];let b=[...o];for(;;){let d;for(const p of b){const m=f(p,h);if(m==="baseline-too-small"||!m.passes)continue;const S=s?.(p)??!1;(!d||S&&!d.loss||S===d.loss&&m.pValue<d.p)&&(d={t:p,p:m.pValue,loss:S})}if(!d)break;h.push(d.t),b=b.filter(p=>p!==d.t)}for(;;){let d;for(const p of h){const m=f(p,h.filter(S=>S!==p));m==="baseline-too-small"||m.passes||(!d||m.pValue>d.p)&&(d={t:p,p:m.pValue})}if(!d)break;h.splice(h.indexOf(d.t),1)}for(const d of h)r.add(d)}return r}function Ye(t){return[t.variable.kind,t.variable.bin??"",t.variable.index??"",t.comparison.family].join("\0")}function _e(t){const n=t.stats.pValue??1;return n>0?(t.stats.adjustedPValue??n)/n:1}export function isRateLoss(t){const n=t.hits/t.n-t.restHits/t.restN;return t.passRate?n<0:n>0}function Ct(t,n,i){const s=H.get(t);let{restHits:e,restN:a}=s;for(const o of n){const u=H.get(o);u&&(e-=u.hits,a-=u.n)}if(a<i.minimumSampleSize)return"baseline-too-small";const l=s.hits/s.n-e/a,r=Math.min(1,Ft(s.hits,s.n,e,a)*_e(t)),c=Math.sign(l)===Math.sign(t.effect.absoluteDelta??0)&&passesRateGate(r,l,rateRelativeEffect({...s,restHits:e,restN:a}),i);return{pValue:r,passes:c}}const Be=new WeakMap;export function welchOfSums(t,n,i,s){const e=(a,l,r)=>r>1?Math.max(0,a-l*l/r)/(r-1):0;return welchFromStats(t.n,t.sum/t.n,e(t.sq,t.sum,t.n),n,i/n,e(s,i,n))}function Vt(t,n,i){const s=Be.get(t);let{restN:e,restSum:a,restSq:l}=s;for(const h of n){const b=Be.get(h);b&&(e-=b.n,a-=b.sum,l-=b.sq)}if(e<i.minimumSampleSize)return"baseline-too-small";const{pValue:r,effectSize:c,delta:o}=welchOfSums(s,e,a,l),u=Math.min(1,r*_e(t)),f=Math.sign(o)===Math.sign(t.effect.absoluteDelta??0)&&u<=i.significanceLevel&&Math.abs(c)>=i.minimumEffectSize;return{pValue:u,passes:f}}function ne(t,n,i,s){const e=new Set(i),a=me(t,n),l=new Map,r=new Map;for(const[o,u]of a){let f=0,h=0;for(const b of u)b.hbin!==void 0&&(h++,e.has(b.hbin)&&f++);l.set(o,f),r.set(o,h)}const c=[];for(const o of n){const u=r.get(o.key)??0,f=l.get(o.key)??0;let h=0,b=0;for(const[w,M]of r)w!==o.key&&(h+=M,b+=l.get(w)??0);if(u<s.minimumSampleSize||h<s.minimumSampleSize)continue;const d=f/u,p=b/h,m=d-p,{pValue:S,method:D}=q(f,u,b,h);c.push(de(ee(o,{id:`yield:${o.key}`,level:"wafer",severity:"info",variable:{kind:"yield",label:"Yield"},comparison:{family:o.family,left:o.label,right:U(o.family)},effect:{direction:m===0?"different":m>0?"higher":"lower",absoluteDelta:m,relativeDelta:p===0?void 0:m/p,effectSize:m},stats:{method:D,pValue:S,sampleSizeLeft:u,sampleSizeRight:h},summary:$e(o.label,m,o.family),highlight:{kind:"region",regionFamily:o.family,regionKeys:[o.key],dieKeys:[...o.dieKeys]}}),{hits:f,n:u,restHits:b,restN:h,passRate:!0}))}return c}function O(t,n,i,s,e,a){const l=d=>i==="soft"?d.sbin:d.hbin,r=[...new Set(t.map(l).filter(d=>d!==void 0))].sort((d,p)=>d-p),c=me(t,n),o=new Map,u=new Map;for(const[d,p]of c){const m=new Map;for(const S of p){const D=l(S);D!==void 0&&m.set(D,(m.get(D)??0)+1)}o.set(d,m),u.set(d,p.length)}const f=[],h=e==="hardBin"?"HBin":"SBin",b=i==="hard"?new Set(a.passBins):a.softPassBins??xe(t,a.passBins).soft;for(const d of n){const p=u.get(d.key)??0,m=o.get(d.key);let S=0;const D=new Map;for(const[w,M]of o)if(w!==d.key){S+=u.get(w)??0;for(const[z,N]of M)D.set(z,(D.get(z)??0)+N)}if(!(p<a.minimumSampleSize||S<a.minimumSampleSize))for(const w of r){const M=m.get(w)??0,z=D.get(w)??0,N=M/p,y=z/S,$=N-y,{pValue:v,method:k}=q(M,p,z,S),R=Oe(w,s,h);f.push(de(ee(d,{id:`${e}:${w}:${d.key}`,level:"wafer",severity:"info",variable:{kind:e,bin:w,label:R},comparison:{family:d.family,left:d.label,right:U(d.family)},effect:{direction:$===0?"different":$>0?"higher":"lower",absoluteDelta:$,relativeDelta:y===0?void 0:$/y,effectSize:$},stats:{method:k,pValue:v,sampleSizeLeft:p,sampleSizeRight:S},summary:Re(d.label,R,$,d.family),highlight:{kind:"bin",bin:w,regionKeys:[d.key],dieKeys:[...d.dieKeys]}}),{hits:M,n:p,restHits:z,restN:S,passRate:b.has(w)}))}}return f}function ie(t,n,i,s){const e=(i??[]).filter(u=>!_(u));if(!e.length)return[];const a=e.map(u=>u.testNumber),l=me(t,n),r=new Map,c=new Map;for(const[u,f]of l){const h=new Uint32Array(e.length),b=new Uint32Array(e.length);for(const d of f)for(let p=0;p<e.length;p++){const m=re(d,a[p],e[p]);m!==void 0&&(b[p]++,m&&h[p]++)}r.set(u,h),c.set(u,b)}const o=[];for(const u of n){const f=r.get(u.key),h=c.get(u.key);for(let b=0;b<e.length;b++){let d=0,p=0;for(const[$,v]of c)$!==u.key&&(p+=v[b],d+=r.get($)[b]);const m=h[b],S=f[b];if(m<s.minimumSampleSize||p<s.minimumSampleSize)continue;const D=S/m,w=d/p,M=D-w,{pValue:z,method:N}=q(S,m,d,p),y=a[b];o.push(de(ee(u,{id:`functional:${y}:${u.key}`,level:"wafer",severity:"info",variable:{kind:"functionalTest",index:y,label:`${T(e[b],y)} pass rate`,...fe(e[b])},comparison:{family:u.family,left:u.label,right:U(u.family)},effect:{direction:M===0?"different":M>0?"higher":"lower",absoluteDelta:M,relativeDelta:w===0?void 0:M/w,effectSize:M},stats:{method:N,pValue:z,sampleSizeLeft:m,sampleSizeRight:p},summary:De(u.label,T(e[b],y),M,u.family),highlight:{kind:"region",regionFamily:u.family,regionKeys:[u.key],dieKeys:[...u.dieKeys]}}),{hits:S,n:m,restHits:d,restN:p,passRate:!0}))}}return o}export function welchFromStats(t,n,i,s,e,a){const l=Math.sqrt(i/t+a/s),r=n-e;if(!Number.isFinite(l)||l===0)return{pValue:1,effectSize:0,delta:r,z:0};const c=r/l,o=Math.sqrt(Math.max(0,(i+a)/2)),u=o===0?r:r/o;return{pValue:Ee(c),effectSize:u,delta:r,z:c}}function Et(t,n){const i=le(t),s=le(n);return welchFromStats(t.length,i,we(t,i),n.length,s,we(n,s))}const Qe=250;function Ue(t,n,i){const s=l=>l.filter(r=>_(i?.find(c=>c.testNumber===r)));if(n)return{testNumbers:s(n.slice().sort((l,r)=>l-r))};const e=Ce(t,"values");if(e.length>Qe){const l=`Test-value analysis was skipped: more than ${Qe} tests were found in the die data, so no test findings were computed. Pass testNumbers: [...] to analyse specific tests.`;return console.warn(`[wafermap] analyzeWaferMap: ${l}`),{testNumbers:[],warning:{code:"test-count-capped",message:l,severity:"warning"}}}return{testNumbers:s(e)}}function se(t,n,i,s){const e=Ue(t,s.testNumbers,i);if(e.warning)return{findings:[],warning:e.warning};const a=e.testNumbers,l=new Map;for(let m=0;m<n.length;m++)for(const S of I(n[m].dies))l.set(S,m);const r=n.length,c=[],o=[];for(const m of t){const S=l.get(ye(m));S!==void 0&&(c.push(m),o.push(S))}const u=[],f=new Float64Array(r),h=new Float64Array(r),b=new Float64Array(r);for(const m of a){f.fill(0),h.fill(0),b.fill(0);let S=0,D=0,w=0,M;for(let z=0;z<c.length;z++){const N=c[z],y=j(N,m);if(y===void 0)continue;M===void 0&&(M=y);const $=y-M,v=o[z];f[v]+=1,h[v]+=$,b[v]+=$*$,S+=1,D+=$,w+=$*$}if(M!==void 0)for(let z=0;z<r;z++){const N=f[z],y=S-N;if(N<s.minimumSampleSize||y<s.minimumSampleSize)continue;const $=h[z]/N,k=(D-h[z])/y,R=$+M,C=k+M,P=N>1?Math.max(0,b[z]-N*$*$)/(N-1):0,V=y>1?Math.max(0,w-b[z]-y*k*k)/(y-1):0,{pValue:E,effectSize:L,delta:g,z:B}=welchFromStats(N,R,P,y,C,V),x=n[z],{label:F,unit:K,...W}=Nt(m,i),ae=C!==0?g/Math.abs(C):void 0,Y=ee(x,{id:`test:${m}:${x.key}`,level:"wafer",severity:"info",variable:{kind:"test",index:m,label:F,unit:K,...W},comparison:{family:x.family,left:x.label,right:U(x.family)},effect:{direction:g===0?"different":g>0?"higher":"lower",absoluteDelta:g,relativeDelta:ae,effectSize:L},stats:{method:"welch-z-approx",pValue:E,sampleSizeLeft:N,sampleSizeRight:y},summary:Me(x.label,F,g,ae,x.family,K),highlight:{kind:"region",regionFamily:x.family,regionKeys:[x.key],dieKeys:[...x.dieKeys]}}),Z={n:N,sum:h[z],sq:b[z],restN:y,restSum:D-h[z],restSq:w-b[z],shift:M};Be.set(Y,Z),He(Y,B,void 0,Z),u.push(Y)}}adjustPValues(u);const d=u.filter(m=>{const S=m.stats.adjustedPValue??m.stats.pValue??1,D=Math.abs(m.effect.effectSize??0);return S<=s.significanceLevel&&D>=s.minimumEffectSize}),p=confirmRegionalFindings(d,Ye,(m,S)=>Vt(m,S,s));return{activeTestNumbers:a,findings:d.filter(m=>p.has(m)).map(m=>({...m,severity:severityForScore(m.stats.adjustedPValue??m.stats.pValue??1,m.effect.effectSize??0)}))}}function Lt(t,n,i,s){if(!i?.length)return[];const e=i.filter(l=>_(l)&&(l.limitLow!==void 0||l.limitHigh!==void 0));if(!e.length)return[];const a=[];for(const l of e){const r=l.testNumber;for(const c of n){const o=me(t,c),u=[],f=new Map;let h=0,b=0;for(const[d,p]of o){let m=0,S=0;for(const D of p){const w=j(D,r);w!==void 0&&(m++,ve(ce(w,l))&&S++)}f.set(d,{valid:m,fail:S}),h+=m,b+=S}for(const d of c){const p=f.get(d.key),m=p.valid,S=h-p.valid;if(m<s.minimumSampleSize||S<s.minimumSampleSize)continue;const D=p.fail,w=b-p.fail,M=D/m,z=w/S,N=M-z,{pValue:y,method:$}=q(D,m,w,S);u.push(de(ee(d,{id:`specLimit:${r}:${d.key}`,level:"wafer",severity:"info",variable:{kind:"test",index:r,label:T(l,r),unit:l.unit,...fe(l)},comparison:{family:d.family,left:d.label,right:U(d.family)},effect:{direction:N===0?"different":N>0?"higher":"lower",absoluteDelta:N,relativeDelta:z===0?void 0:N/z,effectSize:N},stats:{method:$,pValue:y,sampleSizeLeft:m,sampleSizeRight:S},summary:ze(d.label,T(l,r),N),highlight:{kind:"region",regionFamily:d.family,regionKeys:[d.key],dieKeys:[...d.dieKeys]}}),{hits:D,n:m,restHits:w,restN:S,passRate:!1}))}a.push(...u)}}return a}function Fe(t,n){return t==="softBin"?n.softEligibleDies:t==="test"?n.testDies:n.eligibleDies}function Kt(t){return t.id.startsWith("specLimit:")}function oe(t){return t.highlight.regionKeys??[]}function Ot(t){const n=t.variable.bin??t.variable.index??"";return`${t.comparison.family}\0${Ge(t)}\0${t.variable.kind}\0${n}\0${t.effect.direction}`}function qt(t,n){const i=Q(t);return i.family==="ring"?i.ring??0:i.family==="sector"?Ve(n).indexOf(i.sector??""):0}export function inQuadrantOrder(t){const n=new Set(t),i=Se.findIndex((e,a)=>n.has(e)&&!n.has(Se[(a+3)%4])),s=i<0?0:i;return Array.from({length:4},(e,a)=>Se[(s+a)%4]).filter(e=>n.has(e))}export function findContiguousRuns(t,n,i,s){if(n==="quadrant"){const c=new Map;for(const h of t){const b=Q(s(h)).quadrant;b&&c.set(b,h)}const o=[...c.keys()],u=new Set,f=[];for(const h of o){if(u.has(h))continue;const b=[],d=[h];for(u.add(h);d.length;){const p=d.pop();b.push(p);for(const m of o)!u.has(m)&&ft(p,m)&&(u.add(m),d.push(m))}f.push(inQuadrantOrder(b).map(p=>c.get(p)))}return f}const e=c=>qt(s(c),i),a=[...t].sort((c,o)=>e(c)-e(o)),l=[];let r=[];for(const c of a){if(r.length===0){r.push(c);continue}const o=e(r[r.length-1]);e(c)-o===1?r.push(c):(l.push(r),r=[c])}if(r.length&&l.push(r),n==="sector"&&l.length>1){const o=Ve(i).length,u=e(l[0][0]),f=e(l[l.length-1][l[l.length-1].length-1]);if(u===0&&f===o-1){const h=l.pop();l[0]=[...h,...l[0]]}}return l}export function mergedRegionLabel(t,n,i){if(t==="ring"){const e=n.map(c=>Q(c).ring).filter(c=>c!==void 0).sort((c,o)=>c-o),a=e[0],l=e[e.length-1];let r="";return a===l&&a===1&&i>1?r=" (core)":a===l&&a===i&&i>1&&(r=" (edge)"),a===l?`Ring ${a}${r}`:`Rings ${a}\u2013${l}`}if(t==="sector"){const e=n.map(a=>Q(a).sector??"");return e.length===1?`Sector ${e[0]}`:`Sectors ${e[0]}\u2013${e[e.length-1]}`}const s=n.map(e=>Q(e).quadrant??"");return s.length===1?s[0]:s.length===2?`Quadrants ${s[0]} & ${s[1]}`:`Quadrants ${s.slice(0,-1).join(", ")} & ${s[s.length-1]}`}function Ne(t){return[...new Set(t)]}export function weakestMultiplier(t){return wt(t.map(n=>{const i=n.stats.pValue??1;return i>0?(n.stats.adjustedPValue??i)/i:1}))}function X(t,n){return Math.min(1,t*n)}function Tt(t,n){const i=t[0],s=i.comparison.family,e=i.variable.kind,a=Ne(t.flatMap(oe));let l,r;const c=t.map(Ie);if(c.every(y=>y!==void 0)){const y=new Set;l=[];for(const v of c){const k=I(v.dies);for(let R=0;R<k.length;R++)y.has(k[R])||(y.add(k[R]),l.push(v.dieKeys[R]))}const $=I(Fe(i.variable.kind,n));r=v=>y.has($[v])}else{l=Ne(t.flatMap(v=>v.highlight.dieKeys??[]));const y=new Set(l),$=xt(Fe(i.variable.kind,n));r=v=>y.has($[v])}const o=mergedRegionLabel(s,t.map(y=>oe(y)[0]??""),n.ringCount),u=Fe(e,n),f=n.regionDies[s],h=I(u),b=[],d=[];for(let y=0;y<u.length;y++)f.has(h[y])&&(r(y)?b:d).push(u[y]);const p=weakestMultiplier(t);let m,S,D,w,M;if(Kt(i)){const y=i.variable.index,$=n.testDefs?.find(B=>B.testNumber===y),v=B=>{let x=0,F=0;for(const K of B){const W=j(K,y);W!==void 0&&(x++,$&&ve(ce(W,$))&&F++)}return{valid:x,fail:F}},k=v(b),R=v(d),C=k.valid>0?k.fail/k.valid:0,P=R.valid>0?R.fail/R.valid:0,V=C-P,{pValue:E,method:L}=q(k.fail,k.valid,R.fail,R.valid);m={direction:V===0?"different":V>0?"higher":"lower",absoluteDelta:V,relativeDelta:P===0?void 0:V/P,effectSize:V},S={method:L,pValue:E,sampleSizeLeft:k.valid,sampleSizeRight:R.valid};const g=X(E,p);D=severityForFinding(g,V,rateRelativeEffect({hits:k.fail,n:k.valid,restHits:R.fail,restN:R.valid,passRate:!1})),w=ze(o,T($,y),V),M=`specLimit:${y}`}else if(e==="test"){const y=i.variable.index,$=g=>j(g,y),v=b.map($).filter(g=>g!==void 0),k=d.map($).filter(g=>g!==void 0),{pValue:R,effectSize:C,delta:P}=Et(v,k),V=le(k),E=V!==0?P/Math.abs(V):void 0;m={direction:P===0?"different":P>0?"higher":"lower",absoluteDelta:P,relativeDelta:E,effectSize:C},S={method:"welch-z-approx",pValue:R,sampleSizeLeft:v.length,sampleSizeRight:k.length};const L=X(R,p);D=severityForScore(L,C),w=Me(o,i.variable.label,P,E,s,i.variable.unit),M=`test:${y}`}else if(e==="yield"){const y=new Set(n.passBins),$=b.filter(F=>F.hbin!==void 0),v=d.filter(F=>F.hbin!==void 0),k=$.length,R=v.length,C=$.filter(F=>y.has(F.hbin)).length,P=v.filter(F=>y.has(F.hbin)).length,V=k>0?C/k:0,E=R>0?P/R:0,L=V-E,{pValue:g,method:B}=q(C,k,P,R);m={direction:L===0?"different":L>0?"higher":"lower",absoluteDelta:L,relativeDelta:E===0?void 0:L/E,effectSize:L},S={method:B,pValue:g,sampleSizeLeft:k,sampleSizeRight:R};const x=X(g,p);D=severityForFinding(x,L,rateRelativeEffect({hits:C,n:k,restHits:P,restN:R,passRate:!0})),w=$e(o,L,s),M="yield"}else if(e==="functionalTest"){const y=i.variable.index,$=n.testDefs?.find(x=>x.testNumber===y);let v=0,k=0,R=0,C=0;for(const x of b){const F=re(x,y,$);F!==void 0&&(k++,F&&v++)}for(const x of d){const F=re(x,y,$);F!==void 0&&(C++,F&&R++)}const P=k>0?v/k:0,V=C>0?R/C:0,E=P-V,{pValue:L,method:g}=q(v,k,R,C);m={direction:E===0?"different":E>0?"higher":"lower",absoluteDelta:E,relativeDelta:V===0?void 0:E/V,effectSize:E},S={method:g,pValue:L,sampleSizeLeft:k,sampleSizeRight:C};const B=X(L,p);D=severityForFinding(B,E,rateRelativeEffect({hits:v,n:k,restHits:R,restN:C,passRate:!0})),w=De(o,T($,y),E,s),M=`functional:${y}`}else{const y=i.variable.bin,$=B=>e==="softBin"?B.sbin:B.hbin,v=b.filter(B=>$(B)===y).length,k=d.filter(B=>$(B)===y).length,R=v/b.length,C=k/d.length,P=R-C,{pValue:V,method:E}=q(v,b.length,k,d.length);m={direction:P===0?"different":P>0?"higher":"lower",absoluteDelta:P,relativeDelta:C===0?void 0:P/C,effectSize:P},S={method:E,pValue:V,sampleSizeLeft:b.length,sampleSizeRight:d.length};const L=X(V,p);D=severityForFinding(L,P,rateRelativeEffect({hits:v,n:b.length,restHits:k,restN:d.length,passRate:!1}));const g=e==="softBin"?n.sbinDefs:n.hbinDefs;w=Re(o,Oe(y,g,e==="softBin"?"SBin":"HBin"),P,s),M=`${e}:${y}`}S={...S,adjustedPValue:X(S.pValue??1,p)};const z=Ne(a.map(y=>y.replace(`${s}:`,""))).join("-"),N=e==="hardBin"||e==="softBin"?{kind:"bin",bin:i.variable.bin,regionKeys:a,dieKeys:l}:{kind:"region",regionFamily:s,regionKeys:a,dieKeys:l};return{...i,id:`${M}:${s}:${z}`,severity:D,comparison:{family:s,left:o,right:U(s)},effect:m,stats:S,summary:w,highlight:N,relatedIds:t.map(y=>y.id)}}function At(t,n){const i=new Set(["ring","quadrant","sector"]),s=[],e=new Map;for(const l of t){if(!i.has(l.comparison.family)){s.push(l);continue}const r=Ot(l),c=e.get(r)??[];c.push(l),e.set(r,c)}const a=[];for(const l of e.values()){if(l.length===1){a.push(l[0]);continue}const r=l[0].comparison.family;for(const c of findContiguousRuns(l,r,n.sectorCount,o=>oe(o)[0]??""))a.push(c.length===1?c[0]:Tt(c,n))}return[...s,...a]}function jt(t){const n=new Map,i=new Map;for(const e of t){const a=ye(e);e.hbin!==void 0&&e.hbin!==null&&(n.get(e.hbin)??n.set(e.hbin,new Set).get(e.hbin)).add(a),e.sbin!==void 0&&e.sbin!==null&&(i.get(e.sbin)??i.set(e.sbin,new Set).get(e.sbin)).add(a)}const s=new Set;for(const[e,a]of n)for(const[l,r]of i){if(a.size!==r.size)continue;let c=!0;for(const o of a)if(!r.has(o)){c=!1;break}c&&s.add(`${e}:${l}`)}return s}function Ht(t,n){const i=new Set(n);let s;for(const e of t){const a=pe(e,i);if(a!==void 0&&a){if(e.sbin==null||s!==void 0&&e.sbin!==s)return;s=e.sbin}}if(s!==void 0){for(const e of t)if(e.sbin===s&&pe(e,i)!==!0)return;return s}}function It(t){return`${t.comparison.family}\0${t.comparison.left}`}export function redundancyFacts(t,n,i){return{coincident:jt(t),yieldSoftBin:Ht(t,n),passBins:n,sectorCount:i}}const Wt=3/5;function Ge(t){return/^(?:lot-region:)?([^:|]+)/.exec(t.id)?.[1]??t.id}function Yt(t){const n=oe(t);if(n.length)return n;const i=/(ring|sector|quadrant):([^:|]+)$/.exec(t.id);return i?i[2].split("-").map(s=>`${i[1]}:${s}`):[]}function Xe(t,n){const i=new Set;for(const s of Yt(t)){const e=lt(s,n);if(!e)return;for(const a of e)i.add(a)}return i.size?i:void 0}export function collapseRedundantFindings(t,n){const{coincident:i,yieldSoftBin:s,passBins:e}=n,a=(o,u)=>{o.absorbedIds=[...o.absorbedIds??[],u.id]},l=new Map;for(const o of t){const u=It(o);(l.get(u)??l.set(u,[]).get(u)).push(o)}const r=new Set;for(const o of l.values()){for(const f of o)if(!(f.variable.kind!=="hardBin"||f.variable.bin===void 0))for(const h of o){if(h.variable.kind!=="softBin"||h.variable.bin===void 0||r.has(h.id)||!i.has(`${f.variable.bin}:${h.variable.bin}`)||h.effect.direction!==f.effect.direction)continue;a(f,h),r.add(h.id);const b=f.variable.label.replace(/^HBin\s+/,""),d=h.variable.label.replace(/^SBin\s+/,""),p=b===d?`HBin and SBin ${b} (same dies)`:`${f.variable.label} and ${h.variable.label} (same dies)`;f.summary=f.summary.replace(f.variable.label,p),f.variable.label=p;break}const u=o.find(f=>f.variable.kind==="yield");if(u){for(const f of o)if(!(f===u||r.has(f.id)||!(f.variable.kind==="hardBin"&&e.length===1&&f.variable.bin===e[0]||f.variable.kind==="softBin"&&f.variable.bin===s))){a(u,f),r.add(f.id);for(const b of f.absorbedIds??[])u.absorbedIds=[...u.absorbedIds??[],b]}}}const c=new Map;for(const o of t){if(r.has(o.id)||o.comparison.family!=="sector"&&o.comparison.family!=="quadrant")continue;const u=[Ge(o),o.variable.kind,o.variable.bin??"",o.variable.index??"",o.effect.direction].join("\0");(c.get(u)??c.set(u,[]).get(u)).push(o)}for(const o of c.values()){const u=[];for(const f of o.filter(h=>h.comparison.family==="sector")){const h=Xe(f,n.sectorCount);if(h)for(const b of o.filter(d=>d.comparison.family==="quadrant")){const d=Xe(b,n.sectorCount);if(!d)continue;let p=0;for(const S of h)d.has(S)&&p++;const m=h.size+d.size-p;p/m>=Wt-1e-9&&u.push({sector:f,quadrant:b,overlap:p/m})}}u.sort((f,h)=>h.overlap-f.overlap);for(const{sector:f,quadrant:h}of u){if(r.has(f.id)||r.has(h.id))continue;const b=(h.stats.pValue??1)<(f.stats.pValue??1),[d,p]=b?[h,f]:[f,h];a(d,p),r.add(p.id),d.absorbedIds=[...d.absorbedIds??[],...p.absorbedIds??[]]}}}export function analyzeWaferMap(t,n={}){const i=G,s=te,e=[];G=e,te=void 0;try{const a=_t(t,n);return je.set(a,{candidates:e,facts:te}),a}finally{G=i,te=s}}function _t(t,n){const{resolved:i,warnings:s}=resolveOptions(n),e=Ze(t),a={...i,passBins:[...pt(e,"analyzeWaferMap")],ringCount:gt(e,"analyzeWaferMap")},l=e.isLotStack,r=e.aggrMethod,c=!l||r==="mode"||r==="countBin"||r==="percent",o=e.dies.filter(g=>kt(g)),u=o.filter(Pe),f=$t(a,o.length);f.softPassBins=xe(o,f.passBins).soft;const h=e.dies.filter(g=>ge(g)),b=h.filter(Pe),d=ot(b,e.wafer,f.ringCount),p=it(b,e.wafer,f.ringCount),m=st(b,e.reticleConfig),S=rt(h,!1),D=at(b,e.wafer,f.sectorCount),w=[],M=[];c&&M.push(...ne(o,d,f.passBins,f),...ne(o,p,f.passBins,f),...ne(o,m,f.passBins,f),...ne(o,S,f.passBins,f),...ne(o,D,f.passBins,f)),c&&M.push(...O(o,d,"hard",e.hbinDefs,"hardBin",f),...O(o,p,"hard",e.hbinDefs,"hardBin",f),...O(o,m,"hard",e.hbinDefs,"hardBin",f),...O(o,S,"hard",e.hbinDefs,"hardBin",f),...O(o,D,"hard",e.hbinDefs,"hardBin",f));{const g=o.filter(B=>B.sbin!==void 0);M.push(...O(g,d,"soft",e.sbinDefs,"softBin",f),...O(g,p,"soft",e.sbinDefs,"softBin",f),...O(g,m,"soft",e.sbinDefs,"softBin",f),...O(g,S,"soft",e.sbinDefs,"softBin",f),...O(g,D,"soft",e.sbinDefs,"softBin",f))}const z=[...s];let N;if(f.enableTestValueAnalysis){const g=se(o,d,e.testDefs,f),B=se(o,p,e.testDefs,f),x=se(o,m,e.testDefs,f),F=se(o,S,e.testDefs,f),K=se(o,D,e.testDefs,f);w.push(...g.findings,...B.findings,...x.findings,...F.findings,...K.findings),g.warning&&z.push(g.warning),N=g.activeTestNumbers,M.push(...Lt(o,[d,p,m,S,D],e.testDefs,f)),M.push(...ie(o,d,e.testDefs,f),...ie(o,p,e.testDefs,f),...ie(o,m,e.testDefs,f),...ie(o,S,e.testDefs,f),...ie(o,D,e.testDefs,f))}w.push(...Pt(M,f));{const g=Rt(l,c,e.testDefs);(!l||c||g!==void 0)&&w.push(...ct(u,e.wafer,{...f,isFailingDie:g}))}const y=At(w,{eligibleDies:o,softEligibleDies:o.filter(g=>g.sbin!==void 0),testDies:o,passBins:f.passBins,ringCount:f.ringCount,sectorCount:f.sectorCount,regionDies:{ring:new Set(d.flatMap(g=>I(g.dies))),quadrant:new Set(p.flatMap(g=>I(g.dies))),sector:new Set(D.flatMap(g=>I(g.dies)))},hbinDefs:e.hbinDefs,sbinDefs:e.sbinDefs,testDefs:e.testDefs});w.length=0,w.push(...y);let $;if(c){const g=ut(u,e.wafer,{passBins:f.passBins,ringCount:f.ringCount});if($=g??void 0,g!==null&&g.pattern!=="random"&&g.pattern!=="none"){const B=ht[g.pattern],x=g.confidence==="high"?"unusual":g.confidence==="medium"?"notable":"info",F=g.features,K=A=>`${(A*100).toFixed(0)}%`,W=g.pattern==="edge-ring"||g.pattern==="edge-local"?`${K(F.edgeRdd)} of edge dies failing`:g.pattern==="center"?`centroid at ${K(F.centroidDistNorm)} of wafer radius from centre`:g.pattern==="donut"?`${K(Math.max(F.radialFailRates[1],F.radialFailRates[2]))} of dies failing at mid-radius, ${K(F.radialFailRates[0])} at the centre`:g.pattern==="scratch"?`a line ${Math.round(F.lineLength)} dies long and about ${Math.max(1,Math.round(F.lineWidth*2))} wide`:`${K(F.globalRdd)} of dies failing`,ae=new Set(f.passBins),Y=o.filter(A=>mt(A,ae)===!0),Z=claimForPattern([g.pattern],x,w,A=>oe(A).map(he=>Q(he).ring).filter(he=>he!==void 0),f.ringCount);w.push({id:`spatial-pattern:${g.pattern}`,level:"wafer",severity:x,variable:{kind:"spatialPattern",label:B},comparison:{family:"spatial-pattern",left:B,right:"Wafer"},effect:{direction:"different",effectSize:F.globalRdd},stats:{method:"geometry",sampleSizeLeft:Y.length,sampleSizeRight:o.length},summary:`Spatial pattern: ${B.toLowerCase()} (${g.confidence} confidence) \u2014 ${W}${g.note?` [${g.note}]`:""}`,highlight:{kind:"dies",dieKeys:Y.map(A=>be(A))},relatedIds:Z.length>0?Z:void 0})}}w.sort((g,B)=>{const x=g.stats.adjustedPValue??g.stats.pValue??1,F=B.stats.adjustedPValue??B.stats.pValue??1;return x!==F?x-F:Math.abs(B.effect.absoluteDelta??0)-Math.abs(g.effect.absoluteDelta??0)});const v=Dt(e.dies,o.length,e.yield.yieldPercent);l&&(v.isLotStack=!0,r&&(v.aggregationMethod=r));const k=new Set(a.passBins),R={},C=(g,B)=>{const x=R[g]??={dieKeys:[],lostDies:0};x.dieKeys.push(be(B)),pe(B,k)!==!0&&x.lostDies++},P=Mt(e.dies,e.testDefs,C);P&&(v.testSpecYield=P);const V=computeFunctionalYield(e.dies,e.testDefs,C);if(V&&(v.functionalYield=V),Object.keys(R).length&&(v.testFailures=R),$&&(v.spatialPattern=$),N===void 0&&f.computePerTestStats){const g=Ue(o,f.testNumbers,e.testDefs);g.warning&&z.push(g.warning),N=g.testNumbers}if(N?.length){const g=zt(e.dies,N,e.testDefs,f.minimumSampleSize);g&&(v.perTestStats=g);const B=Je([{dies:e.dies}],e.testDefs,N);B&&(v.capability=B)}Object.assign(v,et(e.dies,e.testDefs));const E=tt([{dies:e.dies,wafer:e.wafer,passBins:f.passBins,ringCount:f.ringCount}]);E&&(v.regionYield=E),z.length>0&&(v.warnings=z);const L=redundancyFacts(o,f.passBins,f.sectorCount);return collapseRedundantFindings(w,L),G&&(te=L),{level:"wafer",hasNotableFindings:w.some(g=>g.severity==="notable"||g.severity==="unusual"),findings:w,wafer:e.wafer.metadata??void 0,stats:v}}
@@ -29,6 +29,11 @@ export interface CapabilityDatum {
29
29
  /** Pooled within-wafer sample stddev. NaN if no item contributed ≥2 values. */
30
30
  stdWithin: number;
31
31
  n: number;
32
+ /** Dies whose value for this test the value filter excluded (not in `n`), and the limit set they were outside of. */
33
+ excluded?: {
34
+ count: number;
35
+ limitSet: 'validity' | 'spec' | 'test';
36
+ };
32
37
  /** Cp/Cpk use `stdWithin`; null when stdWithin is NaN or 0, or when `hasSpec` is false. */
33
38
  cp: number | null;
34
39
  cpk: number | null;
@@ -1 +1 @@
1
- import{isYieldEligibleDie as B}from"../core/dies.js";import{testValuesReader as D}from"../core/dieTable.js";import{drain as q}from"../core/utils.js";import{isParametricTest as v}from"../renderer/buildWaferMap.js";import{countOutOfSpec as H,hasSpecLimits as E}from"../renderer/spec.js";import{testLabel as P,derivedFields as V}from"../renderer/testLabel.js";import{describeValues as _}from"./math.js";const I=25e4;function z(n){if(n.specLow!==void 0&&n.specHigh!==void 0&&n.specHigh>n.specLow)return{lsl:n.specLow,usl:n.specHigh,basis:"spec"};if(n.limitLow!==void 0&&n.limitHigh!==void 0&&n.limitHigh>n.limitLow)return{lsl:n.limitLow,usl:n.limitHigh,basis:"test"}}function x(n){const s=new Map,e=new Map;for(const l of n){const t=l.testNumber;if(t===void 0||!v(l))continue;e.set(t,l);const i=z(l);i&&s.set(t,i)}return{defByTestNumber:e,specByTest:s}}function*C(n,s,e){const l=[...s.keys()],t=l.length,i=new Float64Array(t),r=new Float64Array(t),o=new Float64Array(t),f=new Float64Array(t),p=new Float64Array(t),N=new Float64Array(t),w=new Float64Array(t),m=new Float64Array(t);let d=0;if(e)for(const a of n)d+=a.dies?.length??0;const M=e?Array.from({length:t},()=>new Float64Array(d)):[],S=D(l),h=new Float64Array(t),b=Math.max(500,Math.floor(I/Math.max(1,t)));let F=0;for(const a of n){N.fill(0),w.fill(0),m.fill(0);for(const u of a.dies??[])if(++F>=b&&(F=0,yield),!!B(u)){S(u,h);for(let c=0;c<t;c++){const g=h[c];Number.isFinite(g)&&(i[c]++,r[c]+=g,o[c]+=g*g,N[c]++,w[c]+=g,m[c]+=g*g,e&&(M[c][i[c]-1]=g))}}for(let u=0;u<t;u++){const c=N[u];if(c<2)continue;const g=w[u]/c,$=(m[u]-c*g*g)/(c-1);f[u]+=(c-1)*Math.max(0,$),p[u]+=c-1}}const y=new Map;for(let a=0;a<t;a++){if(i[a]===0)continue;const u=l[a];y.set(u,{n:i[a],sum:r[a],sumSq:o[a],withinNumerator:f[a],withinDenominator:p[a]}),e&&e.set(u,M[a].subarray(0,i[a]))}return y}function R(n,s,e){return q(C(n,s,e))}function A(n,s,e,l){const{n:t,sum:i,sumSq:r,withinNumerator:o,withinDenominator:f}=l,p=i/t,N=t>=2?Math.max(0,(r-t*p*p)/(t-1)):0,w=Math.sqrt(N),m=f>0?Math.sqrt(o/f):NaN;let d=null,M=null,S=null,h=null;if(e){const{lsl:b,usl:F}=e,y=F-b;S=w>0?y/(6*w):null,h=w>0?Math.min((F-p)/(3*w),(p-b)/(3*w)):null,d=Number.isFinite(m)&&m>0?y/(6*m):null,M=Number.isFinite(m)&&m>0?Math.min((F-p)/(3*m),(p-b)/(3*m)):null}return{testNumber:n,label:P(s,n),unit:s.unit,...V(s),hasSpec:e!==void 0,lsl:e?.lsl,usl:e?.usl,...e?{limitBasis:e.basis}:{},mean:p,stdOverall:w,stdWithin:m,n:t,cp:d,cpk:M,pp:S,ppk:h}}function L(n){return n.sort((s,e)=>s.hasSpec!==e.hasSpec?s.hasSpec?-1:1:s.hasSpec?s.ppk===null&&e.ppk===null?0:s.ppk===null?1:e.ppk===null?-1:s.ppk-e.ppk:e.stdOverall-s.stdOverall)}export function buildCapabilityData(n,s){return q(buildCapabilityDataSteps(n,s))}export function*buildCapabilityDataSteps(n,s){return(yield*pooledTestStatsSteps(n,s)).capability.slice()}const T=new Map,j=4,O=new WeakMap;let W=1;function Y(n,s){const e=[];for(const t of n){const i=t.dies;if(!i){e.push(0);continue}let r=O.get(i);r===void 0&&(r=W++,O.set(i,r)),e.push(r)}const l=s.filter(t=>t.testNumber!==void 0&&v(t)).map(t=>`${t.testNumber}${t.testType??"P"}${t.limitLow??""}${t.limitHigh??""}${t.specLow??""}${t.specHigh??""}${t.name??""}${t.unit??""}`);return`${e.join(",")}${l.join("")}`}export function clearPooledTestStatsCache(){T.clear();for(const n of k.values())n.work.return(void 0);k.clear()}export function*pooledTestStatsSteps(n,s){const e=Y(n,s),l=T.get(e);if(l)return T.delete(e),T.set(e,l),l;let t=k.get(e);t||(t={work:K(n,s,e),callers:0},k.set(e,t));const i=t;i.callers++;try{for(;;){if(i.result)return i.result;const r=i.work.next();if(r.done)return i.result=r.value,k.delete(e),r.value;yield}}finally{i.callers--,!i.result&&i.callers===0&&(i.work.return(void 0),k.get(e)===i&&k.delete(e))}}const k=new Map;function*K(n,s,e){const l={stats:new Map,specTally:new Map,capability:[]},{defByTestNumber:t,specByTest:i}=x(s);if(t.size===0)return l;const r=new Map,o=yield*C(n,t,r),f=new Map,p=new Map,N=[];for(const m of s){yield;const d=m.testNumber;if(d===void 0)continue;const M=o.get(d);if(!M||M.n===0||!t.has(d))continue;const S=r.get(d);r.delete(d),E(m)&&p.set(d,{n:S.length,fail:H(S,m)});const h=_(S);f.set(d,h);const b=i.get(d),F=A(d,m,b,M);let y;if(b){const a=b.usl-b.lsl;y=u=>(u-b.lsl)/a}else{const a=h.min,u=h.max-a;y=u>0?c=>(c-a)/u:()=>.5}N.push({...F,min:y(h.min),q1:y(h.q1),median:y(h.median),q3:y(h.q3),max:y(h.max)})}const w={stats:f,specTally:p,capability:L(N)};return T.set(e,w),T.size>j&&T.delete(T.keys().next().value),w}export function buildCapabilityFigures(n,s){const{defByTestNumber:e,specByTest:l}=x(s);if(e.size===0)return[];const t=R(n,e,null),i=[];for(const[r,o]of t)o.n!==0&&i.push(A(r,e.get(r),l.get(r),o));return L(i)}export function poolCapabilityFigures(n,s){const{defByTestNumber:e,specByTest:l}=x(s),t=new Map;for(const r of n)for(const o of r){if(!e.has(o.testNumber)||o.n===0)continue;let f=t.get(o.testNumber);f||(f={n:0,sum:0,sumSq:0,withinNumerator:0,withinDenominator:0},t.set(o.testNumber,f));const p=o.stdOverall*o.stdOverall;f.n+=o.n,f.sum+=o.n*o.mean,f.sumSq+=(o.n-1)*p+o.n*o.mean*o.mean,o.n>=2&&(f.withinNumerator+=(o.n-1)*p,f.withinDenominator+=o.n-1)}const i=[];for(const[r,o]of t)i.push(A(r,e.get(r),l.get(r),o));return L(i)}
1
+ import{isYieldEligibleDie as v}from"../core/dies.js";import{excludedCounts as H,testValuesReader as E}from"../core/dieTable.js";import{drain as C}from"../core/utils.js";import{isParametricTest as O}from"../renderer/buildWaferMap.js";import{countOutOfSpec as P,hasSpecLimits as V}from"../renderer/spec.js";import{testLabel as _,derivedFields as I}from"../renderer/testLabel.js";import{describeValues as z}from"./math.js";const R=25e4;function j(n){if(n.specLow!==void 0&&n.specHigh!==void 0&&n.specHigh>n.specLow)return{lsl:n.specLow,usl:n.specHigh,basis:"spec"};if(n.limitLow!==void 0&&n.limitHigh!==void 0&&n.limitHigh>n.limitLow)return{lsl:n.limitLow,usl:n.limitHigh,basis:"test"}}function A(n){const s=new Map,e=new Map;for(const l of n){const t=l.testNumber;if(t===void 0||!O(l))continue;e.set(t,l);const i=j(l);i&&s.set(t,i)}return{defByTestNumber:e,specByTest:s}}function*$(n,s,e){const l=[...s.keys()],t=l.length,i=new Float64Array(t),r=new Float64Array(t),o=new Float64Array(t),f=new Float64Array(t),p=new Float64Array(t),S=new Float64Array(t),y=new Float64Array(t),d=new Float64Array(t);let x=0;if(e)for(const m of n)x+=m.dies?.length??0;const g=e?Array.from({length:t},()=>new Float64Array(x)):[],u=E(l),b=new Float64Array(t),M=Math.max(500,Math.floor(R/Math.max(1,t)));let h=0;for(const m of n){S.fill(0),y.fill(0),d.fill(0);for(const c of m.dies??[])if(++h>=M&&(h=0,yield),!!v(c)){u(c,b);for(let a=0;a<t;a++){const w=b[a];Number.isFinite(w)&&(i[a]++,r[a]+=w,o[a]+=w*w,S[a]++,y[a]+=w,d[a]+=w*w,e&&(g[a][i[a]-1]=w))}}for(let c=0;c<t;c++){const a=S[c];if(a<2)continue;const w=y[c]/a,k=(d[c]-a*w*w)/(a-1);f[c]+=(a-1)*Math.max(0,k),p[c]+=a-1}}const N=new Map;for(let m=0;m<t;m++){if(i[m]===0)continue;const c=l[m];N.set(c,{n:i[m],sum:r[m],sumSq:o[m],withinNumerator:f[m],withinDenominator:p[m]}),e&&e.set(c,g[m].subarray(0,i[m]))}return N}function W(n,s,e){return C($(n,s,e))}function L(n,s,e,l){const{n:t,sum:i,sumSq:r,withinNumerator:o,withinDenominator:f}=l,p=i/t,S=t>=2?Math.max(0,(r-t*p*p)/(t-1)):0,y=Math.sqrt(S),d=f>0?Math.sqrt(o/f):NaN;let x=null,g=null,u=null,b=null;if(e){const{lsl:M,usl:h}=e,N=h-M;u=y>0?N/(6*y):null,b=y>0?Math.min((h-p)/(3*y),(p-M)/(3*y)):null,x=Number.isFinite(d)&&d>0?N/(6*d):null,g=Number.isFinite(d)&&d>0?Math.min((h-p)/(3*d),(p-M)/(3*d)):null}return{testNumber:n,label:_(s,n),unit:s.unit,...I(s),hasSpec:e!==void 0,lsl:e?.lsl,usl:e?.usl,...e?{limitBasis:e.basis}:{},mean:p,stdOverall:y,stdWithin:d,n:t,cp:x,cpk:g,pp:u,ppk:b}}function q(n){return n.sort((s,e)=>s.hasSpec!==e.hasSpec?s.hasSpec?-1:1:s.hasSpec?s.ppk===null&&e.ppk===null?0:s.ppk===null?1:e.ppk===null?-1:s.ppk-e.ppk:e.stdOverall-s.stdOverall)}export function buildCapabilityData(n,s){return C(buildCapabilityDataSteps(n,s))}export function*buildCapabilityDataSteps(n,s){return(yield*pooledTestStatsSteps(n,s)).capability.slice()}const F=new Map,Y=4,B=new WeakMap;let K=1;function U(n,s){const e=[];for(const t of n){const i=t.dies;if(!i){e.push(0);continue}let r=B.get(i);r===void 0&&(r=K++,B.set(i,r)),e.push(r)}const l=s.filter(t=>t.testNumber!==void 0&&O(t)).map(t=>`${t.testNumber}${t.testType??"P"}${t.limitLow??""}${t.limitHigh??""}${t.specLow??""}${t.specHigh??""}${t.name??""}${t.unit??""}`);return`${e.join(",")}${l.join("")}`}export function clearPooledTestStatsCache(){F.clear();for(const n of T.values())n.work.return(void 0);T.clear()}export function*pooledTestStatsSteps(n,s){const e=U(n,s),l=F.get(e);if(l)return F.delete(e),F.set(e,l),l;let t=T.get(e);t||(t={work:G(n,s,e),callers:0},T.set(e,t));const i=t;i.callers++;try{for(;;){if(i.result)return i.result;const r=i.work.next();if(r.done)return i.result=r.value,T.delete(e),r.value;yield}}finally{i.callers--,!i.result&&i.callers===0&&(i.work.return(void 0),T.get(e)===i&&T.delete(e))}}const T=new Map;function*G(n,s,e){const l={stats:new Map,specTally:new Map,capability:[]},{defByTestNumber:t,specByTest:i}=A(s);if(t.size===0)return l;const r=new Map,o=yield*$(n,t,r),f=new Map,p=new Map,S=[],y=new Map;let d;for(const g of n){const u=H((g.dies??[]).filter(b=>v(b)));if(u){d??=u.by;for(const[b,M]of u.counts)y.set(b,(y.get(b)??0)+M)}}for(const g of s){yield;const u=g.testNumber;if(u===void 0)continue;const b=o.get(u);if(!b||b.n===0||!t.has(u))continue;const M=r.get(u);r.delete(u),V(g)&&p.set(u,{n:M.length,fail:P(M,g)});const h=z(M);f.set(u,h);const N=i.get(u),m=L(u,g,N,b);let c;if(N){const w=N.usl-N.lsl;c=k=>(k-N.lsl)/w}else{const w=h.min,k=h.max-w;c=k>0?D=>(D-w)/k:()=>.5}const a=y.get(u);S.push({...m,...a&&d?{excluded:{count:a,limitSet:d}}:{},min:c(h.min),q1:c(h.q1),median:c(h.median),q3:c(h.q3),max:c(h.max)})}const x={stats:f,specTally:p,capability:q(S)};return F.set(e,x),F.size>Y&&F.delete(F.keys().next().value),x}export function buildCapabilityFigures(n,s){const{defByTestNumber:e,specByTest:l}=A(s);if(e.size===0)return[];const t=W(n,e,null),i=[];for(const[r,o]of t)o.n!==0&&i.push(L(r,e.get(r),l.get(r),o));return q(i)}export function poolCapabilityFigures(n,s){const{defByTestNumber:e,specByTest:l}=A(s),t=new Map;for(const r of n)for(const o of r){if(!e.has(o.testNumber)||o.n===0)continue;let f=t.get(o.testNumber);f||(f={n:0,sum:0,sumSq:0,withinNumerator:0,withinDenominator:0},t.set(o.testNumber,f));const p=o.stdOverall*o.stdOverall;f.n+=o.n,f.sum+=o.n*o.mean,f.sumSq+=(o.n-1)*p+o.n*o.mean*o.mean,o.n>=2&&(f.withinNumerator+=(o.n-1)*p,f.withinDenominator+=o.n-1)}const i=[];for(const[r,o]of t)i.push(L(r,e.get(r),l.get(r),o));return q(i)}