@wafertools/wafermap 0.33.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/AGENTS.md +6 -6
  2. package/CHANGELOG.md +271 -0
  3. package/README.md +5 -5
  4. package/dist/packages/canvas-adapter/chartPopulation.d.ts +15 -10
  5. package/dist/packages/canvas-adapter/chartPopulation.js +1 -1
  6. package/dist/packages/canvas-adapter/charts/barPanel.d.ts +8 -1
  7. package/dist/packages/canvas-adapter/charts/barPanel.js +1 -1
  8. package/dist/packages/canvas-adapter/charts/binCluster.d.ts +7 -1
  9. package/dist/packages/canvas-adapter/charts/binCluster.js +1 -1
  10. package/dist/packages/canvas-adapter/charts/boxplot.js +1 -1
  11. package/dist/packages/canvas-adapter/charts/capability.js +1 -1
  12. package/dist/packages/canvas-adapter/charts/chartShell.d.ts +72 -5
  13. package/dist/packages/canvas-adapter/charts/chartShell.js +1 -1
  14. package/dist/packages/canvas-adapter/charts/correlation.js +1 -2
  15. package/dist/packages/canvas-adapter/charts/groupedBarPlot.d.ts +2 -0
  16. package/dist/packages/canvas-adapter/charts/groupedBarPlot.js +1 -1
  17. package/dist/packages/canvas-adapter/charts/histogram.d.ts +16 -0
  18. package/dist/packages/canvas-adapter/charts/histogram.js +1 -1
  19. package/dist/packages/canvas-adapter/charts/palette.d.ts +2 -0
  20. package/dist/packages/canvas-adapter/charts/palette.js +1 -1
  21. package/dist/packages/canvas-adapter/charts/plotChart.d.ts +27 -0
  22. package/dist/packages/canvas-adapter/charts/plotChart.js +1 -0
  23. package/dist/packages/canvas-adapter/charts/pointInteractions.d.ts +45 -0
  24. package/dist/packages/canvas-adapter/charts/pointInteractions.js +1 -0
  25. package/dist/packages/canvas-adapter/charts/regionYieldDiagram.d.ts +8 -1
  26. package/dist/packages/canvas-adapter/charts/regionYieldDiagram.js +1 -1
  27. package/dist/packages/canvas-adapter/charts/scatter.d.ts +19 -0
  28. package/dist/packages/canvas-adapter/charts/scatter.js +1 -1
  29. package/dist/packages/canvas-adapter/charts/sweep.d.ts +12 -0
  30. package/dist/packages/canvas-adapter/charts/sweep.js +1 -1
  31. package/dist/packages/canvas-adapter/charts/testPassRate.d.ts +7 -0
  32. package/dist/packages/canvas-adapter/charts/testPassRate.js +1 -1
  33. package/dist/packages/canvas-adapter/charts/trend.d.ts +11 -0
  34. package/dist/packages/canvas-adapter/charts/trend.js +1 -1
  35. package/dist/packages/canvas-adapter/confirmDialog.d.ts +13 -0
  36. package/dist/packages/canvas-adapter/confirmDialog.js +1 -0
  37. package/dist/packages/canvas-adapter/dataTab.d.ts +137 -0
  38. package/dist/packages/canvas-adapter/dataTab.js +1 -0
  39. package/dist/packages/canvas-adapter/dieList.d.ts +39 -4
  40. package/dist/packages/canvas-adapter/dieList.js +6 -7
  41. package/dist/packages/canvas-adapter/drilldown.d.ts +23 -3
  42. package/dist/packages/canvas-adapter/drilldown.js +1 -1
  43. package/dist/packages/canvas-adapter/guideWindow.d.ts +96 -0
  44. package/dist/packages/canvas-adapter/guideWindow.js +1 -0
  45. package/dist/packages/canvas-adapter/identityHeader.d.ts +19 -0
  46. package/dist/packages/canvas-adapter/identityHeader.js +1 -1
  47. package/dist/packages/canvas-adapter/index.d.ts +3 -3
  48. package/dist/packages/canvas-adapter/index.js +1 -1
  49. package/dist/packages/canvas-adapter/insightsTab.d.ts +75 -54
  50. package/dist/packages/canvas-adapter/insightsTab.js +1 -1
  51. package/dist/packages/canvas-adapter/maplessSummary.d.ts +2 -2
  52. package/dist/packages/canvas-adapter/plotEditor.d.ts +29 -0
  53. package/dist/packages/canvas-adapter/plotEditor.js +1 -0
  54. package/dist/packages/canvas-adapter/plotItems.d.ts +32 -0
  55. package/dist/packages/canvas-adapter/plotItems.js +1 -0
  56. package/dist/packages/canvas-adapter/plotModal.d.ts +30 -0
  57. package/dist/packages/canvas-adapter/plotModal.js +1 -0
  58. package/dist/packages/canvas-adapter/plotStore.d.ts +52 -0
  59. package/dist/packages/canvas-adapter/plotStore.js +1 -0
  60. package/dist/packages/canvas-adapter/plotTab.d.ts +33 -0
  61. package/dist/packages/canvas-adapter/plotTab.js +1 -0
  62. package/dist/packages/canvas-adapter/renderWaferGallery.d.ts +11 -2
  63. package/dist/packages/canvas-adapter/renderWaferGallery.js +1 -1
  64. package/dist/packages/canvas-adapter/renderWaferMap.d.ts +29 -2
  65. package/dist/packages/canvas-adapter/renderWaferMap.js +1 -1
  66. package/dist/packages/canvas-adapter/summaryPanel.d.ts +34 -10
  67. package/dist/packages/canvas-adapter/summaryPanel.js +2 -4
  68. package/dist/packages/canvas-adapter/summaryRail.d.ts +7 -0
  69. package/dist/packages/canvas-adapter/summaryRail.js +1 -0
  70. package/dist/packages/canvas-adapter/sweepEditor.d.ts +17 -0
  71. package/dist/packages/canvas-adapter/sweepEditor.js +1 -0
  72. package/dist/packages/canvas-adapter/tableExport.d.ts +22 -0
  73. package/dist/packages/canvas-adapter/tableExport.js +3 -0
  74. package/dist/packages/canvas-adapter/toolbar.d.ts +25 -97
  75. package/dist/packages/canvas-adapter/toolbar.js +2 -2
  76. package/dist/packages/canvas-adapter/userGuideHtml.d.ts +1 -1
  77. package/dist/packages/canvas-adapter/userGuideHtml.js +354 -45
  78. package/dist/packages/canvas-adapter/version.d.ts +2 -2
  79. package/dist/packages/canvas-adapter/version.js +1 -1
  80. package/dist/packages/canvas-adapter/viewSwitch.d.ts +13 -0
  81. package/dist/packages/canvas-adapter/viewSwitch.js +1 -0
  82. package/dist/packages/canvas-adapter/virtualTable.d.ts +44 -0
  83. package/dist/packages/canvas-adapter/virtualTable.js +1 -0
  84. package/dist/packages/core/classify.d.ts +3 -2
  85. package/dist/packages/core/classify.js +1 -1
  86. package/dist/packages/core/index.d.ts +1 -1
  87. package/dist/packages/core/index.js +1 -1
  88. package/dist/packages/core/passBins.d.ts +17 -4
  89. package/dist/packages/core/passBins.js +1 -1
  90. package/dist/packages/core/reticle.d.ts +20 -0
  91. package/dist/packages/core/reticle.js +1 -1
  92. package/dist/packages/core/ringCount.d.ts +22 -0
  93. package/dist/packages/core/ringCount.js +1 -0
  94. package/dist/packages/core/tableCsv.d.ts +43 -0
  95. package/dist/packages/core/tableCsv.js +3 -0
  96. package/dist/packages/core/wafer.d.ts +15 -0
  97. package/dist/packages/core/wafer.js +1 -1
  98. package/dist/packages/renderer/binColors.d.ts +6 -6
  99. package/dist/packages/renderer/binColors.js +1 -1
  100. package/dist/packages/renderer/buildView.d.ts +1 -1
  101. package/dist/packages/renderer/buildView.js +1 -1
  102. package/dist/packages/renderer/buildWaferMap.js +1 -1
  103. package/dist/packages/renderer/derivedTests/apply.js +1 -1
  104. package/dist/packages/renderer/derivedTests/evaluate.d.ts +3 -1
  105. package/dist/packages/renderer/derivedTests/evaluate.js +1 -1
  106. package/dist/packages/renderer/derivedTests/parser.d.ts +7 -0
  107. package/dist/packages/renderer/derivedTests/parser.js +2 -2
  108. package/dist/packages/stats/analyzeWaferLot.js +1 -1
  109. package/dist/packages/stats/analyzeWaferMap.js +1 -1
  110. package/dist/packages/stats/binPareto.d.ts +1 -1
  111. package/dist/packages/stats/binPareto.js +1 -1
  112. package/dist/packages/stats/dieRegions.d.ts +42 -0
  113. package/dist/packages/stats/dieRegions.js +1 -0
  114. package/dist/packages/stats/facets.d.ts +8 -0
  115. package/dist/packages/stats/facets.js +1 -1
  116. package/dist/packages/stats/histogram.d.ts +27 -0
  117. package/dist/packages/stats/histogram.js +1 -1
  118. package/dist/packages/stats/index.d.ts +4 -1
  119. package/dist/packages/stats/index.js +1 -1
  120. package/dist/packages/stats/lotDrift.js +1 -1
  121. package/dist/packages/stats/lotPattern.js +1 -1
  122. package/dist/packages/stats/math.d.ts +9 -6
  123. package/dist/packages/stats/math.js +1 -1
  124. package/dist/packages/stats/metadataColumns.js +1 -1
  125. package/dist/packages/stats/patternClassification.d.ts +1 -1
  126. package/dist/packages/stats/patternClassification.js +1 -1
  127. package/dist/packages/stats/plotData.d.ts +258 -0
  128. package/dist/packages/stats/plotData.js +1 -0
  129. package/dist/packages/stats/plotId.d.ts +3 -0
  130. package/dist/packages/stats/plotId.js +1 -0
  131. package/dist/packages/stats/plotSpec.d.ts +119 -0
  132. package/dist/packages/stats/plotSpec.js +4 -0
  133. package/dist/packages/stats/presentation.d.ts +2 -0
  134. package/dist/packages/stats/presentation.js +1 -1
  135. package/dist/packages/stats/regions.d.ts +15 -0
  136. package/dist/packages/stats/regions.js +1 -1
  137. package/dist/packages/stats/renderSummaryReport.d.ts +8 -3
  138. package/dist/packages/stats/renderSummaryReport.js +15 -15
  139. package/dist/packages/stats/reportHtml.d.ts +1 -1
  140. package/dist/packages/stats/reportHtml.js +36 -29
  141. package/dist/packages/stats/scatter.d.ts +6 -0
  142. package/dist/packages/stats/scatter.js +1 -1
  143. package/dist/packages/stats/sweep.d.ts +37 -1
  144. package/dist/packages/stats/sweep.js +1 -1
  145. package/dist/packages/stats/sweepText.d.ts +14 -0
  146. package/dist/packages/stats/sweepText.js +1 -0
  147. package/dist/packages/stats/sweepXFromName.d.ts +14 -0
  148. package/dist/packages/stats/sweepXFromName.js +1 -1
  149. package/dist/packages/stats/synthesis.d.ts +14 -4
  150. package/dist/packages/stats/synthesis.js +1 -1
  151. package/dist/packages/stats/testPassRate.d.ts +6 -0
  152. package/dist/packages/stats/testPassRate.js +1 -1
  153. package/dist/packages/stats/trend.js +1 -1
  154. package/dist/packages/stats/types.d.ts +1 -1
  155. package/dist/packages/stats/yield.d.ts +15 -6
  156. package/dist/packages/stats/yield.js +1 -1
  157. package/llms.txt +15 -3
  158. package/package.json +3 -3
@@ -1 +1 @@
1
- import{createWafer as z}from"../core/wafer.js";import{isYieldEligibleDie as ye,getDieKey as X,hasPosition as F}from"../core/dies.js";import{applyOrientation as ee,transformDies as be,clipDiesToWafer as we}from"../core/transforms.js";import{generateDies as xe}from"../core/dies.js";import{dieHasAnyTestData as De,dieLink as G,finaliseDie as j,linkDie as ve,recordedVerdict as Me,recordedVerdictsReader as Se,tableFromRows as Ce,testValue as q,testsPresent as ke,VERDICT_FAIL as Ae,VERDICT_NONE as Oe,VERDICT_PASS as Ne}from"../core/dieTable.js";import{isDieColumns as $e,linkColumns as Re,linkRows as te,relink as Te}from"./columnarInput.js";import{affineRotation as Ee,affineMirror as We,affineCompose as Fe,affinePoint as Ie}from"../core/transforms.js";import{inferWaferFromXY as _e}from"../core/inference/wafer.js";import{resolveGridPitch as Pe}from"../core/inference/pitch.js";import{assignGridIndices as Ve}from"../core/inference/grid.js";import{generateReticleGrid as Be}from"../core/reticle.js";import{applyDerivedTests as Le}from"./derivedTests/apply.js";import{isStdfBin as Ye,isStdfCoord as ne,isStdfTestNumber as ie,isStdfSite as Xe,STDF_BIN_MAX as je,STDF_COORD_MAX as se,STDF_TEST_NUM_MAX as Ke,STDF_SITE_MAX as He}from"../core/stdf.js";import{hasAnyKey as Ue,maxOf as J,minOf as re,modeOf as ze}from"../core/utils.js";import{aggregateValues as oe,aggregateBinCounts as Ge,stackHoldsMeasurements as qe}from"../core/aggregates.js";export function isParametricTest(t){return t?.testType!=="F"}export function isBuiltMap(t){return"wafer"in t&&"dies"in t&&"dataAxisFlip"in t}function Je(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:4,ringCountWarning:void 0};if(typeof t!="number"||!Number.isFinite(t))return e(4,"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 Qe(t,e){const n=Array.isArray(t)?{}:t,i={hbin:0,sbin:0,siteNum:0,testValues:0,testPass:0};let a;const o=(l,b)=>{i[l]++,a??=`${l} ${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 l of e.badTestNumbers)r.add(l)}const h=l=>l==null?!0:typeof l!="number"?!1:Number.isNaN(l)?(m++,!1):Ye(l)?!0:(s.bins++,!1);function d(l){const b=new Set,w=new Set;for(let O=0;O<l.length;O+=O<50?1:100){const k=l[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=>ie(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<l.length;O++){const k=l[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),h(M.hbin)||(_().hbin=void 0),h(M.sbin)||(_().sbin=void 0);const L=typeof M.x=="number"&&!ne(M.x),f=typeof M.y=="number"&&!ne(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"&&!Xe(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??=l.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 l=n.lotStack?.results;if(Array.isArray(l)){const b=l.map(w=>Array.isArray(w)?d(w):void 0);b.some(Boolean)&&(c.stackResults=b.map((w,g)=>w??l[g]))}}if(Array.isArray(n.testDefs)){const l=n.testDefs,b=l.filter(w=>w==null||typeof w.testNumber!="number"||ie(w.testNumber));for(const w of l)b.includes(w)||r.add(String(w.testNumber));b.length!==l.length&&(c.testDefs=b)}const p=n.waferConfig?.orientation;if(typeof p=="number"){const l=Number.isFinite(p)?(p%360+360)%360:NaN;l===0||l===90||l===180||l===270?c.orientation=l:(s.orientation++,c.orientation=0)}const u=(l,b,w=`${b}s`)=>`${l} ${l===1?b:w}`,x=[];if(i.hbin&&x.push(u(i.hbin,"hard bin")),i.sbin&&x.push(u(i.sbin,"soft bin")),i.siteNum&&x.push(u(i.siteNum,"site number")),i.testValues&&x.push(u(i.testValues,"test value")),i.testPass&&x.push(u(i.testPass,"pass/fail verdict")),x.length){const l=`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] ${l}`),c.warnings.push({code:"input-values-not-numbers",message:l,severity:"error"})}const D=[];if(s.bins&&D.push(`${u(s.bins,"bin")} (legal: whole numbers 0\u2013${je}) \u2014 those dies have no bin`),s.positions&&D.push(`${u(s.positions,"coordinate")} (legal: whole numbers \u2212${se} to ${se}) \u2014 those dies have no position`),r.size&&D.push(`${u(r.size,"test number")} (legal: whole numbers 0\u2013${Ke}) \u2014 those tests are left out`),s.values&&D.push(`${u(s.values,"test value")} that ${s.values===1?"is":"are"} not finite \u2014 left out`),s.sites&&D.push(`${u(s.sites,"site number")} (legal: 0\u2013${He}) \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 l=[];D.length&&l.push(`buildWaferMap received values outside the STDF V4 ranges, treated as missing: ${D.join("; ")}.`),m&&l.push(`${u(m,"bin was","bins were")} NaN and ${m===1?"is":"are"} treated as no bin.`);const b=l.join(" ");console.warn(`[wafermap] ${b}`),c.warnings.push({code:"input-values-outside-stdf",message:b,severity:"warning"})}return c}function ae(t){const e=(h,d)=>h!==null&&typeof h=="object"&&h[d]!==void 0,n=Array.isArray(t)?{}:t,i=[],a=(h,d,c)=>{h&&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(h=>e(h,"index")&&!e(h,"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(h=>Array.isArray(h));if(a(s.some(h=>h.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 Ze(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=z({diameter:e,notch:t.waferConfig?.notch,orientation:0}),o=we(xe(a,{width:n,height:i}),a,{width:n,height:i}).filter(d=>!d.partial),{flipX:s,flipY:r}=de(t.dieConfig,{type:"center"}),{layout:m,...h}=t;return{...h,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 et(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)&&$e(t.results)?{...t,results:Re(t.results,e).records}:t,i=Qe(n,e);return Array.isArray(n)?{results:Q(i.results??n),waferOpts:void 0,dieOpts:void 0,explicitDies:void 0,reticleOpts:void 0,lotStackOpts:void 0,passBins:[1],ringCount:4,ringCountWarning:void 0,removedFieldWarning:ae(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:Q(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(Q)}:void 0,passBins:n.passBins??[1],...Je(n.ringCount),removedFieldWarning:ae(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 Q(t){return t.length>0&&G(t[0])!==void 0?t:te(t).records}function tt(t,e){return e?.coordinateOrigin?e.coordinateOrigin:{type:"center"}}function nt(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 it(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,h=-1/0;for(const d of t){const c=Math.round(d.x)-e,p=Math.round(d.y)-n;c<s&&(s=c),c>r&&(r=c),p<m&&(m=p),p>h&&(h=p)}return{colMidX:(s+r)/2*i,colMidY:(m+h)/2*a,anchored:!1}}function st(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 p=Math.round(c.x)-e,u=Math.round(c.y)-n;r+=p,m+=u,p<i&&(i=p),p>a&&(a=p),u<o&&(o=u),u>s&&(s=u)}const h=t.length,d=(c,p,u)=>{const x=(u-p)/2;return x<=0?0:Math.abs(c/h-(p+u)/2)/x};return d(r,i,a)>.11||d(m,o,s)>.11}function de(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 rt(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 ot(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 ke(d,"values"))o.has(c)||s.add(c);if(s.size===0)return oe(a,n);const r=[...s],m=r.map(d=>oe(a,n,d)),h=new Map;for(let d=0;d<r.length;d++){const c=r[d];for(const p of m[d]){const u=X(p);h.has(u)||h.set(u,{template:p,testValues:{}});const x=h.get(u),D=p.testValues?.[0];D!==void 0&&(x.testValues[c]=D)}}return[...h.values()].map(({template:d,testValues:c})=>({...d,testValues:Ue(c)?c:void 0}))}if(n==="countBin"||n==="percent"){if(i===void 0)return[];const o=Ge(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 h=X(m);o.has(h)||o.set(h,[]),o.get(h).push(m)}const s=[];for(const[r,m]of o){const h=r.split(","),d=Number(h[0]),c=Number(h[1]),p=m.map(x=>x.hbin).filter(x=>x!==void 0),u=ze(p);u!==null&&s.push({x:d,y:c,hbin:u})}return s}return[]}function fe(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 ue(t,e,n="exclude"){const i=new Set(e),o=t.filter(u=>!u.partial).filter(u=>u.edgeExcluded).length,s=t.filter(u=>u.partial).length;let r=0,m=0,h=!1;for(const u of t){if(!ye(u))continue;const x=u.hbin??u.sbin;x!==void 0&&(h=!0,i.has(x)?r++:m++)}const d=r+m,c=h&&d>0?r/d*100:null;let p=null;if(n==="denominator-only"){const u=d+o;p=h&&u>0?r/u*100:null}return{passDies:r,failDies:m,edgeExcludedDies:o,partialDies:s,totalDies:d,yieldPercent:c,yieldPercentGross:p}}function le(t,e,n,i,a,o=0,s=0,r=0,m=0,h=0,d=!1,c=!1){if(!t)return[];const p=t.anchorDie??{x:0,y:0},u=Be(e,{width:t.width,height:t.height,diePitchX:i,diePitchY:a,anchorDie:{x:p.x-o,y:p.y-s},gridOrigin:{x:-r,y:-m}}),x=Fe(We(d,c,e.center.x,e.center.y),Ee(h,e.center.x,e.center.y));return u.filter(D=>{const l=D.width/2,b=D.height/2,w=[[D.x-l,D.y-b],[D.x+l,D.y-b],[D.x+l,D.y+b],[D.x-l,D.y+b]].map(([v,N])=>Ie(x,v,N)),g=re(w.map(v=>v.x)),y=J(w.map(v=>v.x)),A=re(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 at(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 dt=.2;function ft(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)<=dt,c=new Map,p=[],u=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=u.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}),p.push(A)):(R.count++,A.startsWith("i:")&&x++,o(R.winner,g)&&(R.winner=g)),y!==void 0&&u.set(y,A)}const l=[],b=[...p.filter(g=>g.startsWith("p:")),...p.filter(g=>!g.startsWith("p:"))];for(const g of b){const y=c.get(g);y!==void 0&&l.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:l,warning:w}}export function getDieTestValue(t,e){return q(t,e)}export function getTestPassStatus(t,e,n){const i=Me(t,e);return i!==void 0?i:n!==void 0&&!isParametricTest(n)?ce(q(t,e)):void 0}function ce(t){return t===0||t===1?t===1:void 0}export function testPassStatusReader(t){const e=t.map(a=>a.testNumber),n=Se(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]!==Oe||!i[r])continue;const m=ce(q(o,e[r]));m!==void 0&&(s[r]=m?Ne:Ae)}return s}}export function dieHasTestData(t){return De(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 ve({...t,...n},o.table,o.row)}function he(t){return t.some(dieHasTestData)?"value":"hardBin"}function pe(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 ut="do not fit inside the supplied",lt="Inferred wafer diameter",ct="The probed dies reach only",ht=.75,pt=20;export const STANDARD_WAFER_DIAMETERS_MM=[100,125,150,200,300];const mt=.02;function me(t,e){return e.reduce((n,i)=>Math.abs(i-t)<Math.abs(n-t)?i:n)}function gt(t,e){if(!e.length)return!0;const n=me(t,e);return Math.abs(n-t)/n<=mt}function yt(t){return t===void 0?STANDARD_WAFER_DIAMETERS_MM:t.filter(e=>Number.isFinite(e)&&e>0)}export function buildWaferMap(t){const e=et(!Array.isArray(t)&&t.layout?Ze(t):t),n=[];if(e.derivedTests){const f=new Set(e.passBins),C=$=>{const E=$.length>0?G($[0]):void 0,W=Le($,E?.table??Ce([]),e.testDefs,e.derivedTests,f);return E&&Te($,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(rt));const i=e.lotStackOpts?te(ot(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}=ft(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 Z=V.get(X(P));return Z?H(P,Z):P})}const $=e.waferOpts?.diameter??300,E=z({diameter:$,notch:e.waferOpts?.notch,orientation:e.waferOpts?.orientation??0,metadata:e.waferOpts?.metadata});E.orientation!==0&&(f=ee(f,E)),f=f.map(j);const W=le(e.reticleOpts,E,f,1,1,0,0,0,0,E.orientation),ge=S.map((V,P)=>j(H({id:`unpositioned_${P}`,width:f[0]?.width??1,height:f[0]?.height??1},V))),U=[...f,...C,...ge];return{wafer:E,dies:U,dataAxisFlip:{x:!1,y:!1},reticleConfig:e.reticleOpts,units:"mm",inference:s,warnings:[...e.removedFieldWarning?[e.removedFieldWarning]:[],...e.inputValueWarnings,...o?[o]:[],...pe(r,s),...n,...e.ringCountWarning?[e.ringCountWarning]:[]],plotMode:he(a),metadata:E.metadata??null,isLotStack:!1,dataCoverage:fe(U),passBins:e.passBins,ringCount:e.ringCount,yield:ue(U,e.passBins,e.edgeDieYieldMode),reticles:W,hbinDefs:e.hbinDefs,sbinDefs:e.sbinDefs,testDefs:e.testDefs,metadataFields:e.metadataFields}}const m=a.filter(F),h=a.filter(f=>!F(f)),d=m.map(f=>({x:f.x,y:f.y})),c=Pe(d,e.dieOpts,e.waferOpts?.diameter);s.diePitch={confidence:c.confidence,units:c.units};const{pitchX:p,pitchY:u}=c,x=c.units,D=tt(m,e.dieOpts),l=Ve(d);s.grid={confidence:l.confidence};const{offsetX:b,offsetY:w}=nt(d,D,l),{flipX:g,flipY:y}=de(e.dieOpts,D),{colMidX:A,colMidY:R,anchored:v}=it(d,b,w,p,u,e.waferOpts?.center);let N=e.waferOpts?.diameter;const B=d.map(f=>({x:(Math.round(f.x)-b)*p-A,y:(Math.round(f.y)-w)*u-R})),I=J(B.map(({x:f,y:C})=>Math.hypot(Math.abs(f)+p/2,Math.abs(C)+u/2)));if(N===void 0)if(d.length>0)if(x==="mm"){const f=_e(B,{minRadius:I});N=f.diameter,s.wafer={confidence:f.confidence,method:f.method};const C=yt(e.standardDiameters);if(!gt(N,C)){const T=me(N,C);r.push({code:"non-standard-diameter",message:`${lt} ${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&&st(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>=pt){const f=I/(N/2);f<ht&&r.push({code:"diameter-exceeds-die-extent",message:`${ct} ${(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)+p/2,Math.abs(S)+u/2)>N/2+1e-9).length;r.push({code:"geometry-conflict",message:`${C} of ${B.length} probed die positions ${ut} ${N} mm wafer at the supplied die pitch of ${p} \xD7 ${u} 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=z({diameter:N,notch:e.waferOpts?.notch,orientation:e.waferOpts?.orientation??0,metadata:e.waferOpts?.metadata});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*p-A,physY:T*u-R,width:p,height:u,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=ee(k,O),(g||y)&&(k=be(k,{flipX:g,flipY:y},O.center));const M=[];e.waferOpts?.edgeExclusion&&e.waferOpts.edgeExclusion>0&&(k=at(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=le(e.reticleOpts,O,k,p,u,b,w,A,R,O.orientation,g,y),_=h.map((f,C)=>j(H({id:`unpositioned_${C}`,width:p,height:u},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]:[],...pe(r,s),...M,...n,...e.ringCountWarning?[e.ringCountWarning]:[]],plotMode:he(a),metadata:O.metadata??null,isLotStack:e.lotStackOpts!==void 0,dataCoverage:fe(L),passBins:e.passBins,ringCount:e.ringCount,yield:ue(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 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 +1 @@
1
- import{isStdfTestNumber as D,STDF_TEST_NUM_MAX as T}from"../../core/stdf.js";import{diePassStatus as M}from"../../core/dies.js";import{getTestPassStatus as V,isParametricTest as _}from"../buildWaferMap.js";import{classifySpec as F}from"../spec.js";import{parseExpression as P}from"./parser.js";import{evaluate as A}from"./evaluate.js";import{extendTable as E,rowView as O,testValue as I,HAS_VALUES as k,HAS_VERDICTS as C,VERDICT_FAIL as L,VERDICT_NONE as S,VERDICT_PASS as R}from"../../core/dieTable.js";function l(N){return{code:"derived-test-invalid",message:N,severity:"warning"}}function j(N,p){const m=[],r=n=>{switch(n.k){case"acc":{if(n.kind!=="t")return;const o=p.get(n.test)?.unit;return o?new Set([o]):void 0}case"unary":return n.op==="-"?r(n.arg):void 0;case"binary":{const o=r(n.left),i=r(n.right);if(n.op==="+"||n.op==="-"){if(o&&i){const a=new Set([...o,...i]);return a.size>1&&m.push(`${[...a].join(" and ")} are combined by "${n.op}"`),a}return o??i}return}case"call":{if(n.name==="min"||n.name==="max"||n.name==="mean"||n.name==="sum"){const o=n.args[0];if(o?.k==="vec"&&o.kind==="t"){const i=new Set(o.tests.map(a=>p.get(a)?.unit).filter(a=>!!a));return i.size>1&&m.push(`${[...i].join(" and ")} are combined by "${n.name}"`),i}}return}default:return}};return r(N),m}function B(N,p,m){const r=[],n=new Map((p??[]).map(e=>[e.testNumber,e])),o=e=>`${JSON.stringify(e.name??"")} (test ${e.testNumber})`,i=[],a=new Set;for(const e of N){const t=o(e);if(!D(e.testNumber)){r.push(l(`Derived test ${t} was dropped: \`testNumber\` must be a whole number from 0 to ${T}, as STDF stores it.`));continue}if(m.has(e.testNumber)||n.has(e.testNumber)){r.push(l(`Derived test ${t} was dropped: test number ${e.testNumber} already exists in the data. Measured values are never replaced by a derived test \u2014 give it an unused number.`));continue}if(a.has(e.testNumber)){r.push(l(`Derived test ${t} was dropped: test number ${e.testNumber} is used by an earlier derived test.`));continue}if(typeof e.expression!="string"||e.expression.trim()===""){r.push(l(`Derived test ${t} was dropped: \`expression\` is empty.`));continue}a.add(e.testNumber),i.push(e)}const v=new Map(n);for(const e of i){const{expression:t,constants:d,...u}=e;v.set(e.testNumber,{...u,testType:e.testType??"P"})}const b=new Map,f=new Set;for(const e of i){const t=o(e),d={testDefs:v,constants:e.constants??{}},u=P(e.expression,d);if(!u.ok){r.push(l(`Derived test ${t} was dropped: ${u.message}`)),f.add(e.testNumber);continue}const s=u.type==="boolean",c=!_(e);if(s!==c){r.push(l(s?`Derived test ${t} was dropped: its expression produces a true/false verdict, so it must declare \`testType: 'F'\`.`:`Derived test ${t} was dropped: it declares \`testType: 'F'\` but its expression produces a number. Functional tests carry a verdict, not a measurement.`)),f.add(e.testNumber);continue}if(s&&(e.limitLow!==void 0||e.limitHigh!==void 0)&&r.push(l(`Derived test ${t}: test limits are ignored on a true/false derived test.`)),e.testNumber===void 0)continue;const $=e.testNumber,x=[...new Set(u.reads.map(h=>h.test))].filter(h=>h!==$&&a.has(h));if(u.reads.some(h=>h.test===$)){r.push(l(`Derived test ${t} was dropped: its expression reads itself.`)),f.add($);continue}for(const h of j(u.ast,v))r.push(l(`Derived test ${t} combines different units \u2014 ${h}. The result is computed as written; set \`unit\` on the derived test to say what it is.`));b.set($,{raw:e,compiled:{def:{...e,testType:s?"F":"P",derived:!0},ast:u.ast,boolean:s},deps:x})}const g=[],w=new Map,y=(e,t)=>{if(w.get(e)==="done")return!f.has(e);if(w.get(e)==="visiting"){const s=[...t.slice(t.indexOf(e)),e].join(" \u2192 ");for(const c of t.slice(t.indexOf(e)))f.has(c)||(f.add(c),r.push(l(`Derived test ${o(b.get(c).raw)} was dropped: its expression depends on itself through ${s}.`)));return!1}const d=b.get(e);if(d===void 0)return!1;w.set(e,"visiting");let u=!0;for(const s of d.deps)if(!y(s,[...t,e])){if(!f.has(e)){f.add(e);const c=b.get(s)?.raw.name??`test ${s}`;r.push(l(`Derived test ${o(d.raw)} was dropped: it reads ${JSON.stringify(c)} (test ${s}), which was itself dropped.`))}u=!1;break}return w.set(e,"done"),!u||f.has(e)?!1:(g.push(d.compiled),!0)};for(const e of i)y(e.testNumber,[]);return{compiled:g,warnings:r}}export function applyDerivedTests(N,p,m,r,n){if(r===void 0||r.length===0)return{table:p,testDefs:m,warnings:[]};const o=new Set;for(const[e,t]of p.values)t.some(d=>!Number.isNaN(d))&&o.add(e);for(const[e,t]of p.verdicts)t.some(d=>d!==S)&&o.add(e);const{compiled:i,warnings:a}=B(r,m,o);if(i.length===0)return{table:p,testDefs:m,warnings:a};const v=new Map((m??[]).map(e=>[e.testNumber,e]));for(const e of i)v.set(e.def.testNumber,e.def);const b=p.rows,f=new Map,g=new Map;for(const e of i)e.boolean?g.set(e.def.testNumber,new Int8Array(b).fill(S)):f.set(e.def.testNumber,new Float64Array(b).fill(NaN));const w=E(p,f,g),y=O(w);for(let e=0;e<b;e++){const t=y(e),d=s=>I(t,s),u={value:d,testPass:s=>V(t,s,v.get(s)),specPass:s=>{const c=F(d(s),v.get(s));return c===null?void 0:c==="pass"},diePass:()=>M(N[e],n)};for(const s of i){const c=A(s.ast,u);c!==void 0&&(s.boolean?(g.get(s.def.testNumber)[e]=c?R:L,w.fields[e]|=C):(f.get(s.def.testNumber)[e]=c,w.fields[e]|=k))}}return{table:w,testDefs:[...m??[],...i.map(e=>e.def)],warnings:a}}
1
+ import{isStdfTestNumber as D,STDF_TEST_NUM_MAX as T}from"../../core/stdf.js";import{diePassStatus as M}from"../../core/dies.js";import{getTestPassStatus as F,isParametricTest as V}from"../buildWaferMap.js";import{classifySpec as _}from"../spec.js";import{parseExpression as P}from"./parser.js";import{evaluate as A}from"./evaluate.js";import{extendTable as E,rowView as O,testValue as I,HAS_VALUES as k,HAS_VERDICTS as C,VERDICT_FAIL as L,VERDICT_NONE as S,VERDICT_PASS as R}from"../../core/dieTable.js";function l(w){return{code:"derived-test-invalid",message:w,severity:"warning"}}function j(w,p){const m=[],n=r=>{switch(r.k){case"acc":{if(r.kind!=="t")return;const o=p.get(r.test)?.unit;return o?new Set([o]):void 0}case"unary":return r.op==="-"?n(r.arg):void 0;case"binary":{const o=n(r.left),a=n(r.right);if(r.op==="+"||r.op==="-"){if(o&&a){const d=new Set([...o,...a]);return d.size>1&&m.push(`${[...d].join(" and ")} are combined by "${r.op}"`),d}return o??a}return}case"call":{if(r.name==="min"||r.name==="max"||r.name==="mean"||r.name==="sum"){const o=r.args[0];if(o?.k==="vec"&&o.kind==="t"){const a=new Set(o.tests.map(d=>p.get(d)?.unit).filter(d=>!!d));return a.size>1&&m.push(`${[...a].join(" and ")} are combined by "${r.name}"`),a}}return}default:return}};return n(w),m}function B(w,p,m){const n=[],r=new Map((p??[]).map(e=>[e.testNumber,e])),o=e=>`${JSON.stringify(e.name??"")} (test ${e.testNumber})`,a=[],d=new Set;for(const e of w){const s=o(e);if(!D(e.testNumber)){n.push(l(`Derived test ${s} was dropped: \`testNumber\` must be a whole number from 0 to ${T}, as STDF stores it.`));continue}if(m.has(e.testNumber)||r.has(e.testNumber)){n.push(l(`Derived test ${s} was dropped: test number ${e.testNumber} already exists in the data. Measured values are never replaced by a derived test \u2014 give it an unused number.`));continue}if(d.has(e.testNumber)){n.push(l(`Derived test ${s} was dropped: test number ${e.testNumber} is used by an earlier derived test.`));continue}if(typeof e.expression!="string"||e.expression.trim()===""){n.push(l(`Derived test ${s} was dropped: \`expression\` is empty.`));continue}d.add(e.testNumber),a.push(e)}const g=new Map(r);for(const e of a){const{expression:s,constants:u,...c}=e;g.set(e.testNumber,{...c,testType:e.testType??"P"})}const h=new Map,f=new Set;for(const e of a){const s=o(e),u={testDefs:g,constants:e.constants??{}},c=P(e.expression,u);if(!c.ok){n.push(l(`Derived test ${s} was dropped: ${c.message}`)),f.add(e.testNumber);continue}const t=c.type==="boolean",i=!V(e);if(t!==i){n.push(l(t?`Derived test ${s} was dropped: its expression produces a true/false verdict, so it must declare \`testType: 'F'\`.`:`Derived test ${s} was dropped: it declares \`testType: 'F'\` but its expression produces a number. Functional tests carry a verdict, not a measurement.`)),f.add(e.testNumber);continue}if(t&&(e.limitLow!==void 0||e.limitHigh!==void 0)&&n.push(l(`Derived test ${s}: test limits are ignored on a true/false derived test.`)),e.testNumber===void 0)continue;const N=e.testNumber,x=[...new Set(c.reads.map(v=>v.test))].filter(v=>v!==N&&d.has(v));if(c.reads.some(v=>v.test===N)){n.push(l(`Derived test ${s} was dropped: its expression reads itself.`)),f.add(N);continue}for(const v of j(c.ast,g))n.push(l(`Derived test ${s} combines different units \u2014 ${v}. The result is computed as written; set \`unit\` on the derived test to say what it is.`));h.set(N,{raw:e,compiled:{def:{...e,testType:t?"F":"P",derived:!0},ast:c.ast,boolean:t},deps:x})}const y=[],b=new Map,$=(e,s)=>{if(b.get(e)==="done")return!f.has(e);if(b.get(e)==="visiting"){const t=[...s.slice(s.indexOf(e)),e].join(" \u2192 ");for(const i of s.slice(s.indexOf(e)))f.has(i)||(f.add(i),n.push(l(`Derived test ${o(h.get(i).raw)} was dropped: its expression depends on itself through ${t}.`)));return!1}const u=h.get(e);if(u===void 0)return!1;b.set(e,"visiting");let c=!0;for(const t of u.deps)if(!$(t,[...s,e])){if(!f.has(e)){f.add(e);const i=h.get(t)?.raw.name??`test ${t}`;n.push(l(`Derived test ${o(u.raw)} was dropped: it reads ${JSON.stringify(i)} (test ${t}), which was itself dropped.`))}c=!1;break}return b.set(e,"done"),!c||f.has(e)?!1:(y.push(u.compiled),!0)};for(const e of a)$(e.testNumber,[]);return{compiled:y,warnings:n}}export function applyDerivedTests(w,p,m,n,r){if(n===void 0||n.length===0)return{table:p,testDefs:m,warnings:[]};const o=new Set;for(const[e,s]of p.values)s.some(u=>!Number.isNaN(u))&&o.add(e);for(const[e,s]of p.verdicts)s.some(u=>u!==S)&&o.add(e);const{compiled:a,warnings:d}=B(n,m,o);if(a.length===0)return{table:p,testDefs:m,warnings:d};const g=new Map((m??[]).map(e=>[e.testNumber,e]));for(const e of a)g.set(e.def.testNumber,e.def);const h=p.rows,f=new Map,y=new Map;for(const e of a)e.boolean?y.set(e.def.testNumber,new Int8Array(h).fill(S)):f.set(e.def.testNumber,new Float64Array(h).fill(NaN));const b=E(p,f,y),$=O(b);for(let e=0;e<h;e++){const s=$(e),u=t=>I(s,t),c={value:u,testPass:t=>F(s,t,g.get(t)),specPass:t=>{const i=_(u(t),g.get(t));return i===null?void 0:i==="pass"},diePass:()=>M(w[e],r),field:t=>{const i=w[e],N=t==="x"?i.x:t==="y"?i.y:t==="hbin"?i.hbin:t==="sbin"?i.sbin:i.siteNum;return typeof N=="number"&&Number.isFinite(N)?N:void 0}};for(const t of a){const i=A(t.ast,c);i!==void 0&&(t.boolean?(y.get(t.def.testNumber)[e]=i?R:L,b.fields[e]|=C):(f.get(t.def.testNumber)[e]=i,b.fields[e]|=k))}}return{table:b,testDefs:[...m??[],...a.map(e=>e.def)],warnings:d}}
@@ -21,7 +21,7 @@
21
21
  * for the same reason: `NaN` must reach the map as no-data, not as a value that
22
22
  * drags a mean toward zero or classifies as in-spec.
23
23
  */
24
- import type { ExprNode } from './parser.js';
24
+ import type { DieField, ExprNode } from './parser.js';
25
25
  /** Per-die data the evaluator is allowed to reach. Deliberately a closed set of
26
26
  * functions rather than the die object, so the AST has no path to anything
27
27
  * else on the die or in the host. */
@@ -34,6 +34,8 @@ export interface EvalContext {
34
34
  specPass(test: number): boolean | undefined;
35
35
  /** The die's bin-based pass verdict, via `diePassStatus`. */
36
36
  diePass(): boolean | undefined;
37
+ /** One of the die's own recorded fields, or `undefined` when it has none (a die with no position, no bin, no site). */
38
+ field(name: DieField): number | undefined;
37
39
  }
38
40
  type Scalar = number | boolean | undefined;
39
41
  /**
@@ -1 +1 @@
1
- import{minOf as c,maxOf as f}from"../../core/utils.js";function s(e){return Number.isFinite(e)?e:void 0}function l(e,t){const n=r=>e.kind==="t"?t.value(r):e.kind==="testPass"?t.testPass(r):t.specPass(r);return e.tests.map(n)}function o(e,t){const n=t.filter(r=>r!==void 0);if(e==="countKnown")return n.length;if(n.length!==0)switch(e){case"all":return n.every(Boolean);case"any":return n.some(Boolean);case"none":return!n.some(Boolean);case"countTrue":return n.filter(Boolean).length;case"countFalse":return n.filter(r=>!r).length;case"min":return c(n);case"max":return f(n);case"sum":return s(n.reduce((r,a)=>r+a,0));case"mean":return s(n.reduce((r,a)=>r+a,0)/n.length);default:return}}const d={abs:e=>Math.abs(e[0]),sqrt:e=>Math.sqrt(e[0]),ln:e=>Math.log(e[0]),log10:e=>Math.log10(e[0]),exp:e=>Math.exp(e[0]),floor:e=>Math.floor(e[0]),ceil:e=>Math.ceil(e[0]),round:e=>Math.round(e[0]),sign:e=>Math.sign(e[0]),pow:e=>Math.pow(e[0],e[1]),min:e=>c(e),max:e=>f(e)};export function evaluate(e,t){switch(e.k){case"num":return e.value;case"acc":return e.kind==="t"?t.value(e.test):e.kind==="testPass"?t.testPass(e.test):t.specPass(e.test);case"diePass":return t.diePass();case"vec":return;case"unary":{const n=evaluate(e.arg,t);return n===void 0?void 0:e.op==="-"?s(-n):!n}case"binary":{const n=evaluate(e.left,t);if(n===void 0)return;const r=evaluate(e.right,t);if(r===void 0)return;switch(e.op){case"+":return s(n+r);case"-":return s(n-r);case"*":return s(n*r);case"/":return s(n/r);case"%":return s(n%r);case"^":return s(Math.pow(n,r));case"<":return n<r;case"<=":return n<=r;case">":return n>r;case">=":return n>=r;case"==":return n===r;case"!=":return n!==r;case"and":return n&&r;case"or":return n||r}return}case"call":{if(e.name==="if"){const u=evaluate(e.args[0],t);return u===void 0?void 0:evaluate(e.args[u?1:2],t)}const n=e.args[0];if(e.args.length===1&&n!==void 0&&n.k==="vec")return o(e.name,l(n,t));const r=d[e.name];if(r===void 0)return;const a=[];for(const u of e.args){const i=evaluate(u,t);if(i===void 0)return;a.push(i)}return s(r(a))}}}
1
+ import{minOf as c,maxOf as f}from"../../core/utils.js";function s(e){return Number.isFinite(e)?e:void 0}function l(e,t){const n=r=>e.kind==="t"?t.value(r):e.kind==="testPass"?t.testPass(r):t.specPass(r);return e.tests.map(n)}function d(e,t){const n=t.filter(r=>r!==void 0);if(e==="countKnown")return n.length;if(n.length!==0)switch(e){case"all":return n.every(Boolean);case"any":return n.some(Boolean);case"none":return!n.some(Boolean);case"countTrue":return n.filter(Boolean).length;case"countFalse":return n.filter(r=>!r).length;case"min":return c(n);case"max":return f(n);case"sum":return s(n.reduce((r,a)=>r+a,0));case"mean":return s(n.reduce((r,a)=>r+a,0)/n.length);default:return}}const o={abs:e=>Math.abs(e[0]),sqrt:e=>Math.sqrt(e[0]),ln:e=>Math.log(e[0]),log10:e=>Math.log10(e[0]),exp:e=>Math.exp(e[0]),floor:e=>Math.floor(e[0]),ceil:e=>Math.ceil(e[0]),round:e=>Math.round(e[0]),sign:e=>Math.sign(e[0]),pow:e=>Math.pow(e[0],e[1]),min:e=>c(e),max:e=>f(e)};export function evaluate(e,t){switch(e.k){case"num":return e.value;case"acc":return e.kind==="t"?t.value(e.test):e.kind==="testPass"?t.testPass(e.test):t.specPass(e.test);case"diePass":return t.diePass();case"dieField":return t.field(e.field);case"vec":return;case"unary":{const n=evaluate(e.arg,t);return n===void 0?void 0:e.op==="-"?s(-n):!n}case"binary":{const n=evaluate(e.left,t);if(n===void 0)return;const r=evaluate(e.right,t);if(r===void 0)return;switch(e.op){case"+":return s(n+r);case"-":return s(n-r);case"*":return s(n*r);case"/":return s(n/r);case"%":return s(n%r);case"^":return s(Math.pow(n,r));case"<":return n<r;case"<=":return n<=r;case">":return n>r;case">=":return n>=r;case"==":return n===r;case"!=":return n!==r;case"and":return n&&r;case"or":return n||r}return}case"call":{if(e.name==="if"){const u=evaluate(e.args[0],t);return u===void 0?void 0:evaluate(e.args[u?1:2],t)}const n=e.args[0];if(e.args.length===1&&n!==void 0&&n.k==="vec")return d(e.name,l(n,t));const r=o[e.name];if(r===void 0)return;const a=[];for(const u of e.args){const i=evaluate(u,t);if(i===void 0)return;a.push(i)}return s(r(a))}}}
@@ -41,6 +41,10 @@ export type ExprType = 'number' | 'boolean' | 'numberVec' | 'boolVec';
41
41
  * vocabulary exactly: `'test'` is the tester's recorded verdict, `'spec'` is the
42
42
  * spec-limit judgement. `t` is the measured value itself. */
43
43
  export type AccessorKind = 't' | 'testPass' | 'specPass';
44
+ /** A die's own recorded fields an expression may read: where it is, which bins it landed in, which probe site. */
45
+ export type DieField = 'x' | 'y' | 'hbin' | 'sbin' | 'site';
46
+ /** The call each die field is read with. Call syntax, like `diePass()`, so a name here is never mistaken for a constant. */
47
+ export declare const DIE_FIELD_CALLS: Readonly<Record<string, DieField>>;
44
48
  export type ExprNode = {
45
49
  k: 'num';
46
50
  value: number;
@@ -54,6 +58,9 @@ export type ExprNode = {
54
58
  tests: number[];
55
59
  } | {
56
60
  k: 'diePass';
61
+ } | {
62
+ k: 'dieField';
63
+ field: DieField;
57
64
  } | {
58
65
  k: 'unary';
59
66
  op: '-' | 'not';
@@ -1,2 +1,2 @@
1
- import{isParametricTest as c}from"../buildWaferMap.js";import{hasSpecLimits as l}from"../spec.js";export const FUNCTIONS={abs:[{arity:1,returns:"number"}],sqrt:[{arity:1,returns:"number"}],ln:[{arity:1,returns:"number"}],log10:[{arity:1,returns:"number"}],exp:[{arity:1,returns:"number"}],floor:[{arity:1,returns:"number"}],ceil:[{arity:1,returns:"number"}],round:[{arity:1,returns:"number"}],sign:[{arity:1,returns:"number"}],pow:[{arity:2,returns:"number"}],min:[{vecOf:"numberVec",returns:"number"},{variadic:!0,returns:"number"}],max:[{vecOf:"numberVec",returns:"number"},{variadic:!0,returns:"number"}],if:[{arity:3,returns:"number"}],all:[{vecOf:"boolVec",returns:"boolean"}],any:[{vecOf:"boolVec",returns:"boolean"}],none:[{vecOf:"boolVec",returns:"boolean"}],countTrue:[{vecOf:"boolVec",returns:"number"}],countFalse:[{vecOf:"boolVec",returns:"number"}],mean:[{vecOf:"numberVec",returns:"number"}],sum:[{vecOf:"numberVec",returns:"number"}],countKnown:[{vecOf:"any",returns:"number"}]};const d=["t","testPass","specPass"],m=["<=",">=","==","!=","..","+","-","*","/","%","^","<",">"],b=["(",")","[","]",","];class o extends Error{position;constructor(t,e){super(t),this.position=e}}function h(r){const t=[];let e=0;for(;e<r.length;){const n=r[e];if(n===" "||n===" "||n===`
2
- `||n==="\r"){e++;continue}if(n>="0"&&n<="9"){const s=e;for(;e<r.length&&r[e]>="0"&&r[e]<="9";)e++;if(r[e]==="."&&r[e+1]!==".")for(e++;e<r.length&&r[e]>="0"&&r[e]<="9";)e++;if(r[e]==="e"||r[e]==="E"){const a=e;if(e++,(r[e]==="+"||r[e]==="-")&&e++,r[e]>="0"&&r[e]<="9")for(;e<r.length&&r[e]>="0"&&r[e]<="9";)e++;else e=a}const u=r.slice(s,e);t.push({kind:"num",text:u,pos:s,value:Number(u)});continue}if(/[A-Za-z_]/.test(n)){const s=e;for(;e<r.length&&/[A-Za-z0-9_]/.test(r[e]);)e++;t.push({kind:"ident",text:r.slice(s,e),pos:s});continue}const i=m.find(s=>r.startsWith(s,e));if(i){t.push({kind:"op",text:i,pos:e}),e+=i.length;continue}if(b.includes(n)){t.push({kind:"punc",text:n,pos:e}),e++;continue}throw new o(`Unexpected character ${JSON.stringify(n)} at position ${e}`,e)}return t.push({kind:"eof",text:"",pos:r.length}),t}class f{toks;ctx;p=0;reads=[];usesDiePass=!1;constructor(t,e){this.toks=t,this.ctx=e}peek(){return this.toks[this.p]}next(){return this.toks[this.p++]}at(t){const e=this.peek();return(e.kind==="op"||e.kind==="punc"||e.kind==="ident")&&e.text===t}eat(t){return this.at(t)?(this.p++,!0):!1}expect(t){if(!this.at(t)){const e=this.peek();throw new o(`Expected ${JSON.stringify(t)} but found ${e.kind==="eof"?"end of expression":JSON.stringify(e.text)} at position ${e.pos}`,e.pos)}return this.next()}parse(){const t=this.parseOr();return this.expectEnd(),t}parseTestRefOnly(){const t=this.parseTestRef(this.peek().pos);return this.expectEnd(),t}expectEnd(){const t=this.peek();if(t.kind!=="eof")throw new o(`Unexpected ${JSON.stringify(t.text)} at position ${t.pos}`,t.pos)}requireScalar(t,e,n){if(t.type==="numberVec"||t.type==="boolVec")throw new o(`${e} cannot be applied to a test range at position ${n} \u2014 a range must be reduced first, e.g. mean(t[1010..1015]) or all(testPass[1010..1015])`,n);return t.type}parseOr(){let t=this.parseAnd();for(;this.at("or");){const e=this.next().pos,n=this.parseAnd();this.requireBool(t,"or",e),this.requireBool(n,"or",e),t={node:{k:"binary",op:"or",left:t.node,right:n.node},type:"boolean"}}return t}parseAnd(){let t=this.parseNot();for(;this.at("and");){const e=this.next().pos,n=this.parseNot();this.requireBool(t,"and",e),this.requireBool(n,"and",e),t={node:{k:"binary",op:"and",left:t.node,right:n.node},type:"boolean"}}return t}requireBool(t,e,n){if(this.requireScalar(t,`Operator ${JSON.stringify(e)}`,n),t.type!=="boolean")throw new o(`Operator ${JSON.stringify(e)} needs a true/false operand at position ${n}, but got a number \u2014 compare it first, e.g. t[1020] > 5`,n)}parseNot(){if(this.at("not")){const t=this.next().pos,e=this.parseNot();return this.requireBool(e,"not",t),{node:{k:"unary",op:"not",arg:e.node},type:"boolean"}}return this.parseCompare()}parseCompare(){const t=this.parseAdd(),e=this.peek();if(e.kind==="op"&&["<","<=",">",">=","==","!="].includes(e.text)){this.next();const n=this.parseAdd(),i=this.requireScalar(t,`Operator ${JSON.stringify(e.text)}`,e.pos),s=this.requireScalar(n,`Operator ${JSON.stringify(e.text)}`,e.pos);if(i!==s)throw new o(`Cannot compare a ${i} with a ${s} at position ${e.pos}`,e.pos);if(i==="boolean"&&e.text!=="=="&&e.text!=="!=")throw new o(`Operator ${JSON.stringify(e.text)} cannot order true/false values at position ${e.pos}`,e.pos);return{node:{k:"binary",op:e.text,left:t.node,right:n.node},type:"boolean"}}return t}parseAdd(){let t=this.parseMul();for(;;){const e=this.peek();if(e.kind!=="op"||e.text!=="+"&&e.text!=="-")return t;this.next();const n=this.parseMul();this.requireNum(t,e.text,e.pos),this.requireNum(n,e.text,e.pos),t={node:{k:"binary",op:e.text,left:t.node,right:n.node},type:"number"}}}parseMul(){let t=this.parsePow();for(;;){const e=this.peek();if(e.kind!=="op"||!["*","/","%"].includes(e.text))return t;this.next();const n=this.parsePow();this.requireNum(t,e.text,e.pos),this.requireNum(n,e.text,e.pos),t={node:{k:"binary",op:e.text,left:t.node,right:n.node},type:"number"}}}parsePow(){const t=this.parseUnary(),e=this.peek();if(e.kind==="op"&&e.text==="^"){this.next();const n=this.parsePow();return this.requireNum(t,"^",e.pos),this.requireNum(n,"^",e.pos),{node:{k:"binary",op:"^",left:t.node,right:n.node},type:"number"}}return t}requireNum(t,e,n){if(this.requireScalar(t,`Operator ${JSON.stringify(e)}`,n),t.type!=="number")throw new o(`Operator ${JSON.stringify(e)} needs a numeric operand at position ${n}, but got a true/false value`,n)}parseUnary(){const t=this.peek();if(t.kind==="op"&&t.text==="-"){this.next();const e=this.parseUnary();return this.requireNum(e,"-",t.pos),{node:{k:"unary",op:"-",arg:e.node},type:"number"}}return this.parsePrimary()}parsePrimary(){const t=this.next();if(t.kind==="num")return{node:{k:"num",value:t.value},type:"number"};if(t.kind==="punc"&&t.text==="("){const e=this.parseOr();return this.expect(")"),e}if(t.kind==="ident"){if(d.includes(t.text))return this.parseAccessor(t.text,t.pos);if(t.text==="diePass")return this.expect("("),this.expect(")"),this.usesDiePass=!0,{node:{k:"diePass"},type:"boolean"};if(this.at("("))return this.parseCall(t.text,t.pos);if(Object.prototype.hasOwnProperty.call(this.ctx.constants,t.text)){const e=this.ctx.constants[t.text];if(typeof e!="number"||!Number.isFinite(e))throw new o(`Constant ${JSON.stringify(t.text)} at position ${t.pos} is not a finite number`,t.pos);return{node:{k:"num",value:e},type:"number"}}throw new o(`Unknown name ${JSON.stringify(t.text)} at position ${t.pos}. Test values are read as t[1020], verdicts as testPass[1020] or specPass[1020]; other names must be declared in \`constants\`.`,t.pos)}throw new o(`Unexpected ${t.kind==="eof"?"end of expression":JSON.stringify(t.text)} at position ${t.pos}`,t.pos)}parseAccessor(t,e){this.expect("[");const{tests:n,range:i}=this.parseTestRef(e);this.expect("]");for(const u of n)this.checkAccessible(t,u,e);for(const u of n)this.reads.push({kind:t,test:u});const s=t==="t"?"number":"boolean";return i?{node:{k:"vec",kind:t,tests:n},type:s==="number"?"numberVec":"boolVec"}:{node:{k:"acc",kind:t,test:n[0]},type:s}}checkAccessible(t,e,n){const i=this.ctx.testDefs.get(e);if(i===void 0)throw new o(`Test ${e} at position ${n} is not declared in \`testDefs\``,n);if(t==="t"&&!c(i))throw new o(`t[${e}] at position ${n} reads a measured value, but test ${e} is functional (testType 'F') and has no measured value \u2014 use testPass[${e}] for its verdict`,n);if(t==="specPass"){if(!c(i))throw new o(`specPass[${e}] at position ${n} needs test limits, but test ${e} is functional (testType 'F') \u2014 use testPass[${e}] for its recorded verdict`,n);if(!l(i))throw new o(`specPass[${e}] at position ${n} needs \`limitLow\` or \`limitHigh\` on test ${e}, which declares neither`,n)}}parseTestRef(t){const e=this.expectInt();if(!this.eat(".."))return{tests:[e],range:!1};const n=this.expectInt();if(n<e)throw new o(`Test range ${e}..${n} at position ${t} runs backwards`,t);const i=[...this.ctx.testDefs.keys()].filter(s=>s>=e&&s<=n).sort((s,u)=>s-u);if(i.length===0)throw new o(`Test range ${e}..${n} at position ${t} matches no declared test`,t);return{tests:i,range:!0}}expectInt(){const t=this.peek();if(t.kind!=="num"||!Number.isInteger(t.value))throw new o(`Expected a test number at position ${t.pos}`,t.pos);return this.next(),t.value}parseCall(t,e){const n=FUNCTIONS[t];if(n===void 0)throw new o(`Unknown function ${JSON.stringify(t)} at position ${e}. Available: ${Object.keys(FUNCTIONS).sort().join(", ")}`,e);this.expect("(");const i=[];if(!this.at(")"))do i.push(this.parseOr());while(this.eat(","));this.expect(")");const s=i.map(a=>a.type),u={k:"call",name:t,args:i.map(a=>a.node)};for(const a of n){if(a.vecOf!==void 0){if(s.length!==1)continue;const p=s[0];if(!(p==="numberVec"||p==="boolVec")||a.vecOf!=="any"&&a.vecOf!==p)continue;return{node:u,type:a.returns}}if(a.variadic){if(s.length<2||!s.every(p=>p==="number"))continue;return{node:u,type:a.returns}}if(a.arity!==void 0){if(s.length!==a.arity)continue;if(t==="if"){if(s[0]!=="boolean"||s[1]!=="number"||s[2]!=="number")continue;return{node:u,type:"number"}}if(!s.every(p=>p==="number"))continue;return{node:u,type:a.returns}}}throw new o(`${t}(${s.join(", ")}) at position ${e} is not a valid call \u2014 ${y(t,n)}`,e)}}function y(r,t){return`expected ${t.map(n=>n.vecOf==="boolVec"?`${r}(<true/false test range>)`:n.vecOf==="numberVec"?`${r}(<value test range>)`:n.vecOf==="any"?`${r}(<test range>)`:n.variadic?`${r}(number, number, \u2026)`:r==="if"?"if(<true/false>, number, number)":`${r}(${Array.from({length:n.arity??0},()=>"number").join(", ")})`).join(" or ")}`}export function parseExpression(r,t){try{if(r.length>MAX_EXPRESSION_LENGTH)return{ok:!1,message:`Expression is ${r.length} characters, over the ${MAX_EXPRESSION_LENGTH} limit`,position:MAX_EXPRESSION_LENGTH};const e=new f(h(r),t),{node:n,type:i}=e.parse();return i==="numberVec"||i==="boolVec"?{ok:!1,message:"Expression results in a test range, not a single value \u2014 reduce it, e.g. mean(t[1010..1015]) or all(testPass[1010..1015])",position:0}:{ok:!0,ast:n,type:i,reads:e.reads,usesDiePass:e.usesDiePass}}catch(e){if(e instanceof o)return{ok:!1,message:e.message,position:e.position};throw e}}export function parseTestReference(r,t){try{if(r.length>MAX_EXPRESSION_LENGTH)return{ok:!1,message:`Test reference is ${r.length} characters, over the ${MAX_EXPRESSION_LENGTH} limit`,position:MAX_EXPRESSION_LENGTH};const{tests:e,range:n}=new f(h(r),{testDefs:t,constants:{}}).parseTestRefOnly();return{ok:!0,tests:e,range:n}}catch(e){if(e instanceof o)return{ok:!1,message:e.message,position:e.position};throw e}}export const MAX_EXPRESSION_LENGTH=2e3;
1
+ import{isParametricTest as c}from"../buildWaferMap.js";import{hasSpecLimits as l}from"../spec.js";export const DIE_FIELD_CALLS={dieX:"x",dieY:"y",hbin:"hbin",sbin:"sbin",site:"site"},FUNCTIONS={abs:[{arity:1,returns:"number"}],sqrt:[{arity:1,returns:"number"}],ln:[{arity:1,returns:"number"}],log10:[{arity:1,returns:"number"}],exp:[{arity:1,returns:"number"}],floor:[{arity:1,returns:"number"}],ceil:[{arity:1,returns:"number"}],round:[{arity:1,returns:"number"}],sign:[{arity:1,returns:"number"}],pow:[{arity:2,returns:"number"}],min:[{vecOf:"numberVec",returns:"number"},{variadic:!0,returns:"number"}],max:[{vecOf:"numberVec",returns:"number"},{variadic:!0,returns:"number"}],if:[{arity:3,returns:"number"}],all:[{vecOf:"boolVec",returns:"boolean"}],any:[{vecOf:"boolVec",returns:"boolean"}],none:[{vecOf:"boolVec",returns:"boolean"}],countTrue:[{vecOf:"boolVec",returns:"number"}],countFalse:[{vecOf:"boolVec",returns:"number"}],mean:[{vecOf:"numberVec",returns:"number"}],sum:[{vecOf:"numberVec",returns:"number"}],countKnown:[{vecOf:"any",returns:"number"}]};const d=["t","testPass","specPass"],b=["<=",">=","==","!=","..","+","-","*","/","%","^","<",">"],m=["(",")","[","]",","];class o extends Error{position;constructor(t,e){super(t),this.position=e}}function h(r){const t=[];let e=0;for(;e<r.length;){const n=r[e];if(n===" "||n===" "||n===`
2
+ `||n==="\r"){e++;continue}if(n>="0"&&n<="9"){const s=e;for(;e<r.length&&r[e]>="0"&&r[e]<="9";)e++;if(r[e]==="."&&r[e+1]!==".")for(e++;e<r.length&&r[e]>="0"&&r[e]<="9";)e++;if(r[e]==="e"||r[e]==="E"){const a=e;if(e++,(r[e]==="+"||r[e]==="-")&&e++,r[e]>="0"&&r[e]<="9")for(;e<r.length&&r[e]>="0"&&r[e]<="9";)e++;else e=a}const u=r.slice(s,e);t.push({kind:"num",text:u,pos:s,value:Number(u)});continue}if(/[A-Za-z_]/.test(n)){const s=e;for(;e<r.length&&/[A-Za-z0-9_]/.test(r[e]);)e++;t.push({kind:"ident",text:r.slice(s,e),pos:s});continue}const i=b.find(s=>r.startsWith(s,e));if(i){t.push({kind:"op",text:i,pos:e}),e+=i.length;continue}if(m.includes(n)){t.push({kind:"punc",text:n,pos:e}),e++;continue}throw new o(`Unexpected character ${JSON.stringify(n)} at position ${e}`,e)}return t.push({kind:"eof",text:"",pos:r.length}),t}class f{toks;ctx;p=0;reads=[];usesDiePass=!1;constructor(t,e){this.toks=t,this.ctx=e}peek(){return this.toks[this.p]}next(){return this.toks[this.p++]}at(t){const e=this.peek();return(e.kind==="op"||e.kind==="punc"||e.kind==="ident")&&e.text===t}eat(t){return this.at(t)?(this.p++,!0):!1}expect(t){if(!this.at(t)){const e=this.peek();throw new o(`Expected ${JSON.stringify(t)} but found ${e.kind==="eof"?"end of expression":JSON.stringify(e.text)} at position ${e.pos}`,e.pos)}return this.next()}parse(){const t=this.parseOr();return this.expectEnd(),t}parseTestRefOnly(){const t=this.parseTestRef(this.peek().pos);return this.expectEnd(),t}expectEnd(){const t=this.peek();if(t.kind!=="eof")throw new o(`Unexpected ${JSON.stringify(t.text)} at position ${t.pos}`,t.pos)}requireScalar(t,e,n){if(t.type==="numberVec"||t.type==="boolVec")throw new o(`${e} cannot be applied to a test range at position ${n} \u2014 a range must be reduced first, e.g. mean(t[1010..1015]) or all(testPass[1010..1015])`,n);return t.type}parseOr(){let t=this.parseAnd();for(;this.at("or");){const e=this.next().pos,n=this.parseAnd();this.requireBool(t,"or",e),this.requireBool(n,"or",e),t={node:{k:"binary",op:"or",left:t.node,right:n.node},type:"boolean"}}return t}parseAnd(){let t=this.parseNot();for(;this.at("and");){const e=this.next().pos,n=this.parseNot();this.requireBool(t,"and",e),this.requireBool(n,"and",e),t={node:{k:"binary",op:"and",left:t.node,right:n.node},type:"boolean"}}return t}requireBool(t,e,n){if(this.requireScalar(t,`Operator ${JSON.stringify(e)}`,n),t.type!=="boolean")throw new o(`Operator ${JSON.stringify(e)} needs a true/false operand at position ${n}, but got a number \u2014 compare it first, e.g. t[1020] > 5`,n)}parseNot(){if(this.at("not")){const t=this.next().pos,e=this.parseNot();return this.requireBool(e,"not",t),{node:{k:"unary",op:"not",arg:e.node},type:"boolean"}}return this.parseCompare()}parseCompare(){const t=this.parseAdd(),e=this.peek();if(e.kind==="op"&&["<","<=",">",">=","==","!="].includes(e.text)){this.next();const n=this.parseAdd(),i=this.requireScalar(t,`Operator ${JSON.stringify(e.text)}`,e.pos),s=this.requireScalar(n,`Operator ${JSON.stringify(e.text)}`,e.pos);if(i!==s)throw new o(`Cannot compare a ${i} with a ${s} at position ${e.pos}`,e.pos);if(i==="boolean"&&e.text!=="=="&&e.text!=="!=")throw new o(`Operator ${JSON.stringify(e.text)} cannot order true/false values at position ${e.pos}`,e.pos);return{node:{k:"binary",op:e.text,left:t.node,right:n.node},type:"boolean"}}return t}parseAdd(){let t=this.parseMul();for(;;){const e=this.peek();if(e.kind!=="op"||e.text!=="+"&&e.text!=="-")return t;this.next();const n=this.parseMul();this.requireNum(t,e.text,e.pos),this.requireNum(n,e.text,e.pos),t={node:{k:"binary",op:e.text,left:t.node,right:n.node},type:"number"}}}parseMul(){let t=this.parsePow();for(;;){const e=this.peek();if(e.kind!=="op"||!["*","/","%"].includes(e.text))return t;this.next();const n=this.parsePow();this.requireNum(t,e.text,e.pos),this.requireNum(n,e.text,e.pos),t={node:{k:"binary",op:e.text,left:t.node,right:n.node},type:"number"}}}parsePow(){const t=this.parseUnary(),e=this.peek();if(e.kind==="op"&&e.text==="^"){this.next();const n=this.parsePow();return this.requireNum(t,"^",e.pos),this.requireNum(n,"^",e.pos),{node:{k:"binary",op:"^",left:t.node,right:n.node},type:"number"}}return t}requireNum(t,e,n){if(this.requireScalar(t,`Operator ${JSON.stringify(e)}`,n),t.type!=="number")throw new o(`Operator ${JSON.stringify(e)} needs a numeric operand at position ${n}, but got a true/false value`,n)}parseUnary(){const t=this.peek();if(t.kind==="op"&&t.text==="-"){this.next();const e=this.parseUnary();return this.requireNum(e,"-",t.pos),{node:{k:"unary",op:"-",arg:e.node},type:"number"}}return this.parsePrimary()}parsePrimary(){const t=this.next();if(t.kind==="num")return{node:{k:"num",value:t.value},type:"number"};if(t.kind==="punc"&&t.text==="("){const e=this.parseOr();return this.expect(")"),e}if(t.kind==="ident"){if(d.includes(t.text))return this.parseAccessor(t.text,t.pos);if(t.text==="diePass")return this.expect("("),this.expect(")"),this.usesDiePass=!0,{node:{k:"diePass"},type:"boolean"};if(Object.prototype.hasOwnProperty.call(DIE_FIELD_CALLS,t.text)){if(!this.at("("))throw new o(`${JSON.stringify(t.text)} at position ${t.pos} reads a die's own field and is written with parentheses: ${t.text}().`,t.pos);return this.expect("("),this.expect(")"),{node:{k:"dieField",field:DIE_FIELD_CALLS[t.text]},type:"number"}}if(this.at("("))return this.parseCall(t.text,t.pos);if(Object.prototype.hasOwnProperty.call(this.ctx.constants,t.text)){const e=this.ctx.constants[t.text];if(typeof e!="number"||!Number.isFinite(e))throw new o(`Constant ${JSON.stringify(t.text)} at position ${t.pos} is not a finite number`,t.pos);return{node:{k:"num",value:e},type:"number"}}throw new o(`Unknown name ${JSON.stringify(t.text)} at position ${t.pos}. Test values are read as t[1020], verdicts as testPass[1020] or specPass[1020], a die's own fields as dieX(), dieY(), hbin(), sbin() or site(); other names must be declared in \`constants\`.`,t.pos)}throw new o(`Unexpected ${t.kind==="eof"?"end of expression":JSON.stringify(t.text)} at position ${t.pos}`,t.pos)}parseAccessor(t,e){this.expect("[");const{tests:n,range:i}=this.parseTestRef(e);this.expect("]");for(const u of n)this.checkAccessible(t,u,e);for(const u of n)this.reads.push({kind:t,test:u});const s=t==="t"?"number":"boolean";return i?{node:{k:"vec",kind:t,tests:n},type:s==="number"?"numberVec":"boolVec"}:{node:{k:"acc",kind:t,test:n[0]},type:s}}checkAccessible(t,e,n){const i=this.ctx.testDefs.get(e);if(i===void 0)throw new o(`Test ${e} at position ${n} is not declared in \`testDefs\``,n);if(t==="t"&&!c(i))throw new o(`t[${e}] at position ${n} reads a measured value, but test ${e} is functional (testType 'F') and has no measured value \u2014 use testPass[${e}] for its verdict`,n);if(t==="specPass"){if(!c(i))throw new o(`specPass[${e}] at position ${n} needs test limits, but test ${e} is functional (testType 'F') \u2014 use testPass[${e}] for its recorded verdict`,n);if(!l(i))throw new o(`specPass[${e}] at position ${n} needs \`limitLow\` or \`limitHigh\` on test ${e}, which declares neither`,n)}}parseTestRef(t){const e=this.expectInt();if(!this.eat(".."))return{tests:[e],range:!1};const n=this.expectInt();if(n<e)throw new o(`Test range ${e}..${n} at position ${t} runs backwards`,t);const i=[...this.ctx.testDefs.keys()].filter(s=>s>=e&&s<=n).sort((s,u)=>s-u);if(i.length===0)throw new o(`Test range ${e}..${n} at position ${t} matches no declared test`,t);return{tests:i,range:!0}}expectInt(){const t=this.peek();if(t.kind!=="num"||!Number.isInteger(t.value))throw new o(`Expected a test number at position ${t.pos}`,t.pos);return this.next(),t.value}parseCall(t,e){const n=FUNCTIONS[t];if(n===void 0)throw new o(`Unknown function ${JSON.stringify(t)} at position ${e}. Available: ${Object.keys(FUNCTIONS).sort().join(", ")}`,e);this.expect("(");const i=[];if(!this.at(")"))do i.push(this.parseOr());while(this.eat(","));this.expect(")");const s=i.map(a=>a.type),u={k:"call",name:t,args:i.map(a=>a.node)};for(const a of n){if(a.vecOf!==void 0){if(s.length!==1)continue;const p=s[0];if(!(p==="numberVec"||p==="boolVec")||a.vecOf!=="any"&&a.vecOf!==p)continue;return{node:u,type:a.returns}}if(a.variadic){if(s.length<2||!s.every(p=>p==="number"))continue;return{node:u,type:a.returns}}if(a.arity!==void 0){if(s.length!==a.arity)continue;if(t==="if"){if(s[0]!=="boolean"||s[1]!=="number"||s[2]!=="number")continue;return{node:u,type:"number"}}if(!s.every(p=>p==="number"))continue;return{node:u,type:a.returns}}}throw new o(`${t}(${s.join(", ")}) at position ${e} is not a valid call \u2014 ${x(t,n)}`,e)}}function x(r,t){return`expected ${t.map(n=>n.vecOf==="boolVec"?`${r}(<true/false test range>)`:n.vecOf==="numberVec"?`${r}(<value test range>)`:n.vecOf==="any"?`${r}(<test range>)`:n.variadic?`${r}(number, number, \u2026)`:r==="if"?"if(<true/false>, number, number)":`${r}(${Array.from({length:n.arity??0},()=>"number").join(", ")})`).join(" or ")}`}export function parseExpression(r,t){try{if(r.length>MAX_EXPRESSION_LENGTH)return{ok:!1,message:`Expression is ${r.length} characters, over the ${MAX_EXPRESSION_LENGTH} limit`,position:MAX_EXPRESSION_LENGTH};const e=new f(h(r),t),{node:n,type:i}=e.parse();return i==="numberVec"||i==="boolVec"?{ok:!1,message:"Expression results in a test range, not a single value \u2014 reduce it, e.g. mean(t[1010..1015]) or all(testPass[1010..1015])",position:0}:{ok:!0,ast:n,type:i,reads:e.reads,usesDiePass:e.usesDiePass}}catch(e){if(e instanceof o)return{ok:!1,message:e.message,position:e.position};throw e}}export function parseTestReference(r,t){try{if(r.length>MAX_EXPRESSION_LENGTH)return{ok:!1,message:`Test reference is ${r.length} characters, over the ${MAX_EXPRESSION_LENGTH} limit`,position:MAX_EXPRESSION_LENGTH};const{tests:e,range:n}=new f(h(r),{testDefs:t,constants:{}}).parseTestRefOnly();return{ok:!0,tests:e,range:n}}catch(e){if(e instanceof o)return{ok:!1,message:e.message,position:e.position};throw e}}export const MAX_EXPRESSION_LENGTH=2e3;
@@ -1 +1 @@
1
- import{analyzeWaferMap as H,candidatesOf as U,describeRegional as Q,resolveOptions as se,adjustPValues as ae,twoProportionZ as X,zPValue as W,welchOfSums as Z,rateRelativeEffect as re,passesRateGate as oe,severityForFinding as J,severityForScore as ee,collapseRedundantFindings as ce,findContiguousRuns as le,mergedRegionLabel as fe}from"./analyzeWaferMap.js";import{normalizeInput as de}from"./normalizeInput.js";import{poolCapability as ue,poolRegionYield as me,poolPassRates as ge}from"./summaryFigures.js";import{mergeTestDefs as pe}from"./mergeTestDefs.js";import{findingPatternKey as he}from"./filterFindings.js";import{median as te}from"../core/utils.js";import{robustFence as ne}from"./math.js";import{findLotPattern as ye}from"./lotPattern.js";import{buildDriftFindings as be}from"./lotDrift.js";import{claimForPattern as we,weakestMultiplier as ve}from"./analyzeWaferMap.js";import{PATTERN_LABELS as Se}from"./patternClassification.js";import{describeWaferPopulation as ze,populationStat as Ie}from"./population.js";const T=8,ke={3:[.97,.994],4:[.829,.926],5:[.71,.821],6:[.625,.74],7:[.568,.68]},Me=3;export function outlierWafers(i){const c=i.length;if(c<3)return null;const o=te([...i]),s=e=>Math.abs(e-o)>=Me;if(c>=T){const e=ne(i,1.5,T),f=ne(i,3,T);if(!e||!f)return null;const u=(e.hi-e.lo)/4,a=[];return i.forEach((d,t)=>{if(d>=e.lo&&d<=e.hi||!s(d))return;const r=d<f.lo||d>f.hi?"unusual":"notable";a.push({index:t,severity:r,statistic:(d-o)/u})}),{method:"tukey-fence",outliers:a}}const m=i.map((e,f)=>f).sort((e,f)=>i[e]-i[f]),p=i[m[c-1]]-i[m[0]];if(p===0)return null;const[n,l]=ke[c],g=[],h=(e,f)=>{const u=Math.abs(i[e]-i[f])/p;u>n&&s(i[e])&&g.push({index:e,severity:u>l?"unusual":"notable",statistic:u})};return h(m[0],m[1]),h(m[c-1],m[c-2]),{method:"dixon-q",outliers:g}}const A=2;function _(i,c){const o={info:0,notable:1,unusual:2};return o[i]>=o[c]?i:c}const Pe=new Set(["ring","quadrant","sector"]),Re=new Set(["ring","quadrant","sector","reticle-position","test-site"]),xe=new Set(["yield","hardBin","softBin","functionalTest","test"]);function $e(i){return Re.has(i.comparison.family)&&xe.has(i.variable.kind)}function Be(i,c){const o=i.map(n=>n.facts);if(!o.length||o.some(n=>!n))return{coincident:new Set,yieldSoftBin:void 0,passBins:[],sectorCount:c};const[s,...m]=o,p=m.every(n=>n.passBins.length===s.passBins.length&&n.passBins.every(l=>s.passBins.includes(l)));return{coincident:new Set([...s.coincident].filter(n=>m.every(l=>l.coincident.has(n)))),yieldSoftBin:m.every(n=>n.yieldSoftBin===s.yieldSoftBin)?s.yieldSoftBin:void 0,passBins:p?s.passBins:[],sectorCount:c}}function j(i,c){let o=0,s=0,m=0,p=0,n=0,l=0,g=0,h=0,e=0,f=!0,u=0;for(const{waferIndex:t,c:r}of i){const y=c(t,r),M=r.rate??r.mean,S=Math.sqrt(M.n+y.n);if(r.rate)o+=S*X(r.rate.hits,r.rate.n,y.hits,y.n),m+=r.rate.hits,p+=r.rate.n,n+=y.hits,l+=y.n;else{const P=Z(r.mean,y.n,y.sum,y.sq);o+=S*P.z,g+=r.mean.n*P.effectSize,h+=r.mean.n*P.delta,u+=r.mean.n,r.relativeDelta===void 0?f=!1:e+=r.mean.n*r.relativeDelta}s+=S*S}const a=s>0?o/Math.sqrt(s):0,d=i[0].c;if(d.rate){const t=n/l,r=m/p-t;return{z:a,delta:r,relativeDelta:t===0?void 0:r/t,size:re({hits:m,n:p,restHits:n,restN:l,passRate:d.rate.passRate})}}return{z:a,delta:h/u,relativeDelta:f?e/u:void 0,size:g/u}}function O(i,c,o,s){return i.rate?oe(c,o.delta,o.size,s):c<=s.significanceLevel&&Math.abs(o.size)>=s.minimumEffectSize}function De(i,c,o,s){const m=new Map;for(const{waferIndex:a,byKey:d}of i)for(const t of d.values())(m.get(t.key)??m.set(t.key,[]).get(t.key)).push({waferIndex:a,c:t});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},l=[];for(const[a,d]of m){if(d.length<A)continue;const t=j(d,n);if(t.z===0)continue;const r=d[0].c;l.push({key:a,entries:d,combined:t,finding:{id:`lot-region:${a}`,level:"lot",severity:"info",variable:{...r.variable,label:r.label},comparison:{...r.comparison},effect:{direction:t.z>0?"higher":"lower",absoluteDelta:t.delta,relativeDelta:t.relativeDelta,effectSize:r.rate?t.delta:t.size},stats:{method:"stouffer-z",pValue:W(t.z),sampleSizeLeft:0,sampleSizeRight:0},summary:"",highlight:{kind:"wafer",waferIndices:[]}}})}ae(l.map(a=>a.finding));const g=l.filter(a=>O(a.entries[0].c,a.finding.stats.adjustedPValue??1,a.combined,c)),h=(a,d)=>{const t=a.entries[0].c,r=d.entries[0].c;return t.source===r.source&&t.variable.kind===r.variable.kind&&t.variable.bin===r.variable.bin&&t.variable.index===r.variable.index&&t.region.family===r.region.family},e=[],f=new Map;for(const a of g){const d=a.finding.stats.pValue??1,t=g.filter(b=>b!==a&&h(a,b)&&b.finding.effect.direction!==a.finding.effect.direction&&(b.finding.stats.pValue??1)<d);if(t.length){const b=($,v)=>{const z=n($,v);for(const B of t){const I=p.get($)?.get(B.key);I&&(I.rate?(z.hits-=I.rate.hits,z.n-=I.rate.n):(z.n-=I.mean.n,z.sum-=I.mean.sum,z.sq-=I.mean.sq))}return z},k=a.entries.filter($=>b($.waferIndex,$.c).n>=c.minimumSampleSize);if(!k.length)continue;const x=j(k,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,c))continue}const r=Math.sign(a.combined.z),y=a.entries.filter(b=>Math.sign(b.c.delta)===r),M=i.length,S=a.entries[0].c,P=a.finding.stats.adjustedPValue??d,K=S.rate?J(P,a.combined.delta,a.combined.size):ee(P,a.combined.size),w=_(K,y.length/M>=.6?"unusual":"info"),N={};for(const b of y)N[b.waferIndex]=[...b.c.region.dieKeys];const E={...a.finding,severity:w,stats:{...a.finding.stats,sampleSizeLeft:y.length,sampleSizeRight:M-y.length},summary:`${Q(S,a.combined.delta,a.combined.relativeDelta)} \u2014 ${a.finding.effect.direction} on ${y.length}/${M} wafers, all wafers' data combined`,highlight:{kind:"wafer",waferIndices:y.map(b=>b.waferIndex),dieKeysByWafer:N}};e.push(E),f.set(E,a)}const u=Ee(f,p,i.length,c,s,n);return e.splice(0,e.length,...e.filter(a=>!u.replaced.has(a)),...u.findings),ce(e,o),e}function Ee(i,c,o,s,m,p){const n=new Map;for(const[h,e]of i){const f=e.entries[0].c;if(!Pe.has(f.region.family))continue;const u=[f.source,f.variable.kind,f.variable.bin??"",f.variable.index??"",f.region.family,h.effect.direction].join("|");(n.get(u)??n.set(u,[]).get(u)).push({finding:h,c:f,key:e.key})}const l=[],g=new Set;for(const h of n.values()){if(h.length<2)continue;const e=h[0].c.region.family;for(const f of le(h,e,s.sectorCount,u=>u.c.region.key)){if(f.length<2)continue;const u=Le(f,c,o,s,m,p);if(u){l.push(u);for(const a of f)g.add(a.finding)}}}return{findings:l,replaced:g}}function Le(i,c,o,s,m,p){const n=i[0].c,l=i[0].finding.effect.direction==="higher"?1:-1,g=fe(n.region.family,i.map(w=>w.c.region.key),m),h=[];for(const[w,N]of c){const E=i.map(v=>N.get(v.key));if(E.some(v=>!v))continue;const b=E,k=b[0];let x,L;if(k.rate){const v=b.reduce((R,D)=>R+D.rate.hits,0),z=b.reduce((R,D)=>R+D.rate.n,0),B=k.rate.hits+k.rate.restHits-v,I=k.rate.n+k.rate.restN-z;if(z<s.minimumSampleSize||I<s.minimumSampleSize)continue;x={...k,rate:{hits:v,n:z,restHits:B,restN:I,passRate:k.rate.passRate}},L=X(v,z,B,I)}else{const v=k.mean,z=b.reduce((q,F)=>q+F.mean.n,0),B=b.reduce((q,F)=>q+F.mean.sum,0),I=b.reduce((q,F)=>q+F.mean.sq,0),R=v.n+v.restN-z,D=v.sum+v.restSum-B,C=v.sq+v.restSq-I;if(z<s.minimumSampleSize||R<s.minimumSampleSize)continue;const V={n:z,sum:B,sq:I,restN:R,restSum:D,restSq:C,shift:v.shift},Y=Z(V,R,D,C),G=D/R+v.shift;x={...k,mean:V,relativeDelta:G!==0?Y.delta/Math.abs(G):void 0},L=Y.z}const $=[...new Set(b.flatMap(v=>[...v.region.dieKeys]))];h.push({waferIndex:w,c:x,z:L,dieKeys:$})}if(h.length<A)return;const e=j(h,p);if(e.z===0||Math.sign(e.z)!==l)return;const f=W(e.z),u=ve(i.map(w=>w.finding)),a=Math.min(1,f*u);if(!O(n,a,e,s))return;const d=h.filter(w=>Math.sign(w.z)===l&&W(w.z)<=s.significanceLevel);if(!d.length)return;const t=n.rate?J(a,e.delta,e.size):ee(a,e.size),r=_(t,d.length/o>=.6?"unusual":"info"),y={};for(const w of d)y[w.waferIndex]=w.dieKeys;const M=i.map(w=>w.c.region.key.slice(w.c.region.key.indexOf(":")+1)).join("-"),S={...n,comparison:{...n.comparison,left:g}},P=i[0].finding,K=P.effect.direction;return{...P,id:`lot-region:${i[0].key.split("|").slice(0,-1).join("|")}|${n.region.family}:${M}`,severity:r,comparison:{...P.comparison,left:g},effect:{direction:K,absoluteDelta:e.delta,relativeDelta:e.relativeDelta,effectSize:n.rate?e.delta:e.size},stats:{method:"stouffer-z",pValue:f,adjustedPValue:a,sampleSizeLeft:d.length,sampleSizeRight:o-d.length},summary:`${Q(S,e.delta,e.relativeDelta)} \u2014 ${K} on ${d.length}/${o} wafers, all wafers' data combined`,highlight:{kind:"wafer",waferIndices:d.map(w=>w.waferIndex),dieKeysByWafer:y},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 qe(i,c){const o=new Map,s=n=>{const l=n.variable.kind==="spatialPattern"?ie[n.comparison.left]:void 0;return l?`spatialPattern|${l}`:he(n)};for(const n of i){const l=new Set,g=new Map;for(const e of n.summary.findings)if(e.variable.kind==="spatialPattern")for(const f of e.relatedIds??[])g.set(f,s(e));const h=new Set(n.summary.findings.flatMap(e=>e.absorbedIds??[]));for(const e of n.summary.findings){if(h.has(e.id)||$e(e)||e.variable.kind==="spatialPattern"&&c?.carriers.has(n.waferIndex))continue;const f=s(e);if(l.has(f))continue;l.add(f);const u=o.get(f)??{finding:e,waferIndices:[],severity:e.severity,labels:new Map,dieKeysByWafer:{},explainedBy:new Map};u.waferIndices.push(n.waferIndex);const a=g.get(e.id);if(a&&u.explainedBy.set(a,(u.explainedBy.get(a)??0)+1),e.variable.kind==="spatialPattern"){u.labels.set(e.comparison.left,(u.labels.get(e.comparison.left)??0)+1);const d=e.highlight.dieKeys;d&&(u.dieKeysByWafer[n.waferIndex]=d)}u.severity=_(u.severity,e.severity),o.set(f,u)}}const m=[];for(const[n,l]of o){if(l.waferIndices.length<A)continue;const g=l.waferIndices.length/Math.max(1,i.length),h=g>=.6||l.severity==="unusual"?"unusual":"notable",e=l.finding;m.push({id:`lot-repeat:${n}`,level:"lot",severity:h,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:l.waferIndices.length,sampleSizeRight:i.length-l.waferIndices.length},summary:`${Ne(e,l.labels)} \u2014 seen on ${l.waferIndices.length}/${i.length} wafers (${Math.round(g*100)}%)`,highlight:{kind:"wafer",waferIndices:l.waferIndices,...l.labels.size?{dieKeysByWafer:l.dieKeysByWafer}:{}}})}const p=new Map(m.map(n=>[n.id,n]));for(const[n,l]of o){const g=p.get(`lot-repeat:${n}`);if(g)for(const[h,e]of l.explainedBy){const f=p.get(`lot-repeat:${h}`);!f||e!==l.waferIndices.length||(f.relatedIds??=[]).push(g.id)}}return m}function Fe(i,c){const{classification:o,carriers:s}=i,m=Se[o.pattern],p=s.size/Math.max(1,c),n={};for(const[l,g]of s)n[l]=g;return{id:"lot-repeat:spatialPattern|lot",level:"lot",severity:p>=.6||o.confidence==="high"?"unusual":"notable",variable:{kind:"spatialPattern",label:m},comparison:{family:"spatial-pattern",left:m,right:"Wafer"},effect:{direction:"different",effectSize:o.features.globalRdd},stats:{method:"wafer-finding-frequency",sampleSizeLeft:s.size,sampleSizeRight:c-s.size},summary:`Spatial pattern: ${m.toLowerCase()} \u2014 seen on ${s.size}/${c} wafers (${Math.round(p*100)}%)`,highlight:{kind:"wafer",waferIndices:[...s.keys()].sort((l,g)=>l-g),dieKeysByWafer:n}}}function Ke(i){const c=/^Rings? (\d+)(?:\s*[–-]\s*(\d+))?/.exec(i.comparison.left);if(!c)return[];const o=+c[1],s=c[2]?+c[2]:o;return Array.from({length:Math.max(0,s-o+1)},(m,p)=>o+p)}function Ne(i,c){if(!c.size)return i.summary;const o=p=>p.toLowerCase();if(c.size===1)return`Spatial pattern: ${o([...c.keys()][0])}`;const s=ie[i.comparison.left],m=[...c].sort((p,n)=>n[1]-p[1]).map(([p,n])=>`${o(p)} on ${n}`);return`Spatial pattern: ${s} (${m.join(", ")})`}function We(i,c){const o=Ie(c,"median"),s=i.map(g=>({waferIndex:g.waferIndex,yieldPercent:g.summary.stats.yieldPercent})).filter(g=>g.yieldPercent!==null),m=s.map(g=>g.yieldPercent),p=outlierWafers(m);if(!p)return[];const n=te(m),l=[];for(const{index:g,severity:h,statistic:e}of p.outliers){const f=s[g],u=f.yieldPercent-n;l.push({id:`inter-wafer:yield:${f.waferIndex}`,level:"inter-wafer",severity:h,variable:{kind:"yield",label:"Yield"},comparison:{family:"wafer",left:`Wafer ${f.waferIndex+1}`,right:o.charAt(0).toUpperCase()+o.slice(1)},effect:{direction:u>0?"higher":"lower",absoluteDelta:u/100,relativeDelta:n===0?void 0:u/n,effectSize:e},stats:{method:p.method,sampleSizeLeft:1,sampleSizeRight:s.length-1},summary:`Wafer ${f.waferIndex+1} yield is ${Math.abs(u).toFixed(1)} percentage points ${u>0?"higher":"lower"} than the ${o}`,highlight:{kind:"wafer",waferIndices:[f.waferIndex]}})}return l}export function analyzeWaferLot(i,c={}){const o=i.map(de),s=o.map((t,r)=>({waferIndex:r,summary:c.perWaferSummaries?.[r]??H(t,c)})),m=s.map(({waferIndex:t,summary:r})=>U(r)??U(H(o[t],c))),p=m.map((t,r)=>({waferIndex:r,byKey:new Map(t.candidates.map(y=>[y.key,y]))})),n=se(c).resolved,l=ye(o,n),g=l&&l.carriers.size>=A?l:null,h=[...De(p,n,Be(m,n.sectorCount),o[0]?.ringCount??n.ringCount),...qe(s,g),...We(s,ze(s.map(t=>t.summary.wafer))),...be(s,n.significanceLevel)];if(g){const t=Fe(g,s.length);t.relatedIds=we([g.classification.pattern],t.severity,h,Ke,n.ringCount),t.relatedIds.length||delete t.relatedIds,h.push(t)}h.sort((t,r)=>{const y=t.severity==="unusual"?2:t.severity==="notable"?1:0,M=r.severity==="unusual"?2:r.severity==="notable"?1:0;return y!==M?M-y:t.summary.localeCompare(r.summary,"en")});const e=s.map(t=>t.summary.wafer).filter(t=>!!t),f={},u=[];if(e.length>0){const t=new Set;for(const r of e)for(const y of Object.keys(r))t.add(y);t.delete("wafer"),t.delete("waferId");for(const r of t){const y=e.filter(S=>r in S).map(S=>S[r]);y.every(S=>S===y[0])?f[r]=y[0]:u.push(r)}}const a=s.map(({waferIndex:t,summary:r})=>({waferIndex:t,yieldPercent:r.stats.yieldPercent})),d=s.map(({waferIndex:t,summary:r})=>r.stats.perTestStats?.length?{waferIndex:t,tests:r.stats.perTestStats}:null).filter(t=>t!==null);return{level:"lot",hasNotableFindings:h.some(t=>t.severity!=="info")||s.some(t=>t.summary.hasNotableFindings),findings:h,lot:Object.keys(f).length>0?f:void 0,...u.length>0?{mixedIdentityFields:u}:{},stats:{waferCount:i.length,...Ae(o,s.map(t=>t.summary))},lotYieldSeries:a,perWafer:s,...d.length>0?{perWaferTestStats:d}:{}}}function Ae(i,c){const o={...ge(c)},s=ue(c,pe(i).defs);s&&(o.capability=s);const m=me(c,i.map(p=>p.ringCount));return m&&(o.regionYield=m),o}
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 +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 Y}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 _,QUADRANT_CYCLE as pe,regionAngleBins as rt}from"./regions.js";import{buildClusterFindings as ft}from"./clusterDetection.js";import{classifyPattern as ct,patternExplains as lt,patternFailVerdict as ut,PATTERN_LABELS as dt}from"./patternClassification.js";import{benjaminiHochberg as mt,fiveNumberSummary as pt,normalCdf as Ce}from"./math.js";import{mean as ae,clamp01 as Ve,maxOf as ht}from"../core/utils.js";import{classifySpec as re,isOutOfSpec as he}from"../renderer/spec.js";const gt={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(e){const i=Object.fromEntries(Object.entries(e).filter(([,f])=>f!==void 0)),s={...I,...i},n=[],t=[];for(const f of["significanceLevel","minimumEffectSize","minimumRelativeEffect"]){const{min:l,max:o}=gt[f],u=s[f];if(typeof u!="number"||!Number.isFinite(u)){t.push(`${f}=${String(u)} is not a finite number (using ${I[f]})`),s[f]=I[f];continue}const a=Math.min(o,Math.max(l,u));a!==u&&(t.push(`${f}=${u} is outside ${l}\u2013${o} (using ${a})`),s[f]=a)}if(Le.includes(s.sectorCount)||(t.push(`sectorCount=${s.sectorCount} is not one of ${Le.join(", ")} (using ${I.sectorCount})`),s.sectorCount=I.sectorCount),t.length){const f=`analyzeWaferMap: ${t.join("; ")}. The analysis ran with the corrected values.`;console.warn(`[wafermap] ${f}`),n.push({code:"analysis-option-corrected",message:f,severity:"warning"})}const c=["passBins","ringCount"].filter(f=>i[f]!==void 0);if(c.length){const f=`analyzeWaferMap: ${c.join(" and ")} ${c.length>1?"are":"is"} no longer an analysis option and was ignored. Set ${c.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 I={ringCount:4,passBins:[1],significanceLevel:.05,minimumEffectSize:.2,minimumRelativeEffect:1,minimumSampleSize:5,enableTestValueAnalysis:!1,computePerTestStats:!1,sectorCount:8,minimumClusterSize:5};function bt(e,i){const s={...e};return s.minimumClusterSize=Math.max(5,Math.round(i*.003)),s}function yt(e){return de(e)?e.hbin!==void 0||e.sbin!==void 0||et(e):!1}function St(e,i,s){if(!e||i)return;const n=(s??[]).filter(t=>Y(t)&&(t.limitLow!==void 0||t.limitHigh!==void 0));if(n.length!==0)return t=>{for(const c of n)if(he(re(j(t,c.testNumber),c)))return!0;return!1}}function wt(e,i,s){const n=new Set,t=new Set,c=new Set,r=new Map,f=new Map;for(const l of Pe(e))n.add(l);for(const l of e)l.hbin!==void 0&&t.add(l.hbin),l.sbin!==void 0&&c.add(l.sbin),de(l)&&(l.hbin!==void 0&&r.set(l.hbin,(r.get(l.hbin)??0)+1),l.sbin!==void 0&&f.set(l.sbin,(f.get(l.sbin)??0)+1));return{totalDies:e.length,analyzedDies:i,excludedDies:e.length-i,yieldPercent:s,testsConsidered:[...n].sort((l,o)=>l-o),hardBinsConsidered:[...t].sort((l,o)=>l-o),softBinsConsidered:[...c].sort((l,o)=>l-o),...r.size?{hardBinCounts:Object.fromEntries(r)}:{},...f.size?{softBinCounts:Object.fromEntries(f)}:{}}}function vt(e,i){if(!i?.length)return;const s=i.filter(t=>Y(t)&&(t.limitLow!==void 0||t.limitHigh!==void 0));if(!s.length)return;const n=[];for(const t of s){const c=t.testNumber;let r=0,f=0,l=0,o=0;for(const u of e){if(u.partial||u.edgeExcluded)continue;const a=re(j(u,c),t);a!==null&&(o++,a==="failLow"?f++:a==="failHigh"?l++:r++)}n.push({testNumber:c,label:t.name,passDies:r,failLowDies:f,failHighDies:l,totalDies:o,yieldPercent:o>0?r/o*100:null})}return n.length?n:void 0}export function computeFunctionalYield(e,i){if(!i?.length)return;const s=i.filter(t=>!Y(t));if(!s.length)return;const n=[];for(const t of s){const c=t.testNumber;let r=0,f=0;for(const o of e){if(o.partial||o.edgeExcluded)continue;const u=se(o,c,t);u!==void 0&&(u?r++:f++)}const l=r+f;n.push({testNumber:c,label:T(t,c),...oe(t),passDies:r,failDies:f,totalDies:l,passRatePercent:l>0?r/l*100:null})}return n.length?n:void 0}function $t(e,i,s,n){const t=[];for(const c of i){const r=[];for(const a of e){if(a.partial||a.edgeExcluded)continue;const h=j(a,c);h!==void 0&&Number.isFinite(h)&&r.push(h)}if(r.length<n)continue;const f=ae(r),l=Math.sqrt(ze(r,f)),o=pt(Float64Array.from(r)),u=s?.find(a=>a.testNumber===c)?.name??String(c);t.push({testNumber:c,label:u,count:r.length,min:o.min,max:o.max,mean:f,stddev:l,median:o.median,q1:o.q1,q3:o.q3})}return t.length?t:void 0}export function twoProportionZ(e,i,s,n){const t=(e+s)/(i+n),c=t*(1-t)*(1/i+1/n);return!Number.isFinite(c)||c<=0?0:(e/i-s/n)/Math.sqrt(c)}export function zPValue(e){return Ve(2*(1-Ce(Math.abs(e))))}function O(e,i,s,n){const t=twoProportionZ(e,i,s,n);return t===0?1:zPValue(t)}export function adjustPValues(e){const i=new Map;for(const s of e){const n=`${s.variable.kind}:${s.comparison.family}`,t=i.get(n)??[];t.push(s),i.set(n,t)}for(const s of i.values()){const n=s.filter(c=>c.stats.pValue!==void 0),t=mt(n.map(c=>c.stats.pValue));n.forEach((c,r)=>{c.stats.adjustedPValue=t[r]})}return e}export function rateRelativeEffect(e){const i=(e.passRate?e.n-e.hits:e.hits)/e.n,s=(e.passRate?e.restN-e.restHits:e.restHits)/e.restN;return s===0?i===0?0:1/0:Math.abs(i-s)/s}export function severityForFinding(e,i,s){const n=Math.abs(i),t=s;return e<=.01&&(n>=.3||t>=2.5)?"unusual":e<=.05&&(n>=.2||t>=1.5)?"notable":"info"}export function severityForScore(e,i){return e<=.01&&Math.abs(i)>=.5?"unusual":e<=.05&&Math.abs(i)>=.15?"notable":"info"}function fe(e){return e==="reticle-position"?"other reticle positions":e==="test-site"?"other test sites":"the rest of the map"}function Q(e){return e==="reticle-position"?"Other reticle positions":e==="test-site"?"Other test sites":"Rest of map"}function ge(e,i,s){const n=(Math.abs(i)*100).toFixed(1);return`${e} yield is ${n} percentage points ${i>0?"higher":"lower"} than ${fe(s)}`}function be(e,i){return i==="quadrant"&&!e.startsWith("Quadrant")?`quadrant ${e}`:e}function Ke(e){return/^(Rings|Sectors|Quadrants)\b/.test(e)?"have":"has"}function ye(e,i,s,n){const t=be(e,n),c=(Math.abs(s)*100).toFixed(1);return`${t} ${Ke(t)} ${i} occurrence ${c} percentage points ${s>0?"higher":"lower"} than ${fe(n)}`}function Se(e,i,s,n){const t=be(e,n),c=(Math.abs(s)*100).toFixed(1);return`${t} ${Ke(t)} ${i} pass rate ${c} percentage points ${s>0?"higher":"lower"} than ${fe(n)}`}function we(e,i,s,n,t,c){const r=be(e,t),f=fe(t),l=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}% ${l} than ${f}`}const o=c?` ${c}`:"";return`${r} mean ${i} is ${Math.abs(s).toPrecision(3)}${o} ${l} than ${f}`}function Ee(e,i,s){const n=i?.find(t=>t.bin===e);return n?.name?`${s} ${e} (${n.name})`:`${s} ${e}`}function zt(e,i){const s=i?.find(n=>n.testNumber===e);return{label:T(s,e),unit:s?.unit,...oe(s)}}const Oe=new WeakMap,Te=new WeakMap,qe=new WeakMap;function Z(e,i){const s=i.highlight.dieKeys;return s&&qe.set(s,e),i}let U=null,J;const He=new WeakMap;export function candidatesOf(e){return He.get(e)}function Ae(e,i,s,n){if(!U)return;const t=je(e);if(!t)return;const c=e.id.slice(0,e.id.indexOf(":")),r=c==="specLimit"?"limitFail":c,{kind:f,bin:l,index:o}=e.variable;U.push({key:[r,f,l??"",o??"",t.family,t.key].join("|"),source:r,variable:e.variable,label:e.variable.label,comparison:e.comparison,region:t,z:i,delta:e.effect.absoluteDelta??0,effectSize:e.effect.effectSize??0,relativeDelta:e.effect.relativeDelta,rate:s,mean:n})}export function describeRegional(e,i,s){const n=e.comparison.left,t=e.region.family;switch(e.source){case"yield":return ge(n,i,t);case"hardBin":case"softBin":return ye(n,e.label,i,t);case"functional":return Se(n,e.label.replace(/ pass rate$/,""),i,t);case"limitFail":return ve(n,e.label,i);case"test":return we(n,e.label,i,s,t,e.variable.unit)}}function ve(e,i,s){return`${e} limit fail rate for ${i} is ${(Math.abs(s)*100).toFixed(1)} pp ${s>0?"higher":"lower"} than the rest of the wafer`}const G=new WeakMap;function ce(e,i){return G.set(e,i),e}function je(e){const i=e.highlight.dieKeys;return i?qe.get(i):void 0}const Ie=new WeakMap;function W(e){let i=Ie.get(e);return i||Ie.set(e,i=e.map(me)),i}function kt(e){let i=Oe.get(e);return i||Oe.set(e,i=e.map(Ne)),i}function le(e,i){let s=Te.get(e);s||Te.set(e,s={members:new Set(e),byFamily:new WeakMap});const n=s.byFamily.get(i);if(n)return n;const{members:t}=s,c=new Map;for(const r of i)c.set(r.key,r.dies.filter(f=>t.has(f)));return s.byFamily.set(i,c),c}function ue(e,i){adjustPValues(e);for(const n of e){const t=G.get(n);Ae(n,twoProportionZ(t.hits,t.n,t.restHits,t.restN),t)}const s=e.filter(n=>passesRateGate(n.stats.adjustedPValue??n.stats.pValue??1,n.effect.absoluteDelta??0,rateRelativeEffect(G.get(n)),i));return s.filter(n=>!Dt(n,s,i)).map(n=>({...n,severity:severityForFinding(n.stats.adjustedPValue??n.stats.pValue??1,n.effect.absoluteDelta??0,rateRelativeEffect(G.get(n)))}))}export function passesRateGate(e,i,s,n){return e<=n.significanceLevel&&(Math.abs(i)>=n.minimumEffectSize||s>=n.minimumRelativeEffect)}export function claimForPattern(e,i,s,n,t){const c=[];for(const r of s){const f=r.comparison.family,l=f==="ring"?n(r):[];e.some(o=>lt(o,f,l,t))&&(c.push(r.id),i!=="info"&&(f==="ring"||f==="quadrant"||f==="sector")&&(r.severity="info"))}return c}function Dt(e,i,s){const n=G.get(e);if(!n)return!1;const t=e.stats.pValue??1;let{restHits:c,restN:r}=n;for(const u of We(e,i)){const a=G.get(u);a&&(c-=a.hits,r-=a.n)}if(r===n.restN)return!1;if(r<s.minimumSampleSize)return!0;const f=n.hits/n.n-c/r;if(Math.sign(f)!==Math.sign(e.effect.absoluteDelta??0))return!0;const l=t>0?(e.stats.adjustedPValue??t)/t:1,o=Math.min(1,O(n.hits,n.n,c,r)*l);return!passesRateGate(o,f,rateRelativeEffect({...n,restHits:c,restN:r}),s)}function We(e,i){const s=e.stats.pValue??1;return i.filter(n=>n!==e&&n.effect.direction!==e.effect.direction&&n.variable.kind===e.variable.kind&&n.variable.bin===e.variable.bin&&n.variable.index===e.variable.index&&n.comparison.family===e.comparison.family&&(n.stats.pValue??1)<s)}const $e=new WeakMap;export function welchOfSums(e,i,s,n){const t=(c,r,f)=>f>1?Math.max(0,c-r*r/f)/(f-1):0;return welchFromStats(e.n,e.sum/e.n,t(e.sq,e.sum,e.n),i,s/i,t(n,s,i))}function Rt(e,i,s){const n=$e.get(e);if(!n)return!1;let{restN:t,restSum:c,restSq:r}=n;for(const h of We(e,i)){const g=$e.get(h);g&&(t-=g.n,c-=g.sum,r-=g.sq)}if(t===n.restN)return!1;if(t<s.minimumSampleSize)return!0;const{pValue:f,effectSize:l,delta:o}=welchOfSums(n,t,c,r);if(Math.sign(o)!==Math.sign(e.effect.absoluteDelta??0))return!0;const u=e.stats.pValue??1,a=u>0?(e.stats.adjustedPValue??u)/u:1;return!(Math.min(1,f*a)<=s.significanceLevel&&Math.abs(l)>=s.minimumEffectSize)}function ee(e,i,s,n){const t=new Set(s),c=le(e,i),r=new Map,f=new Map;for(const[o,u]of c){let a=0,h=0;for(const g of u)g.hbin!==void 0&&(h++,t.has(g.hbin)&&a++);r.set(o,a),f.set(o,h)}const l=[];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);l.push(ce(Z(o,{id:`yield:${o.key}`,level:"wafer",severity:"info",variable:{kind:"yield",label:"Yield"},comparison:{family:o.family,left:o.label,right:Q(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:ge(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(l,n)}function E(e,i,s,n,t,c){const r=p=>s==="soft"?p.sbin:p.hbin,f=[...new Set(e.map(r).filter(p=>p!==void 0))].sort((p,d)=>p-d),l=le(e,i),o=new Map,u=new Map;for(const[p,d]of l){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=t==="hardBin"?"HBin":"SBin",g=s==="hard"?new Set(c.passBins):c.softPassBins??Me(e,c.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<c.minimumSampleSize||w<c.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(ce(Z(p,{id:`${t}:${S}:${p.key}`,level:"wafer",severity:"info",variable:{kind:t,bin:S,label:z},comparison:{family:p.family,left:p.label,right:Q(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:ye(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,c)}function te(e,i,s,n){const t=(s??[]).filter(u=>!Y(u));if(!t.length)return[];const c=t.map(u=>u.testNumber),r=le(e,i),f=new Map,l=new Map;for(const[u,a]of r){const h=new Uint32Array(t.length),g=new Uint32Array(t.length);for(const p of a)for(let d=0;d<t.length;d++){const y=se(p,c[d],t[d]);y!==void 0&&(g[d]++,y&&h[d]++)}f.set(u,h),l.set(u,g)}const o=[];for(const u of i){const a=f.get(u.key),h=l.get(u.key);for(let g=0;g<t.length;g++){let p=0,d=0;for(const[b,v]of l)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=c[g];o.push(ce(Z(u,{id:`functional:${F}:${u.key}`,level:"wafer",severity:"info",variable:{kind:"functionalTest",index:F,label:`${T(t[g],F)} pass rate`,...oe(t[g])},comparison:{family:u.family,left:u.label,right:Q(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:Se(u.label,T(t[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)}function ze(e,i){return e.length<2?0:e.reduce((s,n)=>s+(n-i)**2,0)/(e.length-1)}export function welchFromStats(e,i,s,n,t,c){const r=Math.sqrt(s/e+c/n),f=i-t;if(!Number.isFinite(r)||r===0)return{pValue:1,effectSize:0,delta:f,z:0};const l=f/r,o=Math.sqrt(Math.max(0,(s+c)/2)),u=o===0?f:f/o;return{pValue:Ve(2*(1-Ce(Math.abs(l)))),effectSize:u,delta:f,z:l}}function Mt(e,i){const s=ae(e),n=ae(i);return welchFromStats(e.length,s,ze(e,s),i.length,n,ze(i,n))}const Ye=250;function _e(e,i,s){const n=r=>r.filter(f=>Y(s?.find(l=>l.testNumber===f)));if(i)return{testNumbers:n(i.slice().sort((r,f)=>r-f))};const t=Pe(e,"values");if(t.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(t)}}function ne(e,i,s,n){const t=_e(e,n.testNumbers,s);if(t.warning)return{findings:[],warning:t.warning};const c=t.testNumbers,r=new Map;for(let d=0;d<i.length;d++)for(const y of W(i[d].dies))r.set(y,d);const f=i.length,l=[],o=[];for(const d of e){const y=r.get(me(d));y!==void 0&&(l.push(d),o.push(y))}const u=[],a=new Float64Array(f),h=new Float64Array(f),g=new Float64Array(f);for(const d of c){a.fill(0),h.fill(0),g.fill(0);let y=0,w=0,k=0,S;for(let $=0;$<l.length;$++){const N=l[$],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}=zt(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:Q(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:we(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};$e.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:c,findings:p.filter(d=>!Rt(d,p,n)).map(d=>({...d,severity:severityForScore(d.stats.adjustedPValue??d.stats.pValue??1,d.effect.effectSize??0)}))}}function Bt(e,i,s,n){if(!s?.length)return[];const t=s.filter(r=>Y(r)&&(r.limitLow!==void 0||r.limitHigh!==void 0));if(!t.length)return[];const c=[];for(const r of t){const f=r.testNumber;for(const l of i){const o=le(e,l),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++,he(re(S,r))&&w++)}a.set(p,{valid:y,fail:w}),h+=y,g+=w}for(const p of l){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(ce(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:Q(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:ve(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}))}c.push(...ue(u,n))}}return c}function ke(e,i){return e==="softBin"?i.softEligibleDies:e==="test"?i.testDies:i.eligibleDies}function Nt(e){return e.id.startsWith("specLimit:")}function ie(e){return e.highlight.regionKeys??[]}function Ft(e){const i=e.variable.bin??e.variable.index??"";return`${e.comparison.family}\0${Qe(e)}\0${e.variable.kind}\0${i}\0${e.effect.direction}`}function Pt(e,i){const s=_(e);return s.family==="ring"?s.ring??0:s.family==="sector"?xe(i).indexOf(s.sector??""):0}export function inQuadrantOrder(e){const i=new Set(e),s=pe.findIndex((t,c)=>i.has(t)&&!i.has(pe[(c+3)%4])),n=s<0?0:s;return Array.from({length:4},(t,c)=>pe[(n+c)%4]).filter(t=>i.has(t))}export function findContiguousRuns(e,i,s,n){if(i==="quadrant"){const l=new Map;for(const h of e){const g=_(n(h)).quadrant;g&&l.set(g,h)}const o=[...l.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=>l.get(d)))}return a}const t=l=>Pt(n(l),s),c=[...e].sort((l,o)=>t(l)-t(o)),r=[];let f=[];for(const l of c){if(f.length===0){f.push(l);continue}const o=t(f[f.length-1]);t(l)-o===1?f.push(l):(r.push(f),f=[l])}if(f.length&&r.push(f),i==="sector"&&r.length>1){const o=xe(s).length,u=t(r[0][0]),a=t(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(e,i,s){if(e==="ring"){const t=i.map(l=>_(l).ring).filter(l=>l!==void 0).sort((l,o)=>l-o),c=t[0],r=t[t.length-1];let f="";return c===r&&c===1&&s>1?f=" (core)":c===r&&c===s&&s>1&&(f=" (edge)"),c===r?`Ring ${c}${f}`:`Rings ${c}\u2013${r}`}if(e==="sector"){const t=i.map(c=>_(c).sector??"");return t.length===1?`Sector ${t[0]}`:`Sectors ${t[0]}\u2013${t[t.length-1]}`}const n=i.map(t=>_(t).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(e){return[...new Set(e)]}export function weakestMultiplier(e){return ht(e.map(i=>{const s=i.stats.pValue??1;return s>0?(i.stats.adjustedPValue??s)/s:1}))}function X(e,i){return Math.min(1,e*i)}function xt(e,i){const s=e[0],n=s.comparison.family,t=s.variable.kind,c=De(e.flatMap(ie));let r,f;const l=e.map(je);if(l.every(b=>b!==void 0)){const b=new Set;r=[];for(const M of l){const z=W(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=W(ke(s.variable.kind,i));f=M=>b.has(v[M])}else{r=De(e.flatMap(M=>M.highlight.dieKeys??[]));const b=new Set(r),v=kt(ke(s.variable.kind,i));f=M=>b.has(v[M])}const o=mergedRegionLabel(n,e.map(b=>ie(b)[0]??""),i.ringCount),u=ke(t,i),a=i.regionDies[n],h=W(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(e);let y,w,k,S,$;if(Nt(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&&he(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=X(P,d);k=severityForFinding(B,R,rateRelativeEffect({hits:z.fail,n:z.valid,restHits:D.fail,restN:D.valid,passRate:!1})),S=ve(o,T(v,b),R),$=`specLimit:${b}`}else if(t==="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}=Mt(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=X(D,d);k=severityForScore(B,C),S=we(o,s.variable.label,m,P,n,s.variable.unit),$=`test:${b}`}else if(t==="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=X(x,d);k=severityForFinding(V,B,rateRelativeEffect({hits:C,n:z,restHits:m,restN:D,passRate:!0})),S=ge(o,B,n),$="yield"}else if(t==="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=X(B,d);k=severityForFinding(x,P,rateRelativeEffect({hits:M,n:z,restHits:D,restN:C,passRate:!0})),S=Se(o,T(v,b),P,n),$=`functional:${b}`}else{const b=s.variable.bin,v=x=>t==="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=X(R,d);k=severityForFinding(P,m,rateRelativeEffect({hits:M,n:g.length,restHits:z,restN:p.length,passRate:!1}));const B=t==="softBin"?i.sbinDefs:i.hbinDefs;S=ye(o,Ee(b,B,t==="softBin"?"SBin":"HBin"),m,n),$=`${t}:${b}`}w={...w,adjustedPValue:X(w.pValue??1,d)};const N=De(c.map(b=>b.replace(`${n}:`,""))).join("-"),F=t==="hardBin"||t==="softBin"?{kind:"bin",bin:s.variable.bin,regionKeys:c,dieKeys:r}:{kind:"region",regionFamily:n,regionKeys:c,dieKeys:r};return{...s,id:`${$}:${n}:${N}`,severity:k,comparison:{family:n,left:o,right:Q(n)},effect:y,stats:w,summary:S,highlight:F,relatedIds:e.map(b=>b.id)}}function Ct(e,i){const s=new Set(["ring","quadrant","sector"]),n=[],t=new Map;for(const r of e){if(!s.has(r.comparison.family)){n.push(r);continue}const f=Ft(r),l=t.get(f)??[];l.push(r),t.set(f,l)}const c=[];for(const r of t.values()){if(r.length===1){c.push(r[0]);continue}const f=r[0].comparison.family;for(const l of findContiguousRuns(r,f,i.sectorCount,o=>ie(o)[0]??""))c.push(l.length===1?l[0]:xt(l,i))}return[...n,...c]}function Vt(e){const i=new Map,s=new Map;for(const t of e){const c=me(t);t.hbin!==void 0&&t.hbin!==null&&(i.get(t.hbin)??i.set(t.hbin,new Set).get(t.hbin)).add(c),t.sbin!==void 0&&t.sbin!==null&&(s.get(t.sbin)??s.set(t.sbin,new Set).get(t.sbin)).add(c)}const n=new Set;for(const[t,c]of i)for(const[r,f]of s){if(c.size!==f.size)continue;let l=!0;for(const o of c)if(!f.has(o)){l=!1;break}l&&n.add(`${t}:${r}`)}return n}function Lt(e,i){const s=new Set(i);let n;for(const t of e){const c=Be(t,s);if(c!==void 0&&c){if(t.sbin==null||n!==void 0&&t.sbin!==n)return;n=t.sbin}}if(n!==void 0){for(const t of e)if(t.sbin===n&&Be(t,s)!==!0)return;return n}}function Kt(e){return`${e.comparison.family}\0${e.comparison.left}`}export function redundancyFacts(e,i,s){return{coincident:Vt(e),yieldSoftBin:Lt(e,i),passBins:i,sectorCount:s}}const Et=3/5;function Qe(e){return/^(?:lot-region:)?([^:|]+)/.exec(e.id)?.[1]??e.id}function Ot(e){const i=ie(e);if(i.length)return i;const s=/(ring|sector|quadrant):([^:|]+)$/.exec(e.id);return s?s[2].split("-").map(n=>`${s[1]}:${n}`):[]}function Ue(e,i){const s=new Set;for(const n of Ot(e)){const t=rt(n,i);if(!t)return;for(const c of t)s.add(c)}return s.size?s:void 0}export function collapseRedundantFindings(e,i){const{coincident:s,yieldSoftBin:n,passBins:t}=i,c=(o,u)=>{o.absorbedIds=[...o.absorbedIds??[],u.id]},r=new Map;for(const o of e){const u=Kt(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;c(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"&&t.length===1&&a.variable.bin===t[0]||a.variable.kind==="softBin"&&a.variable.bin===n))){c(u,a),f.add(a.id);for(const g of a.absorbedIds??[])u.absorbedIds=[...u.absorbedIds??[],g]}}}const l=new Map;for(const o of e){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");(l.get(u)??l.set(u,[]).get(u)).push(o)}for(const o of l.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>=Et-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];c(p,d),f.add(d.id),p.absorbedIds=[...p.absorbedIds??[],...d.absorbedIds??[]]}}}export function analyzeWaferMap(e,i={}){const s=U,n=J,t=[];U=t,J=void 0;try{const c=Tt(e,i);return He.set(c,{candidates:t,facts:J}),c}finally{U=s,J=n}}function Tt(e,i){const{resolved:s,warnings:n}=resolveOptions(i),t=Ge(e),c={...s,passBins:t.passBins??I.passBins,ringCount:t.ringCount??I.ringCount},r=t.isLotStack,f=t.aggrMethod,l=!r||f==="mode"||f==="countBin"||f==="percent",o=t.dies.filter(m=>yt(m)),u=o.filter(Fe),a=bt(c,o.length);a.softPassBins=Me(o,a.passBins).soft;const h=t.dies.filter(m=>de(m)),g=h.filter(Fe),p=it(g,t.wafer,a.ringCount),d=tt(g,t.wafer,a.ringCount),y=nt(g,t.reticleConfig),w=ot(h,!1),k=st(g,t.wafer,a.sectorCount),S=[];l&&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)),l&&S.push(...E(o,p,"hard",t.hbinDefs,"hardBin",a),...E(o,d,"hard",t.hbinDefs,"hardBin",a),...E(o,y,"hard",t.hbinDefs,"hardBin",a),...E(o,w,"hard",t.hbinDefs,"hardBin",a),...E(o,k,"hard",t.hbinDefs,"hardBin",a));{const m=o.filter(R=>R.sbin!==void 0);S.push(...E(m,p,"soft",t.sbinDefs,"softBin",a),...E(m,d,"soft",t.sbinDefs,"softBin",a),...E(m,y,"soft",t.sbinDefs,"softBin",a),...E(m,w,"soft",t.sbinDefs,"softBin",a),...E(m,k,"soft",t.sbinDefs,"softBin",a))}const $=[...n];let N;if(a.enableTestValueAnalysis){const m=ne(o,p,t.testDefs,a),R=ne(o,d,t.testDefs,a),P=ne(o,y,t.testDefs,a),B=ne(o,w,t.testDefs,a),x=ne(o,k,t.testDefs,a);S.push(...m.findings,...R.findings,...P.findings,...B.findings,...x.findings),m.warning&&$.push(m.warning),N=m.activeTestNumbers,S.push(...Bt(o,[p,d,y,w,k],t.testDefs,a)),S.push(...te(o,p,t.testDefs,a),...te(o,d,t.testDefs,a),...te(o,y,t.testDefs,a),...te(o,w,t.testDefs,a),...te(o,k,t.testDefs,a))}{const m=St(r,l,t.testDefs);(!r||l||m!==void 0)&&S.push(...ft(u,t.wafer,{...a,isFailingDie:m}))}const F=Ct(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=>W(m.dies))),quadrant:new Set(d.flatMap(m=>W(m.dies))),sector:new Set(k.flatMap(m=>W(m.dies)))},hbinDefs:t.hbinDefs,sbinDefs:t.sbinDefs,testDefs:t.testDefs});S.length=0,S.push(...F);let b;if(l){const m=ct(u,t.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=>_(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=wt(t.dies,o.length,t.yield.yieldPercent);r&&(v.isLotStack=!0,f&&(v.aggregationMethod=f));const M=vt(t.dies,t.testDefs);M&&(v.testSpecYield=M);const z=computeFunctionalYield(t.dies,t.testDefs);if(z&&(v.functionalYield=z),b&&(v.spatialPattern=b),N===void 0&&a.computePerTestStats){const m=_e(o,a.testNumbers,t.testDefs);m.warning&&$.push(m.warning),N=m.testNumbers}if(N?.length){const m=$t(t.dies,N,t.testDefs,a.minimumSampleSize);m&&(v.perTestStats=m);const R=Xe([{dies:t.dies}],t.testDefs,N);R&&(v.capability=R)}Object.assign(v,Ze(t.dies,t.testDefs));const D=Je([{dies:t.dies,wafer:t.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),U&&(J=C),{level:"wafer",hasNotableFindings:S.some(m=>m.severity==="notable"||m.severity==="unusual"),findings:S,wafer:t.wafer.metadata??void 0,stats:v}}
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}}
@@ -65,5 +65,5 @@ export declare function buildBinClusterData(groups: {
65
65
  * `binPassSets(dies, passBins).soft`) — hard pass numbers applied to a soft
66
66
  * tally pin the wrong rows.
67
67
  */
68
- export declare function sortBinsForDisplay(entries: Iterable<[bin: number, count: number]>, passBins?: Iterable<number>): Array<[bin: number, count: number]>;
68
+ export declare function sortBinsForDisplay(entries: Iterable<[bin: number, count: number]>, passBins: Iterable<number>): Array<[bin: number, count: number]>;
69
69
  //# sourceMappingURL=binPareto.d.ts.map
@@ -1 +1 @@
1
- import{isYieldEligibleDie as p}from"../core/dies.js";export function buildBinParetoData(l,u){const s=new Map;let n=0;for(const o of l){const i=u==="hbin"?o.hardBinCounts:o.softBinCounts;if(i){for(const[a,t]of Object.entries(i)){const e=Number(a);n+=t,s.set(e,(s.get(e)??0)+t)}continue}for(const a of o.dies??[]){if(!p(a))continue;const t=u==="hbin"?a.hbin:a.sbin;t!==void 0&&(n++,s.set(t,(s.get(t)??0)+1))}}const c=Array.from(s.entries()).map(([o,i])=>({label:`Bin ${o}`,value:i,percent:n>0?i/n*100:0,itemCount:1,binCode:o}));return c.sort((o,i)=>i.value-o.value),c}export function buildBinClusterData(l,u){const s=l.map(t=>t.key),n=new Map,c=[];function o(t,e,f){let r=n.get(t);r||(r={total:0,counts:[]},n.set(t,r),c.push(t)),r.total+=f,r.counts[e]=(r.counts[e]??0)+f}l.forEach((t,e)=>{for(const f of t.items){const r=u==="hbin"?f.hardBinCounts:f.softBinCounts;if(r){for(const[d,b]of Object.entries(r))o(Number(d),e,b);continue}for(const d of f.dies??[]){if(!p(d))continue;const b=u==="hbin"?d.hbin:d.sbin;b!==void 0&&o(b,e,1)}}});const a=c.slice().sort((t,e)=>n.get(e).total-n.get(t).total).map(t=>{const e=n.get(t);return{binCode:t,label:`Bin ${t}`,total:e.total,counts:s.map((f,r)=>e.counts[r]??0)}});return{groups:s,bins:a}}export function sortBinsForDisplay(l,u=[1]){const s=new Set(u);return[...l].sort((n,c)=>{const o=s.has(n[0]),i=s.has(c[0]);return o!==i?o?-1:1:o&&i?n[0]-c[0]:c[1]-n[1]||n[0]-c[0]})}
1
+ import{isYieldEligibleDie as p}from"../core/dies.js";export function buildBinParetoData(l,u){const s=new Map;let n=0;for(const o of l){const i=u==="hbin"?o.hardBinCounts:o.softBinCounts;if(i){for(const[a,t]of Object.entries(i)){const e=Number(a);n+=t,s.set(e,(s.get(e)??0)+t)}continue}for(const a of o.dies??[]){if(!p(a))continue;const t=u==="hbin"?a.hbin:a.sbin;t!==void 0&&(n++,s.set(t,(s.get(t)??0)+1))}}const c=Array.from(s.entries()).map(([o,i])=>({label:`Bin ${o}`,value:i,percent:n>0?i/n*100:0,itemCount:1,binCode:o}));return c.sort((o,i)=>i.value-o.value),c}export function buildBinClusterData(l,u){const s=l.map(t=>t.key),n=new Map,c=[];function o(t,e,f){let r=n.get(t);r||(r={total:0,counts:[]},n.set(t,r),c.push(t)),r.total+=f,r.counts[e]=(r.counts[e]??0)+f}l.forEach((t,e)=>{for(const f of t.items){const r=u==="hbin"?f.hardBinCounts:f.softBinCounts;if(r){for(const[d,b]of Object.entries(r))o(Number(d),e,b);continue}for(const d of f.dies??[]){if(!p(d))continue;const b=u==="hbin"?d.hbin:d.sbin;b!==void 0&&o(b,e,1)}}});const a=c.slice().sort((t,e)=>n.get(e).total-n.get(t).total).map(t=>{const e=n.get(t);return{binCode:t,label:`Bin ${t}`,total:e.total,counts:s.map((f,r)=>e.counts[r]??0)}});return{groups:s,bins:a}}export function sortBinsForDisplay(l,u){const s=new Set(u);return[...l].sort((n,c)=>{const o=s.has(n[0]),i=s.has(c[0]);return o!==i?o?-1:1:o&&i?n[0]-c[0]:c[1]-n[1]||n[0]-c[0]})}