@wafertools/wafermap 0.37.1 → 0.39.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 (86) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +21 -13
  3. package/dist/packages/canvas-adapter/cellShade.d.ts +21 -0
  4. package/dist/packages/canvas-adapter/cellShade.js +1 -0
  5. package/dist/packages/canvas-adapter/chartPopulation.d.ts +8 -3
  6. package/dist/packages/canvas-adapter/chartPopulation.js +1 -1
  7. package/dist/packages/canvas-adapter/charts/chartShell.d.ts +45 -19
  8. package/dist/packages/canvas-adapter/charts/chartShell.js +1 -1
  9. package/dist/packages/canvas-adapter/charts/commonality.js +1 -1
  10. package/dist/packages/canvas-adapter/charts/correlation.d.ts +11 -0
  11. package/dist/packages/canvas-adapter/charts/correlation.js +1 -1
  12. package/dist/packages/canvas-adapter/charts/divergingScale.d.ts +23 -0
  13. package/dist/packages/canvas-adapter/charts/divergingScale.js +1 -0
  14. package/dist/packages/canvas-adapter/charts/groupComparison.js +1 -1
  15. package/dist/packages/canvas-adapter/charts/palette.d.ts +10 -3
  16. package/dist/packages/canvas-adapter/charts/palette.js +1 -1
  17. package/dist/packages/canvas-adapter/charts/plotChart.d.ts +3 -7
  18. package/dist/packages/canvas-adapter/charts/plotChart.js +1 -1
  19. package/dist/packages/canvas-adapter/dataTab.js +1 -1
  20. package/dist/packages/canvas-adapter/differenceMapPanel.d.ts +1 -0
  21. package/dist/packages/canvas-adapter/differenceMapPanel.js +1 -1
  22. package/dist/packages/canvas-adapter/drilldown.d.ts +5 -0
  23. package/dist/packages/canvas-adapter/drilldown.js +1 -1
  24. package/dist/packages/canvas-adapter/filterJson.d.ts +25 -0
  25. package/dist/packages/canvas-adapter/filterJson.js +5 -0
  26. package/dist/packages/canvas-adapter/index.d.ts +1 -0
  27. package/dist/packages/canvas-adapter/index.js +1 -1
  28. package/dist/packages/canvas-adapter/insightsTab.js +1 -1
  29. package/dist/packages/canvas-adapter/pageFilter.js +2 -2
  30. package/dist/packages/canvas-adapter/pinnedTests.d.ts +10 -0
  31. package/dist/packages/canvas-adapter/pinnedTests.js +1 -0
  32. package/dist/packages/canvas-adapter/plotCard.d.ts +1 -1
  33. package/dist/packages/canvas-adapter/plotCard.js +1 -1
  34. package/dist/packages/canvas-adapter/plotEditor.js +10 -1
  35. package/dist/packages/canvas-adapter/plotJsonComplete.d.ts +46 -0
  36. package/dist/packages/canvas-adapter/plotJsonComplete.js +4 -0
  37. package/dist/packages/canvas-adapter/plotJsonHistory.d.ts +12 -0
  38. package/dist/packages/canvas-adapter/plotJsonHistory.js +1 -0
  39. package/dist/packages/canvas-adapter/plotJsonSuggest.d.ts +16 -0
  40. package/dist/packages/canvas-adapter/plotJsonSuggest.js +1 -0
  41. package/dist/packages/canvas-adapter/plotModal.js +1 -1
  42. package/dist/packages/canvas-adapter/plotTab.js +1 -1
  43. package/dist/packages/canvas-adapter/renderWaferGallery.js +1 -1
  44. package/dist/packages/canvas-adapter/renderWaferMap.js +1 -1
  45. package/dist/packages/canvas-adapter/summaryPanel.d.ts +3 -3
  46. package/dist/packages/canvas-adapter/summaryPanel.js +4 -4
  47. package/dist/packages/canvas-adapter/userGuideHtml.d.ts +1 -1
  48. package/dist/packages/canvas-adapter/userGuideHtml.js +68 -33
  49. package/dist/packages/canvas-adapter/version.d.ts +2 -2
  50. package/dist/packages/canvas-adapter/version.js +1 -1
  51. package/dist/packages/canvas-adapter/viewSwitch.js +1 -1
  52. package/dist/packages/canvas-adapter/virtualTable.d.ts +2 -0
  53. package/dist/packages/canvas-adapter/virtualTable.js +1 -1
  54. package/dist/packages/core/utils.d.ts +6 -0
  55. package/dist/packages/core/utils.js +1 -1
  56. package/dist/packages/renderer/buildWaferMap.js +1 -1
  57. package/dist/packages/renderer/derivedTests/apply.d.ts +10 -0
  58. package/dist/packages/renderer/derivedTests/apply.js +1 -1
  59. package/dist/packages/renderer/derivedTests/check.d.ts +35 -0
  60. package/dist/packages/renderer/derivedTests/check.js +1 -0
  61. package/dist/packages/renderer/fmt.d.ts +5 -0
  62. package/dist/packages/renderer/fmt.js +1 -1
  63. package/dist/packages/renderer/index.d.ts +2 -0
  64. package/dist/packages/renderer/index.js +1 -1
  65. package/dist/packages/stats/analyzeWaferLot.js +1 -1
  66. package/dist/packages/stats/analyzeWaferMap.js +1 -1
  67. package/dist/packages/stats/chartCatalogue.js +1 -1
  68. package/dist/packages/stats/clusterDetection.js +1 -1
  69. package/dist/packages/stats/coFailure.d.ts +11 -0
  70. package/dist/packages/stats/coFailure.js +1 -0
  71. package/dist/packages/stats/correlation.d.ts +7 -0
  72. package/dist/packages/stats/correlation.js +1 -1
  73. package/dist/packages/stats/differenceMap.d.ts +2 -0
  74. package/dist/packages/stats/differenceMap.js +1 -1
  75. package/dist/packages/stats/plotData.d.ts +18 -2
  76. package/dist/packages/stats/plotData.js +1 -1
  77. package/dist/packages/stats/plotSpec.d.ts +31 -2
  78. package/dist/packages/stats/plotSpec.js +4 -4
  79. package/dist/packages/stats/plotTable.d.ts +18 -0
  80. package/dist/packages/stats/plotTable.js +1 -0
  81. package/dist/packages/stats/reportHtml.js +33 -29
  82. package/dist/packages/stats/synthesis.d.ts +7 -1
  83. package/dist/packages/stats/synthesis.js +1 -1
  84. package/dist/packages/stats/testsByWafer.d.ts +11 -0
  85. package/dist/packages/stats/testsByWafer.js +1 -0
  86. package/package.json +8 -4
@@ -0,0 +1,35 @@
1
+ import type { TestDef } from '../buildWaferMap.js';
2
+ import { type AccessorKind } from './parser.js';
3
+ import { type DerivedTestDef } from './apply.js';
4
+ export interface DerivedCheckInput {
5
+ expression: string;
6
+ /** The number the derived test will have; a derived test may not read itself. */
7
+ testNumber: number;
8
+ /** The declared kind. Omitted: not checked against what the expression produces. */
9
+ testType?: 'P' | 'F';
10
+ constants?: Record<string, number>;
11
+ }
12
+ export type DerivedCheck = {
13
+ ok: true;
14
+ /** What the expression produces: a measurement, or a true/false verdict (which needs `testType: 'F'`). */
15
+ produces: 'number' | 'verdict';
16
+ /** Every test the expression reads, and how, in order of appearance. */
17
+ reads: {
18
+ kind: AccessorKind;
19
+ test: number;
20
+ }[];
21
+ /** Advice that does not stop the test being built, such as units combined by `+`. */
22
+ warnings: string[];
23
+ } | {
24
+ ok: false;
25
+ message: string;
26
+ /** 0-based character offset into `expression`, when the problem has one. */
27
+ position?: number;
28
+ };
29
+ /**
30
+ * `testDefs` are the measured tests the expression may read; `otherDerived` are the host's *other* derived
31
+ * tests, which it may read too. The identity rules are the build's: a test number is a whole number from 0 to
32
+ * the STDF maximum, and neither a measured test nor another derived test may already have it.
33
+ */
34
+ export declare function checkDerivedExpression(input: DerivedCheckInput, testDefs: readonly TestDef[], otherDerived?: readonly DerivedTestDef[]): DerivedCheck;
35
+ //# sourceMappingURL=check.d.ts.map
@@ -0,0 +1 @@
1
+ import{isStdfTestNumber as f,STDF_TEST_NUM_MAX as u}from"../../core/stdf.js";import{parseExpression as c}from"./parser.js";import{unitMismatch as d}from"./apply.js";export function checkDerivedExpression(e,n,a=[]){if(typeof e.expression!="string"||e.expression.trim()==="")return{ok:!1,message:"The expression is empty."};if(!f(e.testNumber))return{ok:!1,message:`The test number must be a whole number from 0 to ${u}, as STDF stores it.`};const r=new Map(n.map(s=>[s.testNumber,s]));if(r.has(e.testNumber))return{ok:!1,message:`Test number ${e.testNumber} already exists in the data; give the derived test an unused number.`};for(const s of a){if(s.testNumber===e.testNumber)return{ok:!1,message:`Test number ${e.testNumber} is used by another derived test.`};const{expression:b,constants:p,...m}=s;r.set(s.testNumber,{...m,testType:s.testType??"P"})}const t=c(e.expression,{testDefs:r,constants:e.constants??{}});if(!t.ok)return{ok:!1,message:t.message,position:t.position};const o=t.type==="boolean";if(e.testType!==void 0&&o!==(e.testType==="F"))return{ok:!1,message:o?"The expression produces a true/false verdict, so the test must be functional.":"The test is functional but its expression produces a number; a functional test carries a verdict."};if(t.reads.some(s=>s.test===e.testNumber))return{ok:!1,message:"The expression reads the test it defines."};const i=d(t.ast,r).map(s=>`Different units are combined: ${s}.`);return{ok:!0,produces:o?"verdict":"number",reads:t.reads,warnings:i}}
@@ -3,6 +3,11 @@
3
3
  * agree on every prefix. Internal — not re-exported from the package. */
4
4
  export declare const SI_PREFIX_SCALE: Record<string, number>;
5
5
  export declare const KNOWN_BASE_UNITS: string[];
6
+ /**
7
+ * Whether a test's name already ends with its own unit as a separate token (`fmax_MHz`, `Vth (mV)`, `Idsat uA`). Such
8
+ * a name states its unit, so an axis title must not append a differently scaled one ("fmax_MHz (GHz)").
9
+ */
10
+ export declare function nameStatesUnit(name: string | null | undefined, unit: string | undefined): boolean;
6
11
  /**
7
12
  * Plain-language labels for lot-stack aggregation methods. Maps internal API terms to the words
8
13
  * shown to the user (e.g. `countBin` → "occurrence count"). Shared by the canvas map title and the
@@ -1 +1 @@
1
- import{stepDecimals as p}from"./axisTicks.js";const M=[[1e12,"T"],[1e9,"G"],[1e6,"M"],[1e3,"k"],[1,""],[.001,"m"],[1e-6,"\xB5"],[1e-9,"n"],[1e-12,"p"],[1e-15,"f"]];export const SI_PREFIX_SCALE={T:1e12,G:1e9,M:1e6,k:1e3,m:.001,\u00B5:1e-6,u:1e-6,n:1e-9,p:1e-12,f:1e-15},KNOWN_BASE_UNITS=["Hz","V","A","W","F","\u03A9","Ohm","ohm","S","H","J","C","s"];function m(t){for(const e of KNOWN_BASE_UNITS)if(t.length===e.length+1&&t.endsWith(e)){const r=t[0];if(r in SI_PREFIX_SCALE)return{preScale:SI_PREFIX_SCALE[r],base:e}}return{preScale:1,base:t}}function F(t,e){const{preScale:r,base:n}=m(e),o=t*r,i=Math.abs(o),[c,h]=M.find(([s])=>i>=s*.9999)??[1e-15,"f"],f=o/c,b=Math.abs(f),u=b>=100?0:b>=10?1:2;return`${f.toFixed(u)} ${h}${n}`}function $(t){const e=Math.abs(t);if(e===0)return"0%";const r=e>=100?0:e>=10?1:e>=1?2:Math.min(6,1-Math.floor(Math.log10(e)));return`${t.toFixed(r)}%`}function E(t){const e=Math.abs(t),r=Math.floor(Math.log10(e)/3)*3,n=Math.max(-15,Math.min(12,r)),o=t/Math.pow(10,n),i=Math.abs(o),c=i>=100?0:i>=10?1:2,h=n===0?"":`E${n>0?"+":""}${n}`;return`${o.toFixed(c)}${h}`}export const AGGREGATION_METHOD_LABELS={mean:"mean",median:"median",stddev:"std dev",min:"min",max:"max",count:"count",countBin:"occurrence count",percent:"occurrence %"};export function fmtAggregationMethod(t){return AGGREGATION_METHOD_LABELS[t??""]??t??"aggregated"}export function plainBinTerms(t){return t.replace(/\bHBin\b/g,"hard bin").replace(/\bSBin\b/g,"soft bin")}export function fmtExact(t){if(!Number.isFinite(t)||Math.fround(t)!==t)return String(t);for(let e=1;e<=9;e++){const r=Number(t.toPrecision(e));if(Math.fround(r)===t)return String(r)}return String(t)}export function fmt(t,e,r){if(!isFinite(t))return String(t);if(e==="%")return $(t);const n=Math.abs(t);return n===0?e?`0 ${e}`:"0":e!==void 0?F(t,e):r==="si"?F(t,""):n>=.1&&n<1e4?n>=1e3?t.toFixed(0):n>=100?t.toFixed(1):n>=10?t.toFixed(2):t.toFixed(3):E(t)}function A(t,e){const r=e!==void 0&&e>0?p(e/t):void 0;return n=>{if(!isFinite(n))return String(n);if(n===0)return"0";const o=n/t;if(r!==void 0)return o.toFixed(r);const i=Math.abs(o),c=i>=100?0:i>=10?1:2;return o.toFixed(c)}}function T(t,e,r){if(e===void 0||!(e>0))return r;const n=p(e/t)+1;return o=>{if(!isFinite(o))return String(o);if(o===0)return"0";const i=(o/t).toFixed(n);return i.endsWith("0")?i.slice(0,n===1?-2:-1):i}}export function fmtColorbarAxis(t,e,r,n="engineering",o){const i=Math.abs(t),c=(s,d,a,x)=>{const g=x&&o===void 0?x:A(s,o);return{tickFmt:g,edgeFmt:T(s,o,g),axisLabel:d,scaledUnit:a}};if(r==="%")return c(1,e?`${e} (%)`:"%","%");if(r){const{preScale:s,base:d}=m(r),a=i*s,[x,g]=a===0?[1,""]:M.find(([S])=>a>=S*.9999)??[1e-15,"f"],l=`${g}${d}`;return c(x/s,e?`${e} (${l})`:l,l)}if(i===0||i>=.1&&i<1e4)return c(1,e??"","",s=>fmt(s,void 0,n));if(n==="si"){const[s]=M.find(([x])=>i>=x*.9999)??[1e-15,"f"],d=Math.round(Math.log10(s)),a=d===0?"":`\xD710E${d}`;return c(s,e?a?`${e} (${a})`:e:a,a)}const h=Math.floor(Math.log10(i)/3)*3,f=Math.max(-15,Math.min(12,h)),b=Math.pow(10,f),u=f===0?"":`\xD710E${f}`;return c(b,e?u?`${e} (${u})`:e:u,u)}
1
+ import{stepDecimals as m}from"./axisTicks.js";const M=[[1e12,"T"],[1e9,"G"],[1e6,"M"],[1e3,"k"],[1,""],[.001,"m"],[1e-6,"\xB5"],[1e-9,"n"],[1e-12,"p"],[1e-15,"f"]];export const SI_PREFIX_SCALE={T:1e12,G:1e9,M:1e6,k:1e3,m:.001,\u00B5:1e-6,u:1e-6,n:1e-9,p:1e-12,f:1e-15},KNOWN_BASE_UNITS=["Hz","V","A","W","F","\u03A9","Ohm","ohm","S","H","J","C","s"];function p(e){for(const t of KNOWN_BASE_UNITS)if(e.length===t.length+1&&e.endsWith(t)){const n=e[0];if(n in SI_PREFIX_SCALE)return{preScale:SI_PREFIX_SCALE[n],base:t}}return{preScale:1,base:e}}export function nameStatesUnit(e,t){if(!e||!t)return!1;let n=e.trimEnd();if((n.endsWith(")")||n.endsWith("]"))&&(n=n.slice(0,-1)),!n.endsWith(t))return!1;const r=n.length===t.length?"":n[n.length-t.length-1];return r===""||/[\s_\-/([]/.test(r)}function S(e,t){const{preScale:n,base:r}=p(t),i=e*n,o=Math.abs(i),[c,u]=M.find(([s])=>o>=s*.9999)??[1e-15,"f"],h=i/c,g=Math.abs(h),a=g>=100?0:g>=10?1:2;return`${h.toFixed(a)} ${u}${r}`}function E(e){const t=Math.abs(e);if(t===0)return"0%";const n=t>=100?0:t>=10?1:t>=1?2:Math.min(6,1-Math.floor(Math.log10(t)));return`${e.toFixed(n)}%`}function A(e){const t=Math.abs(e),n=Math.floor(Math.log10(t)/3)*3,r=Math.max(-15,Math.min(12,n)),i=e/Math.pow(10,r),o=Math.abs(i),c=o>=100?0:o>=10?1:2,u=r===0?"":`E${r>0?"+":""}${r}`;return`${i.toFixed(c)}${u}`}export const AGGREGATION_METHOD_LABELS={mean:"mean",median:"median",stddev:"std dev",min:"min",max:"max",count:"count",countBin:"occurrence count",percent:"occurrence %"};export function fmtAggregationMethod(e){return AGGREGATION_METHOD_LABELS[e??""]??e??"aggregated"}export function plainBinTerms(e){return e.replace(/\bHBin\b/g,"hard bin").replace(/\bSBin\b/g,"soft bin")}export function fmtExact(e){if(!Number.isFinite(e)||Math.fround(e)!==e)return String(e);for(let t=1;t<=9;t++){const n=Number(e.toPrecision(t));if(Math.fround(n)===e)return String(n)}return String(e)}export function fmt(e,t,n){if(!isFinite(e))return String(e);if(t==="%")return E(e);const r=Math.abs(e);return r===0?t?`0 ${t}`:"0":t!==void 0?S(e,t):n==="si"?S(e,""):r>=.1&&r<1e4?r>=1e3?e.toFixed(0):r>=100?e.toFixed(1):r>=10?e.toFixed(2):e.toFixed(3):A(e)}function T(e,t){const n=t!==void 0&&t>0?m(t/e):void 0;return r=>{if(!isFinite(r))return String(r);if(r===0)return"0";const i=r/e;if(n!==void 0)return i.toFixed(n);const o=Math.abs(i),c=o>=100?0:o>=10?1:2;return i.toFixed(c)}}function _(e,t,n){if(t===void 0||!(t>0))return n;const r=m(t/e)+1;return i=>{if(!isFinite(i))return String(i);if(i===0)return"0";const o=(i/e).toFixed(r);return o.endsWith("0")?o.slice(0,r===1?-2:-1):o}}const I={"-":"\u207B",0:"\u2070",1:"\xB9",2:"\xB2",3:"\xB3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079"},F=e=>e===0?"":`\xD710${[...String(e)].map(t=>I[t]).join("")}`;export function fmtColorbarAxis(e,t,n,r="engineering",i){const o=Math.abs(e),c=(s,l,f,d)=>{const x=d&&i===void 0?d:T(s,i);return{tickFmt:x,edgeFmt:_(s,i,x),axisLabel:l,scaledUnit:f}};if(n==="%")return c(1,t?`${t} (%)`:"%","%");if(n&&nameStatesUnit(t,n)){const s=o===0||o>=.1&&o<1e4;return p(n).preScale!==1||s?c(1,t,n):fmtColorbarAxis(e,t,void 0,r,i)}if(n){const{preScale:s,base:l}=p(n),f=o*s,[d,x]=f===0?[1,""]:M.find(([$])=>f>=$*.9999)??[1e-15,"f"],b=`${x}${l}`;return c(d/s,t?`${t} (${b})`:b,b)}if(o===0||o>=.1&&o<1e4)return c(1,t??"","",s=>fmt(s,void 0,r));if(r==="si"){const[s]=M.find(([d])=>o>=d*.9999)??[1e-15,"f"],l=Math.round(Math.log10(s)),f=F(l);return c(s,t?f?`${t} (${f})`:t:f,f)}const u=Math.floor(Math.log10(o)/3)*3,h=Math.max(-15,Math.min(12,u)),g=Math.pow(10,h),a=F(h);return c(g,t?a?`${t} (${a})`:t:a,a)}
@@ -10,4 +10,6 @@ export type { BinColors, BinColorSource, MapBinColorOptions } from './binColors.
10
10
  export { binColorsForMaps } from './binColors.js';
11
11
  export { DERIVED_MARK, DERIVED_KEY } from './testLabel.js';
12
12
  export { fmtExact } from './fmt.js';
13
+ export { checkDerivedExpression } from './derivedTests/check.js';
14
+ export type { DerivedCheck, DerivedCheckInput } from './derivedTests/check.js';
13
15
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- export{getDieKey}from"./buildView.js";export{buildWaferMap,getTestPassStatus}from"./buildWaferMap.js";export{registerValueColorScheme,listValueColorSchemes,resolveValueColorFn,registerBinColorScheme,listBinColorSchemes}from"./colorSchemes.js";export{binColorsForMaps}from"./binColors.js";export{DERIVED_MARK,DERIVED_KEY}from"./testLabel.js";export{fmtExact}from"./fmt.js";
1
+ export{getDieKey}from"./buildView.js";export{buildWaferMap,getTestPassStatus}from"./buildWaferMap.js";export{registerValueColorScheme,listValueColorSchemes,resolveValueColorFn,registerBinColorScheme,listBinColorSchemes}from"./colorSchemes.js";export{binColorsForMaps}from"./binColors.js";export{DERIVED_MARK,DERIVED_KEY}from"./testLabel.js";export{fmtExact}from"./fmt.js";export{checkDerivedExpression}from"./derivedTests/check.js";
@@ -1 +1 @@
1
- import{waferDisplayLabel as oe}from"../core/waferLabel.js";import{requireRingCount as ce}from"../core/ringCount.js";import{analyzeWaferMapDecided as F,candidatesOf as H,describeRegional as U,resolveOptions as le,adjustPValues as fe,testValueSize as de,recordedOptions as ue,twoProportionZ as Q,welchOfSums as X,rateRelativeEffect as me,passesRateGate as pe,severityForFinding as Z,severityForScore as J,collapseRedundantFindings as ge,findContiguousRuns as he,mergedRegionLabel as ye}from"./analyzeWaferMap.js";import{normalizeInput as ee}from"./normalizeInput.js";import{autoDecision as we,lotTestValueStatus as be}from"./testValueBudget.js";import{poolCapability as Se,poolRegionYield as ve,poolPassRates as ze}from"./summaryFigures.js";import{mergeTestDefs as Ie}from"./mergeTestDefs.js";import{findingPatternKey as ke}from"./filterFindings.js";import{median as te}from"../core/utils.js";import{robustFence as ne,zPValue as T}from"./math.js";import{findLotPattern as xe}from"./lotPattern.js";import{buildDriftFindings as Pe}from"./lotDrift.js";import{claimForPattern as Re,confirmRegionalFindings as Me,weakestMultiplier as $e}from"./analyzeWaferMap.js";import{PATTERN_LABELS as De}from"./patternClassification.js";import{describeWaferPopulation as Be,populationStat as We}from"./population.js";const N=8,Le={3:[.97,.994],4:[.829,.926],5:[.71,.821],6:[.625,.74],7:[.568,.68]},Ke=3;export function outlierWafers(e){const o=e.length;if(o<3)return null;const s=te([...e]),t=n=>Math.abs(n-s)>=Ke;if(o>=N){const n=ne(e,1.5,N),d=ne(e,3,N);if(!n||!d)return null;const m=(n.hi-n.lo)/4,w=[];return e.forEach((y,l)=>{if(y>=n.lo&&y<=n.hi||!t(y))return;const f=y<d.lo||y>d.hi?"unusual":"notable";w.push({index:l,severity:f,statistic:(y-s)/m})}),{method:"tukey-fence",outliers:w}}const a=e.map((n,d)=>d).sort((n,d)=>e[n]-e[d]),u=e[a[o-1]]-e[a[0]];if(u===0)return null;const[r,c]=Le[o],p=[],h=(n,d)=>{const m=Math.abs(e[n]-e[d])/u;m>r&&t(e[n])&&p.push({index:n,severity:m>c?"unusual":"notable",statistic:m})};return h(a[0],a[1]),h(a[o-1],a[o-2]),{method:"dixon-q",outliers:p}}const q=2;function O(e,o){const s={info:0,notable:1,unusual:2};return s[e]>=s[o]?e:o}const Ee=new Set(["ring","quadrant","sector"]),Te=new Set(["ring","quadrant","sector","reticle-position","test-site"]),qe=new Set(["yield","hardBin","softBin","functionalTest","test"]);function Ae(e){return Te.has(e.comparison.family)&&qe.has(e.variable.kind)}function Fe(e,o){const s=e.map(r=>r.facts);if(!s.length||s.some(r=>!r))return{coincident:new Set,yieldSoftBin:void 0,passBins:[],sectorCount:o};const[t,...a]=s,u=a.every(r=>r.passBins.length===t.passBins.length&&r.passBins.every(c=>t.passBins.includes(c)));return{coincident:new Set([...t.coincident].filter(r=>a.every(c=>c.coincident.has(r)))),yieldSoftBin:a.every(r=>r.yieldSoftBin===t.yieldSoftBin)?t.yieldSoftBin:void 0,passBins:u?t.passBins:[],sectorCount:o}}function j(e,o){let s=0,t=0,a=0,u=0,r=0,c=0,p=0,h=0,n=0,d=!0,m=0;for(const{waferIndex:l,c:f}of e){const i=o(l,f),g=f.rate??f.mean,b=Math.sqrt(g.n+i.n);if(f.rate)s+=b*Q(f.rate.hits,f.rate.n,i.hits,i.n),a+=f.rate.hits,u+=f.rate.n,r+=i.hits,c+=i.n;else{const v=X(f.mean,i.n,i.sum,i.sq);s+=b*v.z,p+=f.mean.n*v.effectSize,h+=f.mean.n*v.delta,m+=f.mean.n,f.relativeDelta===void 0?d=!1:n+=f.mean.n*f.relativeDelta}t+=b*b}const w=t>0?s/Math.sqrt(t):0,y=e[0].c;if(y.rate){const l=r/c,f=a/u-l;return{z:w,delta:f,relativeDelta:l===0?void 0:f/l,size:me({hits:a,n:u,restHits:r,restN:c,passRate:y.rate.passRate})}}return{z:w,delta:h/m,relativeDelta:d?n/m:void 0,size:p/m}}function V(e,o,s,t){return e.rate?pe(o,s.delta,s.size,t):o<=t.significanceLevel&&Math.abs(s.size)>=t.minimumEffectSize}function Ne(e,o,s,t){const a=new Map;for(const{waferIndex:l,byKey:f}of e)for(const i of f.values())(a.get(i.key)??a.set(i.key,[]).get(i.key)).push({waferIndex:l,c:i});const u=new Map(e.map(l=>[l.waferIndex,l.byKey])),r=(l,f)=>f.rate?{hits:f.rate.restHits,n:f.rate.restN,sum:0,sq:0}:{hits:0,n:f.mean.restN,sum:f.mean.restSum,sq:f.mean.restSq},c=[];for(const[l,f]of a){if(f.length<q)continue;const i=j(f,r);if(i.z===0)continue;const g=f[0].c;c.push({key:l,entries:f,combined:i,finding:{id:`lot-region:${l}`,level:"lot",severity:"info",variable:{...g.variable,label:g.label},comparison:{...g.comparison},effect:{direction:i.z>0?"higher":"lower",absoluteDelta:i.delta,relativeDelta:i.relativeDelta,effectSize:g.rate?i.delta:i.size},stats:{method:"stouffer-z",pValue:T(i.z),sampleSizeLeft:0,sampleSizeRight:0},summary:"",highlight:{kind:"wafer",waferIndices:[]}}})}fe(c.map(l=>l.finding));const p=c.filter(l=>V(l.entries[0].c,l.finding.stats.adjustedPValue??1,l.combined,o)),d=Me(p,l=>{const f=l.entries[0].c;return[f.source,f.variable.kind,f.variable.bin??"",f.variable.index??"",f.region.family].join("\0")},(l,f)=>{const i=(R,D)=>{const k=r(R,D);for(const z of f){const P=u.get(R)?.get(z.key);P&&(P.rate?(k.hits-=P.rate.hits,k.n-=P.rate.n):(k.n-=P.mean.n,k.sum-=P.mean.sum,k.sq-=P.mean.sq))}return k},g=l.entries.filter(R=>i(R.waferIndex,R.c).n>=o.minimumSampleSize);if(!g.length)return"baseline-too-small";const b=j(g,i),v=l.finding.stats.pValue??1,x=v>0?(l.finding.stats.adjustedPValue??v)/v:1,S=Math.min(1,T(b.z)*x);return{pValue:S,passes:Math.sign(b.z)===Math.sign(l.combined.z)&&V(l.entries[0].c,S,b,o)}},l=>{const f=l.entries[0].c.rate;return f!==void 0&&(f.passRate?l.combined.z<0:l.combined.z>0)},c),m=[],w=new Map;for(const l of p){if(!d.has(l))continue;const f=l.finding.stats.pValue??1,i=Math.sign(l.combined.z),g=l.entries.filter(z=>Math.sign(z.c.delta)===i),b=e.length,v=l.entries[0].c,x=l.finding.stats.adjustedPValue??f,S=v.rate?Z(x,l.combined.delta,l.combined.size):J(x,l.combined.size),R=O(S,g.length/b>=.6?"unusual":"info"),D={};for(const z of g)D[z.waferIndex]=[...z.c.region.dieKeys];const k={...l.finding,severity:R,stats:{...l.finding.stats,sampleSizeLeft:g.length,sampleSizeRight:b-g.length},summary:`${U(v,l.combined.delta,l.combined.relativeDelta)} \u2014 ${l.finding.effect.direction} on ${g.length}/${b} wafers, all wafers' data combined`,highlight:{kind:"wafer",waferIndices:g.map(z=>z.waferIndex),dieKeysByWafer:D}};m.push(k),w.set(k,l)}const y=Oe(w,u,e.length,o,t,r);return m.splice(0,m.length,...m.filter(l=>!y.replaced.has(l)),...y.findings),ge(m,s),m}function Oe(e,o,s,t,a,u){const r=new Map;for(const[h,n]of e){const d=n.entries[0].c;if(!Ee.has(d.region.family))continue;const m=[d.source,d.variable.kind,d.variable.bin??"",d.variable.index??"",d.region.family,h.effect.direction].join("|");(r.get(m)??r.set(m,[]).get(m)).push({finding:h,c:d,key:n.key})}const c=[],p=new Set;for(const h of r.values()){if(h.length<2)continue;const n=h[0].c.region.family;for(const d of he(h,n,t.sectorCount,m=>m.c.region.key)){if(d.length<2)continue;const m=je(d,o,s,t,a,u);if(m){c.push(m);for(const w of d)p.add(w.finding)}}}return{findings:c,replaced:p}}function je(e,o,s,t,a,u){const r=e[0].c,c=e[0].finding.effect.direction==="higher"?1:-1,p=ye(r.region.family,e.map(S=>S.c.region.key),a),h=[];for(const[S,R]of o){const D=e.map(I=>R.get(I.key));if(D.some(I=>!I))continue;const k=D,z=k[0];let P,A;if(z.rate){const I=k.reduce(($,B)=>$+B.rate.hits,0),M=k.reduce(($,B)=>$+B.rate.n,0),L=z.rate.hits+z.rate.restHits-I,W=z.rate.n+z.rate.restN-M;if(M<t.minimumSampleSize||W<t.minimumSampleSize)continue;P={...z,rate:{hits:I,n:M,restHits:L,restN:W,passRate:z.rate.passRate}},A=Q(I,M,L,W)}else{const I=z.mean,M=k.reduce((K,E)=>K+E.mean.n,0),L=k.reduce((K,E)=>K+E.mean.sum,0),W=k.reduce((K,E)=>K+E.mean.sq,0),$=I.n+I.restN-M,B=I.sum+I.restSum-L,_=I.sq+I.restSq-W;if(M<t.minimumSampleSize||$<t.minimumSampleSize)continue;const Y={n:M,sum:L,sq:W,restN:$,restSum:B,restSq:_,shift:I.shift},C=X(Y,$,B,_),G=B/$+I.shift;P={...z,mean:Y,relativeDelta:G!==0?C.delta/Math.abs(G):void 0},A=C.z}const re=[...new Set(k.flatMap(I=>[...I.region.dieKeys]))];h.push({waferIndex:S,c:P,z:A,dieKeys:re})}if(h.length<q)return;const n=j(h,u);if(n.z===0||Math.sign(n.z)!==c)return;const d=T(n.z),m=$e(e.map(S=>S.finding)),w=Math.min(1,d*m);if(!V(r,w,n,t))return;const y=h.filter(S=>Math.sign(S.z)===c&&T(S.z)<=t.significanceLevel);if(!y.length)return;const l=r.rate?Z(w,n.delta,n.size):J(w,n.size),f=O(l,y.length/s>=.6?"unusual":"info"),i={};for(const S of y)i[S.waferIndex]=S.dieKeys;const g=e.map(S=>S.c.region.key.slice(S.c.region.key.indexOf(":")+1)).join("-"),b={...r,comparison:{...r.comparison,left:p}},v=e[0].finding,x=v.effect.direction;return{...v,id:`lot-region:${e[0].key.split("|").slice(0,-1).join("|")}|${r.region.family}:${g}`,severity:f,comparison:{...v.comparison,left:p},effect:{direction:x,absoluteDelta:n.delta,relativeDelta:n.relativeDelta,effectSize:r.rate?n.delta:n.size},stats:{method:"stouffer-z",pValue:d,adjustedPValue:w,sampleSizeLeft:y.length,sampleSizeRight:s-y.length},summary:`${U(b,n.delta,n.relativeDelta)} \u2014 ${x} on ${y.length}/${s} wafers, all wafers' data combined`,highlight:{kind:"wafer",waferIndices:y.map(S=>S.waferIndex),dieKeysByWafer:i},relatedIds:e.map(S=>S.finding.id)}}const ie={"Edge-ring":"edge","Edge-local":"edge","Center cluster":"centre or donut",Donut:"centre or donut"};function Ve(e,o){const s=new Map,t=r=>{const c=r.variable.kind==="spatialPattern"?ie[r.comparison.left]:void 0;return c?`spatialPattern|${c}`:ke(r)};for(const r of e){const c=new Set,p=new Map;for(const n of r.summary.findings)if(n.variable.kind==="spatialPattern")for(const d of n.relatedIds??[])p.set(d,t(n));const h=new Set(r.summary.findings.flatMap(n=>n.absorbedIds??[]));for(const n of r.summary.findings){if(h.has(n.id)||Ae(n)||n.variable.kind==="spatialPattern"&&o?.carriers.has(r.waferIndex))continue;const d=t(n);if(c.has(d))continue;c.add(d);const m=s.get(d)??{finding:n,waferIndices:[],severity:n.severity,labels:new Map,dieKeysByWafer:{},explainedBy:new Map};m.waferIndices.push(r.waferIndex);const w=p.get(n.id);if(w&&m.explainedBy.set(w,(m.explainedBy.get(w)??0)+1),n.variable.kind==="spatialPattern"){m.labels.set(n.comparison.left,(m.labels.get(n.comparison.left)??0)+1);const y=n.highlight.dieKeys;y&&(m.dieKeysByWafer[r.waferIndex]=y)}m.severity=O(m.severity,n.severity),s.set(d,m)}}const a=[];for(const[r,c]of s){if(c.waferIndices.length<q)continue;const p=c.waferIndices.length/Math.max(1,e.length),h=p>=.6||c.severity==="unusual"?"unusual":"notable",n=c.finding;a.push({id:`lot-repeat:${r}`,level:"lot",severity:h,variable:{...n.variable},comparison:{...n.comparison},effect:{direction:n.effect.direction,absoluteDelta:n.effect.absoluteDelta,relativeDelta:n.effect.relativeDelta,effectSize:n.effect.effectSize},stats:{method:"wafer-finding-frequency",sampleSizeLeft:c.waferIndices.length,sampleSizeRight:e.length-c.waferIndices.length},summary:`${Ce(n,c.labels)} \u2014 seen on ${c.waferIndices.length}/${e.length} wafers (${Math.round(p*100)}%)`,highlight:{kind:"wafer",waferIndices:c.waferIndices,...c.labels.size?{dieKeysByWafer:c.dieKeysByWafer}:{}}})}const u=new Map(a.map(r=>[r.id,r]));for(const[r,c]of s){const p=u.get(`lot-repeat:${r}`);if(p)for(const[h,n]of c.explainedBy){const d=u.get(`lot-repeat:${h}`);!d||n!==c.waferIndices.length||(d.relatedIds??=[]).push(p.id)}}return a}function _e(e,o){const{classification:s,carriers:t}=e,a=De[s.pattern],u=t.size/Math.max(1,o),r={};for(const[c,p]of t)r[c]=p;return{id:"lot-repeat:spatialPattern|lot",level:"lot",severity:u>=.6||s.confidence==="high"?"unusual":"notable",variable:{kind:"spatialPattern",label:a},comparison:{family:"spatial-pattern",left:a,right:"Wafer"},effect:{direction:"different",effectSize:s.features.globalRdd},stats:{method:"wafer-finding-frequency",sampleSizeLeft:t.size,sampleSizeRight:o-t.size},summary:`Spatial pattern: ${a.toLowerCase()} \u2014 seen on ${t.size}/${o} wafers (${Math.round(u*100)}%)`,highlight:{kind:"wafer",waferIndices:[...t.keys()].sort((c,p)=>c-p),dieKeysByWafer:r}}}function Ye(e){const o=/^Rings? (\d+)(?:\s*[–-]\s*(\d+))?/.exec(e.comparison.left);if(!o)return[];const s=+o[1],t=o[2]?+o[2]:s;return Array.from({length:Math.max(0,t-s+1)},(a,u)=>s+u)}function Ce(e,o){if(!o.size)return e.summary;const s=u=>u.toLowerCase();if(o.size===1)return`Spatial pattern: ${s([...o.keys()][0])}`;const t=ie[e.comparison.left],a=[...o].sort((u,r)=>r[1]-u[1]).map(([u,r])=>`${s(u)} on ${r}`);return`Spatial pattern: ${t} (${a.join(", ")})`}function Ge(e,o){const s=We(o,"median"),t=e.map(p=>({waferIndex:p.waferIndex,yieldPercent:p.summary.stats.yieldPercent})).filter(p=>p.yieldPercent!==null),a=t.map(p=>p.yieldPercent),u=outlierWafers(a);if(!u)return[];const r=te(a),c=[];for(const{index:p,severity:h,statistic:n}of u.outliers){const d=t[p],m=d.yieldPercent-r,w=oe({wafer:{metadata:e.find(y=>y.waferIndex===d.waferIndex)?.summary.wafer}},d.waferIndex);c.push({id:`inter-wafer:yield:${d.waferIndex}`,level:"inter-wafer",severity:h,variable:{kind:"yield",label:"Yield"},comparison:{family:"wafer",left:w,right:s.charAt(0).toUpperCase()+s.slice(1)},effect:{direction:m>0?"higher":"lower",absoluteDelta:m/100,relativeDelta:r===0?void 0:m/r,effectSize:n},stats:{method:u.method,sampleSizeLeft:1,sampleSizeRight:t.length-1},summary:`${w} yield is ${Math.abs(m).toFixed(1)} percentage points ${m>0?"higher":"lower"} than the ${s}`,highlight:{kind:"wafer",waferIndices:[d.waferIndex]}})}return c}function se(e,o){if((o.enableTestValueAnalysis??"auto")!=="auto")return;let s=0;for(const t of e){const{tests:a,dies:u}=de(t,o);s+=a*u}return we(s)}export function analyzeWaferLot(e,o={}){const s=e.map(ee),t=se(s,o),a=s.map((i,g)=>({waferIndex:g,summary:o.perWaferSummaries?.[g]??F(i,o,t)})),u=a.map(({waferIndex:i,summary:g})=>H(g)??H(F(s[i],o,t))),r=u.map((i,g)=>({waferIndex:g,byKey:new Map(i.candidates.map(b=>[b.key,b]))})),c=le(o).resolved,p=s.length>0?ce(s[0],"analyzeWaferLot"):void 0,h=xe(s,c),n=h&&h.carriers.size>=q?h:null,d=[...p===void 0?[]:Ne(r,c,Fe(u,c.sectorCount),p),...Ve(a,n),...Ge(a,Be(a.map(i=>i.summary.wafer))),...Pe(a,c.significanceLevel)];if(n&&p!==void 0){const i=_e(n,a.length);i.relatedIds=Re([n.classification.pattern],i.severity,d,Ye,p),i.relatedIds.length||delete i.relatedIds,d.push(i)}d.sort((i,g)=>{const b=i.severity==="unusual"?2:i.severity==="notable"?1:0,v=g.severity==="unusual"?2:g.severity==="notable"?1:0;return b!==v?v-b:i.summary.localeCompare(g.summary,"en")});const m=a.map(i=>i.summary.wafer).filter(i=>!!i),w={},y=[];if(m.length>0){const i=new Set;for(const g of m)for(const b of Object.keys(g))i.add(b);i.delete("wafer"),i.delete("waferId");for(const g of i){const b=m.filter(x=>g in x).map(x=>x[g]);b.every(x=>x===b[0])?w[g]=b[0]:y.push(g)}}const l=a.map(({waferIndex:i,summary:g})=>({waferIndex:i,yieldPercent:g.stats.yieldPercent})),f=a.map(({waferIndex:i,summary:g})=>g.stats.perTestStats?.length?{waferIndex:i,tests:g.stats.perTestStats}:null).filter(i=>i!==null);return{level:"lot",hasNotableFindings:d.some(i=>i.severity!=="info")||a.some(i=>i.summary.hasNotableFindings),findings:d,lot:Object.keys(w).length>0?w:void 0,...y.length>0?{mixedIdentityFields:y}:{},analysisOptions:ue(o),stats:{waferCount:e.length,...He(s,a.map(i=>i.summary)),...Ue(be(a.map(i=>i.summary)))},lotYieldSeries:l,perWafer:a,...f.length>0?{perWaferTestStats:f}:{}}}function He(e,o){const s={...ze(o)},t=Se(o,Ie(e).defs);t&&(s.capability=t);const a=ve(o,e.map(u=>u.ringCount));return a&&(s.regionYield=a),s}const Ue=e=>e?{testValueAnalysis:e}:{},ae=()=>new Promise(e=>setTimeout(e,0));export async function analyzeWaferLotAsync(e,o={}){const{onProgress:s,signal:t,...a}=o,u=e.map(ee),r=se(u,a),c=[];let p=Date.now();for(let h=0;h<u.length;h++)t?.throwIfAborted(),c.push(a.perWaferSummaries?.[h]??F(u[h],a,r)),s?.(h+1,u.length),Date.now()-p>100&&(await ae(),p=Date.now());return await ae(),t?.throwIfAborted(),analyzeWaferLot(u,{...a,perWaferSummaries:c})}export function remapLotWaferIndices(e,o){const s=t=>o[t]??t;return{...e,perWafer:e.perWafer.map(t=>({...t,waferIndex:s(t.waferIndex)})),lotYieldSeries:e.lotYieldSeries.map(t=>({...t,waferIndex:s(t.waferIndex)})),...e.perWaferTestStats?{perWaferTestStats:e.perWaferTestStats.map(t=>({...t,waferIndex:s(t.waferIndex)}))}:{},findings:e.findings.map(t=>{const a=t.highlight;if(!a||a.kind!=="wafer")return t;const u=a.dieKeysByWafer?Object.fromEntries(Object.entries(a.dieKeysByWafer).map(([r,c])=>[s(Number(r)),c])):void 0;return{...t,highlight:{...a,waferIndices:a.waferIndices.map(s),...u?{dieKeysByWafer:u}:{}}}})}}
1
+ import{waferDisplayLabel as le}from"../core/waferLabel.js";import{requireRingCount as fe}from"../core/ringCount.js";import{isPositionedDie as de}from"../core/dies.js";import{analyzeWaferMapDecided as N,candidatesOf as Q,describeRegional as X,resolveOptions as ue,adjustPValues as me,testValueSize as pe,recordedOptions as ge,twoProportionZ as Z,welchOfSums as J,rateRelativeEffect as he,passesRateGate as ye,severityForFinding as ee,severityForScore as te,collapseRedundantFindings as we,findContiguousRuns as be,mergedRegionLabel as Se}from"./analyzeWaferMap.js";import{normalizeInput as ne}from"./normalizeInput.js";import{autoDecision as ve,lotTestValueStatus as ze}from"./testValueBudget.js";import{poolCapability as Ie,poolRegionYield as ke,poolPassRates as xe}from"./summaryFigures.js";import{mergeTestDefs as Pe}from"./mergeTestDefs.js";import{findingPatternKey as Re}from"./filterFindings.js";import{median as ie}from"../core/utils.js";import{robustFence as se,zPValue as q}from"./math.js";import{findLotPattern as Me}from"./lotPattern.js";import{buildDriftFindings as $e}from"./lotDrift.js";import{claimForPattern as De,confirmRegionalFindings as Be,weakestMultiplier as We}from"./analyzeWaferMap.js";import{PATTERN_LABELS as Le}from"./patternClassification.js";import{describeWaferPopulation as Ke,populationStat as Ee}from"./population.js";const O=8,Te={3:[.97,.994],4:[.829,.926],5:[.71,.821],6:[.625,.74],7:[.568,.68]},qe=3;export function outlierWafers(e){const s=e.length;if(s<3)return null;const i=ie([...e]),r=o=>Math.abs(o-i)>=qe;if(s>=O){const o=se(e,1.5,O),f=se(e,3,O);if(!o||!f)return null;const u=(o.hi-o.lo)/4,y=[];return e.forEach((w,v)=>{if(w>=o.lo&&w<=o.hi||!r(w))return;const n=w<f.lo||w>f.hi?"unusual":"notable";y.push({index:v,severity:n,statistic:(w-i)/u})}),{method:"tukey-fence",outliers:y}}const t=e.map((o,f)=>f).sort((o,f)=>e[o]-e[f]),d=e[t[s-1]]-e[t[0]];if(d===0)return null;const[l,c]=Te[s],m=[],h=(o,f)=>{const u=Math.abs(e[o]-e[f])/d;u>l&&r(e[o])&&m.push({index:o,severity:u>c?"unusual":"notable",statistic:u})};return h(t[0],t[1]),h(t[s-1],t[s-2]),{method:"dixon-q",outliers:m}}const A=2;function j(e,s){const i={info:0,notable:1,unusual:2};return i[e]>=i[s]?e:s}const Ae=new Set(["ring","quadrant","sector"]),Fe=new Set(["ring","quadrant","sector","reticle-position","test-site"]),Ne=new Set(["yield","hardBin","softBin","functionalTest","test"]);function Oe(e){return Fe.has(e.comparison.family)&&Ne.has(e.variable.kind)}function je(e,s){const i=e.map(l=>l.facts);if(!i.length||i.some(l=>!l))return{coincident:new Set,yieldSoftBin:void 0,passBins:[],sectorCount:s};const[r,...t]=i,d=t.every(l=>l.passBins.length===r.passBins.length&&l.passBins.every(c=>r.passBins.includes(c)));return{coincident:new Set([...r.coincident].filter(l=>t.every(c=>c.coincident.has(l)))),yieldSoftBin:t.every(l=>l.yieldSoftBin===r.yieldSoftBin)?r.yieldSoftBin:void 0,passBins:d?r.passBins:[],sectorCount:s}}function V(e,s){let i=0,r=0,t=0,d=0,l=0,c=0,m=0,h=0,o=0,f=!0,u=0;for(const{waferIndex:v,c:n}of e){const g=s(v,n),a=n.rate??n.mean,p=Math.sqrt(a.n+g.n);if(n.rate)i+=p*Z(n.rate.hits,n.rate.n,g.hits,g.n),t+=n.rate.hits,d+=n.rate.n,l+=g.hits,c+=g.n;else{const b=J(n.mean,g.n,g.sum,g.sq);i+=p*b.z,m+=n.mean.n*b.effectSize,h+=n.mean.n*b.delta,u+=n.mean.n,n.relativeDelta===void 0?f=!1:o+=n.mean.n*n.relativeDelta}r+=p*p}const y=r>0?i/Math.sqrt(r):0,w=e[0].c;if(w.rate){const v=l/c,n=t/d-v;return{z:y,delta:n,relativeDelta:v===0?void 0:n/v,size:he({hits:t,n:d,restHits:l,restN:c,passRate:w.rate.passRate})}}return{z:y,delta:h/u,relativeDelta:f?o/u:void 0,size:m/u}}function _(e,s,i,r){return e.rate?ye(s,i.delta,i.size,r):s<=r.significanceLevel&&Math.abs(i.size)>=r.minimumEffectSize}function Y(e,s){return s<e?` with positions, ${e-s} without`:""}function Ve(e,s,i,r,t){const d=new Map;for(const{waferIndex:n,byKey:g}of e)for(const a of g.values())(d.get(a.key)??d.set(a.key,[]).get(a.key)).push({waferIndex:n,c:a});const l=new Map(e.map(n=>[n.waferIndex,n.byKey])),c=(n,g)=>g.rate?{hits:g.rate.restHits,n:g.rate.restN,sum:0,sq:0}:{hits:0,n:g.mean.restN,sum:g.mean.restSum,sq:g.mean.restSq},m=[];for(const[n,g]of d){if(g.length<A)continue;const a=V(g,c);if(a.z===0)continue;const p=g[0].c;m.push({key:n,entries:g,combined:a,finding:{id:`lot-region:${n}`,level:"lot",severity:"info",variable:{...p.variable,label:p.label},comparison:{...p.comparison},effect:{direction:a.z>0?"higher":"lower",absoluteDelta:a.delta,relativeDelta:a.relativeDelta,effectSize:p.rate?a.delta:a.size},stats:{method:"stouffer-z",pValue:q(a.z),sampleSizeLeft:0,sampleSizeRight:0},summary:"",highlight:{kind:"wafer",waferIndices:[]}}})}me(m.map(n=>n.finding));const h=m.filter(n=>_(n.entries[0].c,n.finding.stats.adjustedPValue??1,n.combined,s)),u=Be(h,n=>{const g=n.entries[0].c;return[g.source,g.variable.kind,g.variable.bin??"",g.variable.index??"",g.region.family].join("\0")},(n,g)=>{const a=(M,B)=>{const k=c(M,B);for(const z of g){const R=l.get(M)?.get(z.key);R&&(R.rate?(k.hits-=R.rate.hits,k.n-=R.rate.n):(k.n-=R.mean.n,k.sum-=R.mean.sum,k.sq-=R.mean.sq))}return k},p=n.entries.filter(M=>a(M.waferIndex,M.c).n>=s.minimumSampleSize);if(!p.length)return"baseline-too-small";const b=V(p,a),x=n.finding.stats.pValue??1,P=x>0?(n.finding.stats.adjustedPValue??x)/x:1,S=Math.min(1,q(b.z)*P);return{pValue:S,passes:Math.sign(b.z)===Math.sign(n.combined.z)&&_(n.entries[0].c,S,b,s)}},n=>{const g=n.entries[0].c.rate;return g!==void 0&&(g.passRate?n.combined.z<0:n.combined.z>0)},m),y=[],w=new Map;for(const n of h){if(!u.has(n))continue;const g=n.finding.stats.pValue??1,a=Math.sign(n.combined.z),p=n.entries.filter(z=>Math.sign(z.c.delta)===a),b=t,x=n.entries[0].c,P=n.finding.stats.adjustedPValue??g,S=x.rate?ee(P,n.combined.delta,n.combined.size):te(P,n.combined.size),M=j(S,p.length/b>=.6?"unusual":"info"),B={};for(const z of p)B[z.waferIndex]=[...z.c.region.dieKeys];const k={...n.finding,severity:M,stats:{...n.finding.stats,sampleSizeLeft:p.length,sampleSizeRight:b-p.length},summary:`${X(x,n.combined.delta,n.combined.relativeDelta)} \u2014 ${n.finding.effect.direction} on ${p.length}/${b} wafers${Y(e.length,b)}, all wafers' data combined`,highlight:{kind:"wafer",waferIndices:p.map(z=>z.waferIndex),dieKeysByWafer:B}};y.push(k),w.set(k,n)}const v=_e(w,l,t,e.length,s,r,c);return y.splice(0,y.length,...y.filter(n=>!v.replaced.has(n)),...v.findings),we(y,i),y}function _e(e,s,i,r,t,d,l){const c=new Map;for(const[o,f]of e){const u=f.entries[0].c;if(!Ae.has(u.region.family))continue;const y=[u.source,u.variable.kind,u.variable.bin??"",u.variable.index??"",u.region.family,o.effect.direction].join("|");(c.get(y)??c.set(y,[]).get(y)).push({finding:o,c:u,key:f.key})}const m=[],h=new Set;for(const o of c.values()){if(o.length<2)continue;const f=o[0].c.region.family;for(const u of be(o,f,t.sectorCount,y=>y.c.region.key)){if(u.length<2)continue;const y=Ye(u,s,i,r,t,d,l);if(y){m.push(y);for(const w of u)h.add(w.finding)}}}return{findings:m,replaced:h}}function Ye(e,s,i,r,t,d,l){const c=e[0].c,m=e[0].finding.effect.direction==="higher"?1:-1,h=Se(c.region.family,e.map(S=>S.c.region.key),d),o=[];for(const[S,M]of s){const B=e.map(I=>M.get(I.key));if(B.some(I=>!I))continue;const k=B,z=k[0];let R,F;if(z.rate){const I=k.reduce((D,W)=>D+W.rate.hits,0),$=k.reduce((D,W)=>D+W.rate.n,0),K=z.rate.hits+z.rate.restHits-I,L=z.rate.n+z.rate.restN-$;if($<t.minimumSampleSize||L<t.minimumSampleSize)continue;R={...z,rate:{hits:I,n:$,restHits:K,restN:L,passRate:z.rate.passRate}},F=Z(I,$,K,L)}else{const I=z.mean,$=k.reduce((E,T)=>E+T.mean.n,0),K=k.reduce((E,T)=>E+T.mean.sum,0),L=k.reduce((E,T)=>E+T.mean.sq,0),D=I.n+I.restN-$,W=I.sum+I.restSum-K,C=I.sq+I.restSq-L;if($<t.minimumSampleSize||D<t.minimumSampleSize)continue;const G={n:$,sum:K,sq:L,restN:D,restSum:W,restSq:C,shift:I.shift},H=J(G,D,W,C),U=W/D+I.shift;R={...z,mean:G,relativeDelta:U!==0?H.delta/Math.abs(U):void 0},F=H.z}const ce=[...new Set(k.flatMap(I=>[...I.region.dieKeys]))];o.push({waferIndex:S,c:R,z:F,dieKeys:ce})}if(o.length<A)return;const f=V(o,l);if(f.z===0||Math.sign(f.z)!==m)return;const u=q(f.z),y=We(e.map(S=>S.finding)),w=Math.min(1,u*y);if(!_(c,w,f,t))return;const v=o.filter(S=>Math.sign(S.z)===m&&q(S.z)<=t.significanceLevel);if(!v.length)return;const n=c.rate?ee(w,f.delta,f.size):te(w,f.size),g=j(n,v.length/i>=.6?"unusual":"info"),a={};for(const S of v)a[S.waferIndex]=S.dieKeys;const p=e.map(S=>S.c.region.key.slice(S.c.region.key.indexOf(":")+1)).join("-"),b={...c,comparison:{...c.comparison,left:h}},x=e[0].finding,P=x.effect.direction;return{...x,id:`lot-region:${e[0].key.split("|").slice(0,-1).join("|")}|${c.region.family}:${p}`,severity:g,comparison:{...x.comparison,left:h},effect:{direction:P,absoluteDelta:f.delta,relativeDelta:f.relativeDelta,effectSize:c.rate?f.delta:f.size},stats:{method:"stouffer-z",pValue:u,adjustedPValue:w,sampleSizeLeft:v.length,sampleSizeRight:i-v.length},summary:`${X(b,f.delta,f.relativeDelta)} \u2014 ${P} on ${v.length}/${i} wafers${Y(r,i)}, all wafers' data combined`,highlight:{kind:"wafer",waferIndices:v.map(S=>S.waferIndex),dieKeysByWafer:a},relatedIds:e.map(S=>S.finding.id)}}const ae={"Edge-ring":"edge","Edge-local":"edge","Center cluster":"centre or donut",Donut:"centre or donut"};function Ce(e,s){const i=new Map,r=l=>{const c=l.variable.kind==="spatialPattern"?ae[l.comparison.left]:void 0;return c?`spatialPattern|${c}`:Re(l)};for(const l of e){const c=new Set,m=new Map;for(const o of l.summary.findings)if(o.variable.kind==="spatialPattern")for(const f of o.relatedIds??[])m.set(f,r(o));const h=new Set(l.summary.findings.flatMap(o=>o.absorbedIds??[]));for(const o of l.summary.findings){if(h.has(o.id)||Oe(o)||o.variable.kind==="spatialPattern"&&s?.carriers.has(l.waferIndex))continue;const f=r(o);if(c.has(f))continue;c.add(f);const u=i.get(f)??{finding:o,waferIndices:[],severity:o.severity,labels:new Map,dieKeysByWafer:{},explainedBy:new Map};u.waferIndices.push(l.waferIndex);const y=m.get(o.id);if(y&&u.explainedBy.set(y,(u.explainedBy.get(y)??0)+1),o.variable.kind==="spatialPattern"){u.labels.set(o.comparison.left,(u.labels.get(o.comparison.left)??0)+1);const w=o.highlight.dieKeys;w&&(u.dieKeysByWafer[l.waferIndex]=w)}u.severity=j(u.severity,o.severity),i.set(f,u)}}const t=[];for(const[l,c]of i){if(c.waferIndices.length<A)continue;const m=c.waferIndices.length/Math.max(1,e.length),h=m>=.6||c.severity==="unusual"?"unusual":"notable",o=c.finding;t.push({id:`lot-repeat:${l}`,level:"lot",severity:h,variable:{...o.variable},comparison:{...o.comparison},effect:{direction:o.effect.direction,absoluteDelta:o.effect.absoluteDelta,relativeDelta:o.effect.relativeDelta,effectSize:o.effect.effectSize},stats:{method:"wafer-finding-frequency",sampleSizeLeft:c.waferIndices.length,sampleSizeRight:e.length-c.waferIndices.length},summary:`${Ue(o,c.labels)} \u2014 seen on ${c.waferIndices.length}/${e.length} wafers (${Math.round(m*100)}%)`,highlight:{kind:"wafer",waferIndices:c.waferIndices,...c.labels.size?{dieKeysByWafer:c.dieKeysByWafer}:{}}})}const d=new Map(t.map(l=>[l.id,l]));for(const[l,c]of i){const m=d.get(`lot-repeat:${l}`);if(m)for(const[h,o]of c.explainedBy){const f=d.get(`lot-repeat:${h}`);!f||o!==c.waferIndices.length||(f.relatedIds??=[]).push(m.id)}}return t}function Ge(e,s,i){const{classification:r,carriers:t}=e,d=Le[r.pattern],l=t.size/Math.max(1,s),c={};for(const[m,h]of t)c[m]=h;return{id:"lot-repeat:spatialPattern|lot",level:"lot",severity:l>=.6||r.confidence==="high"?"unusual":"notable",variable:{kind:"spatialPattern",label:d},comparison:{family:"spatial-pattern",left:d,right:"Wafer"},effect:{direction:"different",effectSize:r.features.globalRdd},stats:{method:"wafer-finding-frequency",sampleSizeLeft:t.size,sampleSizeRight:s-t.size},summary:`Spatial pattern: ${d.toLowerCase()} \u2014 seen on ${t.size}/${s} wafers${Y(i,s)} (${Math.round(l*100)}%)`,highlight:{kind:"wafer",waferIndices:[...t.keys()].sort((m,h)=>m-h),dieKeysByWafer:c}}}function He(e){const s=/^Rings? (\d+)(?:\s*[–-]\s*(\d+))?/.exec(e.comparison.left);if(!s)return[];const i=+s[1],r=s[2]?+s[2]:i;return Array.from({length:Math.max(0,r-i+1)},(t,d)=>i+d)}function Ue(e,s){if(!s.size)return e.summary;const i=d=>d.toLowerCase();if(s.size===1)return`Spatial pattern: ${i([...s.keys()][0])}`;const r=ae[e.comparison.left],t=[...s].sort((d,l)=>l[1]-d[1]).map(([d,l])=>`${i(d)} on ${l}`);return`Spatial pattern: ${r} (${t.join(", ")})`}function Qe(e,s){const i=Ee(s,"median"),r=e.map(m=>({waferIndex:m.waferIndex,yieldPercent:m.summary.stats.yieldPercent})).filter(m=>m.yieldPercent!==null),t=r.map(m=>m.yieldPercent),d=outlierWafers(t);if(!d)return[];const l=ie(t),c=[];for(const{index:m,severity:h,statistic:o}of d.outliers){const f=r[m],u=f.yieldPercent-l,y=le({wafer:{metadata:e.find(w=>w.waferIndex===f.waferIndex)?.summary.wafer}},f.waferIndex);c.push({id:`inter-wafer:yield:${f.waferIndex}`,level:"inter-wafer",severity:h,variable:{kind:"yield",label:"Yield"},comparison:{family:"wafer",left:y,right:i.charAt(0).toUpperCase()+i.slice(1)},effect:{direction:u>0?"higher":"lower",absoluteDelta:u/100,relativeDelta:l===0?void 0:u/l,effectSize:o},stats:{method:d.method,sampleSizeLeft:1,sampleSizeRight:r.length-1},summary:`${y} yield is ${Math.abs(u).toFixed(1)} percentage points ${u>0?"higher":"lower"} than the ${i}`,highlight:{kind:"wafer",waferIndices:[f.waferIndex]}})}return c}function re(e,s){if((s.enableTestValueAnalysis??"auto")!=="auto")return;let i=0;for(const r of e){const{tests:t,dies:d}=pe(r,s);i+=t*d}return ve(i)}export function analyzeWaferLot(e,s={}){const i=e.map(ne),r=re(i,s),t=i.map((a,p)=>({waferIndex:p,summary:s.perWaferSummaries?.[p]??N(a,s,r)})),d=t.map(({waferIndex:a,summary:p})=>Q(p)??Q(N(i[a],s,r))),l=d.map((a,p)=>({waferIndex:p,byKey:new Map(a.candidates.map(b=>[b.key,b]))})),c=ue(s).resolved,m=i.filter(a=>a.dies.some(de)).length,h=i.length>0?fe(i[0],"analyzeWaferLot"):void 0,o=Me(i,c),f=o&&o.carriers.size>=A?o:null,u=[...h===void 0?[]:Ve(l,c,je(d,c.sectorCount),h,m),...Ce(t,f),...Qe(t,Ke(t.map(a=>a.summary.wafer))),...$e(t,c.significanceLevel)];if(f&&h!==void 0){const a=Ge(f,m,t.length);a.relatedIds=De([f.classification.pattern],a.severity,u,He,h),a.relatedIds.length||delete a.relatedIds,u.push(a)}u.sort((a,p)=>{const b=a.severity==="unusual"?2:a.severity==="notable"?1:0,x=p.severity==="unusual"?2:p.severity==="notable"?1:0;return b!==x?x-b:a.summary.localeCompare(p.summary,"en")});const y=t.map(a=>a.summary.wafer).filter(a=>!!a),w={},v=[];if(y.length>0){const a=new Set;for(const p of y)for(const b of Object.keys(p))a.add(b);a.delete("wafer"),a.delete("waferId");for(const p of a){const b=y.filter(P=>p in P).map(P=>P[p]);b.every(P=>P===b[0])?w[p]=b[0]:v.push(p)}}const n=t.map(({waferIndex:a,summary:p})=>({waferIndex:a,yieldPercent:p.stats.yieldPercent})),g=t.map(({waferIndex:a,summary:p})=>p.stats.perTestStats?.length?{waferIndex:a,tests:p.stats.perTestStats}:null).filter(a=>a!==null);return{level:"lot",hasNotableFindings:u.some(a=>a.severity!=="info")||t.some(a=>a.summary.hasNotableFindings),findings:u,lot:Object.keys(w).length>0?w:void 0,...v.length>0?{mixedIdentityFields:v}:{},analysisOptions:ge(s),stats:{waferCount:e.length,...Xe(i,t.map(a=>a.summary)),...Ze(ze(t.map(a=>a.summary)))},lotYieldSeries:n,perWafer:t,...g.length>0?{perWaferTestStats:g}:{}}}function Xe(e,s){const i={...xe(s)},r=Ie(s,Pe(e).defs);r&&(i.capability=r);const t=ke(s,e.map(d=>d.ringCount));return t&&(i.regionYield=t),i}const Ze=e=>e?{testValueAnalysis:e}:{},oe=()=>new Promise(e=>setTimeout(e,0));export async function analyzeWaferLotAsync(e,s={}){const{onProgress:i,signal:r,...t}=s,d=e.map(ne),l=re(d,t),c=[];let m=Date.now();for(let h=0;h<d.length;h++)r?.throwIfAborted(),c.push(t.perWaferSummaries?.[h]??N(d[h],t,l)),i?.(h+1,d.length),Date.now()-m>100&&(await oe(),m=Date.now());return await oe(),r?.throwIfAborted(),analyzeWaferLot(d,{...t,perWaferSummaries:c})}export function remapLotWaferIndices(e,s){const i=r=>s[r]??r;return{...e,perWafer:e.perWafer.map(r=>({...r,waferIndex:i(r.waferIndex)})),lotYieldSeries:e.lotYieldSeries.map(r=>({...r,waferIndex:i(r.waferIndex)})),...e.perWaferTestStats?{perWaferTestStats:e.perWaferTestStats.map(r=>({...r,waferIndex:i(r.waferIndex)}))}:{},findings:e.findings.map(r=>{const t=r.highlight;if(!t||t.kind!=="wafer")return r;const d=t.dieKeysByWafer?Object.fromEntries(Object.entries(t.dieKeysByWafer).map(([l,c])=>[i(Number(l)),c])):void 0;return{...r,highlight:{...t,waferIndices:t.waferIndices.map(i),...d?{dieKeysByWafer:d}:{}}}})}}
@@ -1 +1 @@
1
- import{normalizeInput as dt}from"./normalizeInput.js";import{autoDecision as mt,testValueStatus as ht}from"./testValueBudget.js";import{computeCapability as pt,computeTestFlagYield as gt,computeRegionYield as bt}from"./summaryFigures.js";import{binPassSets as Ke}from"../renderer/binColors.js";import{diePassStatus as oe,isYieldEligibleDie as X,getDieKey as de,isPositionedDie as Ae,positionKey as we}from"../core/dies.js";import{dieHasValues as yt,testsPresent as Te,testValue as W}from"../core/dieTable.js";import{stackBinsAreData as St}from"../core/aggregates.js";import{getTestPassStatus as me,isParametricTest as Z}from"../renderer/buildWaferMap.js";import{markedTestLabel as I,derivedFields as he}from"../renderer/testLabel.js";import{buildQuadrantRegions as vt,buildReticlePositionRegions as wt,buildRingRegions as $t,buildSectorRegions as Rt,buildTestSiteRegions as Dt,sectorCompassNames as qe,areQuadrantsAdjacent as Mt,parseRegionKey as J,QUADRANT_CYCLE as $e,regionAngleBins as kt}from"./regions.js";import{buildClusterFindings as Ie}from"./clusterDetection.js";import{classifyPattern as zt,patternExplains as Bt,patternFailVerdict as Ft,PATTERN_LABELS as Ct}from"./patternClassification.js";import{requirePassBins as Nt}from"../core/passBins.js";import{requireRingCount as xt}from"../core/ringCount.js";import{benjaminiHochberg as Pt,fisherExact as Vt,fiveNumberSummary as Et,sampleVariance as Re,zPValue as je}from"./math.js";import{mean as pe,maxOf as Lt}from"../core/utils.js";import{classifySpec as ge,isOutOfSpec as De}from"../renderer/spec.js";import{ringOf as Ot}from"../core/classify.js";import{SEVERITY_ORDER as He,isOneBinCluster as _e}from"./filterFindings.js";const Kt={significanceLevel:{min:1e-6,max:1},minimumEffectSize:{min:0,max:1},minimumRelativeEffect:{min:0,max:Number.MAX_SAFE_INTEGER}},We=[4,8,16];export function resolveOptions(e){const t=Object.fromEntries(Object.entries(e).filter(([,a])=>a!==void 0)),s={...ae,...t},o=[],i=[];for(const a of["significanceLevel","minimumEffectSize","minimumRelativeEffect"]){const{min:p,max:r}=Kt[a],u=s[a];if(typeof u!="number"||!Number.isFinite(u)){i.push(`${a}=${String(u)} is not a finite number (using ${ae[a]})`),s[a]=ae[a];continue}const c=Math.min(r,Math.max(p,u));c!==u&&(i.push(`${a}=${u} is outside ${p}\u2013${r} (using ${c})`),s[a]=c)}if(We.includes(s.sectorCount)||(i.push(`sectorCount=${s.sectorCount} is not one of ${We.join(", ")} (using ${ae.sectorCount})`),s.sectorCount=ae.sectorCount),i.length){const a=`analyzeWaferMap: ${i.join("; ")}. The analysis ran with the corrected values.`;console.warn(`[wafermap] ${a}`),o.push({code:"analysis-option-corrected",message:a,severity:"warning"})}const n=["passBins","ringCount"].filter(a=>t[a]!==void 0);if(n.length){const a=`analyzeWaferMap: ${n.join(" and ")} ${n.length>1?"are":"is"} no longer an analysis option and was ignored. Set ${n.length>1?"them":"it"} on buildWaferMap; the analysis used the value the map was built with.`;console.warn(`[wafermap] ${a}`),o.push({code:"analysis-option-corrected",message:a,severity:"warning"})}const f=["enableYieldAnalysis","enableHardBinAnalysis","enableSoftBinAnalysis","enableReticlePositionAnalysis","enableTestSiteAnalysis","enableClusterAnalysis","enableAngularAnalysis","enablePatternClassification"].filter(a=>t[a]!==void 0);if(f.length){const a=`analyzeWaferMap: ${f.join(", ")} ${f.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] ${a}`),o.push({code:"analysis-option-corrected",message:a,severity:"warning"})}return{resolved:s,warnings:o}}const ae={significanceLevel:.05,minimumEffectSize:.2,minimumRelativeEffect:1,minimumSampleSize:5,enableTestValueAnalysis:"auto",computePerTestStats:!1,sectorCount:8,minimumClusterSize:5};function At(e,t){const s={...e};return s.minimumClusterSize=Math.max(5,Math.round(t*.003)),s}function Ye(e){return X(e)?e.hbin!==void 0||e.sbin!==void 0||yt(e):!1}function Tt(e,t,s){if(!e||t)return;const o=(s??[]).filter(i=>Z(i)&&(i.limitLow!==void 0||i.limitHigh!==void 0));if(o.length!==0)return i=>{for(const n of o)if(De(ge(W(i,n.testNumber),n)))return!0;return!1}}const qt=8,It=.8,jt=.8,Ht=.5;function _t(e,t,s,o,i){const n=new Set(o.passBins),f=e.filter(m=>oe(m,n)!==void 0),a=new Map;let p=0;for(const m of f)oe(m,n)||(p++,m.hbin!==void 0&&a.set(m.hbin,(a.get(m.hbin)??0)+1));const r=[...a].filter(([,m])=>m>=o.minimumClusterSize&&m<=It*p).sort((m,l)=>l[1]-m[1]||m[0]-l[0]).slice(0,qt).map(([m])=>m);if(!r.length)return[];const u=i.filter(m=>m.comparison.family==="cluster").map(be),c=[];for(const m of r){const l=Ie(f,t,{...o,significanceLevel:o.significanceLevel/r.length,isFailingDie:d=>d.hbin===m,bin:{bin:m,label:Ce(m,s,"HBin")}});c.push(...l.filter(d=>!u.some(h=>Yt(be(d),h))))}return c}const Wt=.5;export function claimForBinClusters(e){const t=e.filter(s=>(s.comparison.family==="ring"||s.comparison.family==="quadrant"||s.comparison.family==="sector")&&s.variable.kind==="hardBin"&&s.effect.direction==="higher");for(const s of e){if(!_e(s))continue;const o=be(s),i=t.filter(n=>{if(n.variable.bin!==s.variable.bin||He[n.severity]<He[s.severity])return!1;const f=(n.effect.absoluteDelta??0)*n.stats.sampleSizeLeft;let a=0;for(const p of be(n))o.has(p)&&a++;return f>0&&a>=Wt*f});if(s.severity!=="info")for(const n of i)n.severity="info";i.length&&(s.relatedIds=i.map(n=>n.id))}}function be(e){return new Set("dieKeys"in e.highlight?e.highlight.dieKeys??[]:[])}function Yt(e,t){let s=0;for(const o of e)t.has(o)&&s++;return s>=jt*e.size&&e.size>=Ht*t.size}function Ut(e,t,s,o){const i=new Set,n=new Set,f=new Set,a=new Map,p=new Map;for(const r of Te(e))i.add(r);for(const r of o?e:[])r.hbin!==void 0&&n.add(r.hbin),r.sbin!==void 0&&f.add(r.sbin),X(r)&&(r.hbin!==void 0&&a.set(r.hbin,(a.get(r.hbin)??0)+1),r.sbin!==void 0&&p.set(r.sbin,(p.get(r.sbin)??0)+1));return{totalDies:e.length,analyzedDies:t,excludedDies:e.length-t,yieldPercent:s,testsConsidered:[...i].sort((r,u)=>r-u),hardBinsConsidered:[...n].sort((r,u)=>r-u),softBinsConsidered:[...f].sort((r,u)=>r-u),...a.size?{hardBinCounts:Object.fromEntries(a)}:{},...p.size?{softBinCounts:Object.fromEntries(p)}:{}}}function Qt(e,t,s){if(!t?.length)return;const o=t.filter(n=>Z(n)&&(n.limitLow!==void 0||n.limitHigh!==void 0));if(!o.length)return;const i=[];for(const n of o){const f=n.testNumber;let a=0,p=0,r=0,u=0;for(const c of e){if(!X(c))continue;const m=ge(W(c,f),n);if(m!==null){if(u++,m==="failLow")p++;else if(m==="failHigh")r++;else{a++;continue}s?.(f,c)}}i.push({testNumber:f,label:I(n,f),passDies:a,failLowDies:p,failHighDies:r,totalDies:u,yieldPercent:u>0?a/u*100:null})}return i.length?i:void 0}export function computeFunctionalYield(e,t,s){if(!t?.length)return;const o=t.filter(n=>!Z(n));if(!o.length)return;const i=[];for(const n of o){const f=n.testNumber;let a=0,p=0;for(const u of e){if(!X(u))continue;const c=me(u,f,n);if(c!==void 0){if(c){a++;continue}p++,s?.(f,u)}}const r=a+p;i.push({testNumber:f,label:I(n,f),...he(n),passDies:a,failDies:p,totalDies:r,passRatePercent:r>0?a/r*100:null})}return i.length?i:void 0}function Gt(e,t,s,o){const i=[];for(const n of t){const f=[];for(const c of e){if(!X(c))continue;const m=W(c,n);m!==void 0&&Number.isFinite(m)&&f.push(m)}if(f.length<o)continue;const a=pe(f),p=Math.sqrt(Re(f,a)),r=Et(Float64Array.from(f)),u=s?.find(c=>c.testNumber===n)?.name??String(n);i.push({testNumber:n,label:u,count:f.length,min:r.min,max:r.max,mean:a,stddev:p,median:r.median,q1:r.q1,q3:r.q3})}return i.length?i:void 0}export function twoProportionZ(e,t,s,o){const i=(e+s)/(t+o),n=i*(1-i)*(1/t+1/o);return!Number.isFinite(n)||n<=0?0:(e/t-s/o)/Math.sqrt(n)}const Xt=5;function j(e,t,s,o){const i=t+o,n=e+s;if((i>0?Math.min(n,i-n)*Math.min(t,o)/i:0)<Xt)return{pValue:Vt(e,t-e,s,o-s),method:"fisher-exact"};const a=twoProportionZ(e,t,s,o);return{pValue:a===0?1:je(a),method:"two-proportion-z"}}function Zt(e,t,s,o){return j(e,t,s,o).pValue}export function adjustPValues(e){const t=e.filter(o=>o.stats.pValue!==void 0),s=Pt(t.map(o=>o.stats.pValue));return t.forEach((o,i)=>{o.stats.adjustedPValue=s[i]}),e}export function rateRelativeEffect(e){const t=(e.passRate?e.n-e.hits:e.hits)/e.n,s=(e.passRate?e.restN-e.restHits:e.restHits)/e.restN;return s===0?t===0?0:1/0:Math.abs(t-s)/s}export function severityForFinding(e,t,s){const o=Math.abs(t),i=s;return e<=.01&&(o>=.3||i>=2.5)?"unusual":e<=.05&&(o>=.2||i>=1.5)?"notable":"info"}export function severityForScore(e,t){return e<=.01&&Math.abs(t)>=.5?"unusual":e<=.05&&Math.abs(t)>=.15?"notable":"info"}function ye(e){return e==="reticle-position"?"other reticle positions":e==="test-site"?"other test sites":"the rest of the map"}function ee(e){return e==="reticle-position"?"Other reticle positions":e==="test-site"?"Other test sites":"Rest of map"}function Me(e,t,s){const o=(Math.abs(t)*100).toFixed(1);return`${e} yield is ${o} percentage points ${t>0?"higher":"lower"} than ${ye(s)}`}function ke(e,t){return t==="quadrant"&&!e.startsWith("Quadrant")?`quadrant ${e}`:e}function Ue(e){return/^(Rings|Sectors|Quadrants)\b/.test(e)?"have":"has"}function ze(e,t,s,o){const i=ke(e,o),n=(Math.abs(s)*100).toFixed(1);return`${i} ${Ue(i)} ${t} occurrence ${n} percentage points ${s>0?"higher":"lower"} than ${ye(o)}`}function Be(e,t,s,o){const i=ke(e,o),n=(Math.abs(s)*100).toFixed(1);return`${i} ${Ue(i)} ${t} pass rate ${n} percentage points ${s>0?"higher":"lower"} than ${ye(o)}`}function Fe(e,t,s,o,i,n){const f=ke(e,i),a=ye(i),p=s>0?"higher":"lower";if(o!==void 0&&Number.isFinite(o)){const u=(Math.abs(o)*100).toFixed(1);return`${f} mean ${t} is ${u}% ${p} than ${a}`}const r=n?` ${n}`:"";return`${f} mean ${t} is ${Math.abs(s).toPrecision(3)}${r} ${p} than ${a}`}function Ce(e,t,s){const o=t?.find(i=>i.bin===e);return o?.name?`${s} ${e} (${o.name})`:`${s} ${e}`}function Jt(e,t){const s=t?.find(o=>o.testNumber===e);return{label:I(s,e),unit:s?.unit,...he(s)}}const Qe=new WeakMap,Ge=new WeakMap,Xe=new WeakMap;function re(e,t){const s=t.highlight.dieKeys;return s&&Xe.set(s,e),t}let te=null,fe;const Ze=new WeakMap;export function candidatesOf(e){return Ze.get(e)}function Je(e,t,s,o){if(!te)return;const i=et(e);if(!i)return;const n=e.id.slice(0,e.id.indexOf(":")),f=n==="specLimit"?"limitFail":n,{kind:a,bin:p,index:r}=e.variable;te.push({key:[f,a,p??"",r??"",i.family,i.key].join("|"),source:f,variable:e.variable,label:e.variable.label,comparison:e.comparison,region:i,z:t,delta:e.effect.absoluteDelta??0,effectSize:e.effect.effectSize??0,relativeDelta:e.effect.relativeDelta,rate:s,mean:o})}export function describeRegional(e,t,s){const o=e.comparison.left,i=e.region.family;switch(e.source){case"yield":return Me(o,t,i);case"hardBin":case"softBin":return ze(o,e.label,t,i);case"functional":return Be(o,e.label.replace(/ pass rate$/,""),t,i);case"limitFail":return Ne(o,e.label,t);case"test":return Fe(o,e.label,t,s,i,e.variable.unit)}}function Ne(e,t,s){return`${e} limit fail rate for ${t} is ${(Math.abs(s)*100).toFixed(1)} pp ${s>0?"higher":"lower"} than the rest of the wafer`}const Y=new WeakMap;function Se(e,t){return Y.set(e,t),e}function et(e){const t=e.highlight.dieKeys;return t?Xe.get(t):void 0}const tt=new WeakMap;function U(e){let t=tt.get(e);return t||tt.set(e,t=e.map(we)),t}function en(e){let t=Qe.get(e);return t||Qe.set(e,t=e.map(de)),t}function ve(e,t){let s=Ge.get(e);s||Ge.set(e,s={members:new Set(e),byFamily:new WeakMap});const o=s.byFamily.get(t);if(o)return o;const{members:i}=s,n=new Map;for(const f of t)n.set(f.key,f.dies.filter(a=>i.has(a)));return s.byFamily.set(t,n),n}function tn(e,t){adjustPValues(e);for(const i of e){const n=Y.get(i);Je(i,twoProportionZ(n.hits,n.n,n.restHits,n.restN),n)}const s=e.filter(i=>passesRateGate(i.stats.adjustedPValue??i.stats.pValue??1,i.effect.absoluteDelta??0,rateRelativeEffect(Y.get(i)),t)),o=confirmRegionalFindings(s,nt,(i,n)=>nn(i,n,t),i=>isRateLoss(Y.get(i)),e);return s.filter(i=>o.has(i)).map(i=>({...i,severity:severityForFinding(i.stats.adjustedPValue??i.stats.pValue??1,i.effect.absoluteDelta??0,rateRelativeEffect(Y.get(i)))}))}export function passesRateGate(e,t,s,o){return e<=o.significanceLevel&&(Math.abs(t)>=o.minimumEffectSize||s>=o.minimumRelativeEffect)}export function claimForPattern(e,t,s,o,i){const n=[];for(const f of s){const a=f.comparison.family,p=a==="ring"||a==="cluster"?o(f):[];e.some(r=>Bt(r,a,p,i))&&(n.push(f.id),t!=="info"&&(a==="ring"||a==="quadrant"||a==="sector")&&(f.severity="info"))}return n}export function confirmRegionalFindings(e,t,s,o,i=e){const n=new Map;for(const p of e)(n.get(t(p))??n.set(t(p),[]).get(t(p))).push(p);const f=new Map;if(o)for(const p of i)o(p)&&(f.get(t(p))??f.set(t(p),[]).get(t(p))).push(p);const a=new Set;for(const[p,r]of n){const u=f.get(p)??[],c=(d,h)=>o&&!o(d)?s(d,[...new Set([...h,...u])].filter(g=>g!==d)):s(d,h);if(r.length===1&&(!o||o(r[0])||u.length===0)){a.add(r[0]);continue}const m=[];let l=[...r];for(;;){let d;for(const h of l){const g=c(h,m);if(g==="baseline-too-small"||!g.passes)continue;const v=o?.(h)??!1;(!d||v&&!d.loss||v===d.loss&&g.pValue<d.p)&&(d={t:h,p:g.pValue,loss:v})}if(!d)break;m.push(d.t),l=l.filter(h=>h!==d.t)}for(;;){let d;for(const h of m){const g=c(h,m.filter(v=>v!==h));g==="baseline-too-small"||g.passes||(!d||g.pValue>d.p)&&(d={t:h,p:g.pValue})}if(!d)break;m.splice(m.indexOf(d.t),1)}for(const d of m)a.add(d)}return a}function nt(e){return[e.variable.kind,e.variable.bin??"",e.variable.index??"",e.comparison.family].join("\0")}function it(e){const t=e.stats.pValue??1;return t>0?(e.stats.adjustedPValue??t)/t:1}export function isRateLoss(e){const t=e.hits/e.n-e.restHits/e.restN;return e.passRate?t<0:t>0}function nn(e,t,s){const o=Y.get(e);let{restHits:i,restN:n}=o;for(const r of t){const u=Y.get(r);u&&(i-=u.hits,n-=u.n)}if(n<s.minimumSampleSize)return"baseline-too-small";const f=o.hits/o.n-i/n,a=Math.min(1,Zt(o.hits,o.n,i,n)*it(e)),p=Math.sign(f)===Math.sign(e.effect.absoluteDelta??0)&&passesRateGate(a,f,rateRelativeEffect({...o,restHits:i,restN:n}),s);return{pValue:a,passes:p}}const xe=new WeakMap;export function welchOfSums(e,t,s,o){const i=(n,f,a)=>a>1?Math.max(0,n-f*f/a)/(a-1):0;return welchFromStats(e.n,e.sum/e.n,i(e.sq,e.sum,e.n),t,s/t,i(o,s,t))}function sn(e,t,s){const o=xe.get(e);let{restN:i,restSum:n,restSq:f}=o;for(const m of t){const l=xe.get(m);l&&(i-=l.n,n-=l.sum,f-=l.sq)}if(i<s.minimumSampleSize)return"baseline-too-small";const{pValue:a,effectSize:p,delta:r}=welchOfSums(o,i,n,f),u=Math.min(1,a*it(e)),c=Math.sign(r)===Math.sign(e.effect.absoluteDelta??0)&&u<=s.significanceLevel&&Math.abs(p)>=s.minimumEffectSize;return{pValue:u,passes:c}}function le(e,t,s,o){const i=new Set(s),n=ve(e,t),f=new Map,a=new Map;for(const[r,u]of n){let c=0,m=0;for(const l of u)l.hbin!==void 0&&(m++,i.has(l.hbin)&&c++);f.set(r,c),a.set(r,m)}const p=[];for(const r of t){const u=a.get(r.key)??0,c=f.get(r.key)??0;let m=0,l=0;for(const[D,w]of a)D!==r.key&&(m+=w,l+=f.get(D)??0);if(u<o.minimumSampleSize||m<o.minimumSampleSize)continue;const d=c/u,h=l/m,g=d-h,{pValue:v,method:F}=j(c,u,l,m);p.push(Se(re(r,{id:`yield:${r.key}`,level:"wafer",severity:"info",variable:{kind:"yield",label:"Yield"},comparison:{family:r.family,left:r.label,right:ee(r.family)},effect:{direction:g===0?"different":g>0?"higher":"lower",absoluteDelta:g,relativeDelta:h===0?void 0:g/h,effectSize:g},stats:{method:F,pValue:v,sampleSizeLeft:u,sampleSizeRight:m},summary:Me(r.label,g,r.family),highlight:{kind:"region",regionFamily:r.family,regionKeys:[r.key],dieKeys:[...r.dieKeys]}}),{hits:c,n:u,restHits:l,restN:m,passRate:!0}))}return p}function q(e,t,s,o,i,n){const f=d=>s==="soft"?d.sbin:d.hbin,a=[...new Set(e.map(f).filter(d=>d!==void 0))].sort((d,h)=>d-h),p=ve(e,t),r=new Map,u=new Map;for(const[d,h]of p){const g=new Map;for(const v of h){const F=f(v);F!==void 0&&g.set(F,(g.get(F)??0)+1)}r.set(d,g),u.set(d,h.length)}const c=[],m=i==="hardBin"?"HBin":"SBin",l=s==="hard"?new Set(n.passBins):n.softPassBins??Ke(e,n.passBins).soft;for(const d of t){const h=u.get(d.key)??0,g=r.get(d.key);let v=0;const F=new Map;for(const[D,w]of r)if(D!==d.key){v+=u.get(D)??0;for(const[B,z]of w)F.set(B,(F.get(B)??0)+z)}if(!(h<n.minimumSampleSize||v<n.minimumSampleSize))for(const D of a){const w=g.get(D)??0,B=F.get(D)??0,z=w/h,b=B/v,$=z-b,{pValue:M,method:S}=j(w,h,B,v),R=Ce(D,o,m);c.push(Se(re(d,{id:`${i}:${D}:${d.key}`,level:"wafer",severity:"info",variable:{kind:i,bin:D,label:R},comparison:{family:d.family,left:d.label,right:ee(d.family)},effect:{direction:$===0?"different":$>0?"higher":"lower",absoluteDelta:$,relativeDelta:b===0?void 0:$/b,effectSize:$},stats:{method:S,pValue:M,sampleSizeLeft:h,sampleSizeRight:v},summary:ze(d.label,R,$,d.family),highlight:{kind:"bin",bin:D,regionKeys:[d.key],dieKeys:[...d.dieKeys]}}),{hits:w,n:h,restHits:B,restN:v,passRate:l.has(D)}))}}return c}function ce(e,t,s,o){const i=(s??[]).filter(u=>!Z(u));if(!i.length)return[];const n=i.map(u=>u.testNumber),f=ve(e,t),a=new Map,p=new Map;for(const[u,c]of f){const m=new Uint32Array(i.length),l=new Uint32Array(i.length);for(const d of c)for(let h=0;h<i.length;h++){const g=me(d,n[h],i[h]);g!==void 0&&(l[h]++,g&&m[h]++)}a.set(u,m),p.set(u,l)}const r=[];for(const u of t){const c=a.get(u.key),m=p.get(u.key);for(let l=0;l<i.length;l++){let d=0,h=0;for(const[$,M]of p)$!==u.key&&(h+=M[l],d+=a.get($)[l]);const g=m[l],v=c[l];if(g<o.minimumSampleSize||h<o.minimumSampleSize)continue;const F=v/g,D=d/h,w=F-D,{pValue:B,method:z}=j(v,g,d,h),b=n[l];r.push(Se(re(u,{id:`functional:${b}:${u.key}`,level:"wafer",severity:"info",variable:{kind:"functionalTest",index:b,label:`${I(i[l],b)} pass rate`,...he(i[l])},comparison:{family:u.family,left:u.label,right:ee(u.family)},effect:{direction:w===0?"different":w>0?"higher":"lower",absoluteDelta:w,relativeDelta:D===0?void 0:w/D,effectSize:w},stats:{method:z,pValue:B,sampleSizeLeft:g,sampleSizeRight:h},summary:Be(u.label,I(i[l],b),w,u.family),highlight:{kind:"region",regionFamily:u.family,regionKeys:[u.key],dieKeys:[...u.dieKeys]}}),{hits:v,n:g,restHits:d,restN:h,passRate:!0}))}}return r}export function welchFromStats(e,t,s,o,i,n){const f=Math.sqrt(s/e+n/o),a=t-i;if(!Number.isFinite(f)||f===0)return{pValue:1,effectSize:0,delta:a,z:0};const p=a/f,r=Math.sqrt(Math.max(0,(s+n)/2)),u=r===0?a:a/r;return{pValue:je(p),effectSize:u,delta:a,z:p}}function on(e,t){const s=pe(e),o=pe(t);return welchFromStats(e.length,s,Re(e,s),t.length,o,Re(t,o))}function st(e,t,s){const o=new Map;for(const n of s??[])o.has(n.testNumber)||o.set(n.testNumber,n);const i=n=>n.filter(f=>Z(o.get(f)));return i(t?t.slice().sort((n,f)=>n-f):Te(e,"values"))}export function testValueSize(e,t){const s=e.dies.filter(Ye);return{tests:st(s,t.testNumbers,e.testDefs).length,dies:s.length}}export function recordedOptions(e){const t={};return e.enableTestValueAnalysis!==void 0&&(t.enableTestValueAnalysis=e.enableTestValueAnalysis),e.computePerTestStats!==void 0&&(t.computePerTestStats=e.computePerTestStats),e.sectorCount!==void 0&&(t.sectorCount=e.sectorCount),e.testNumbers!==void 0&&(t.testNumbers=[...e.testNumbers]),t}function an(e,t,s,o,i){const n=new Map;for(let h=0;h<t.length;h++)for(const g of U(t[h].dies))n.set(g,h);const f=t.length,a=[],p=[];for(const h of e){const g=n.get(we(h));g!==void 0&&(a.push(h),p.push(g))}const r=[],u=new Float64Array(f),c=new Float64Array(f),m=new Float64Array(f);for(const h of s){u.fill(0),c.fill(0),m.fill(0);let g=0,v=0,F=0,D;for(let w=0;w<a.length;w++){const B=a[w],z=W(B,h);if(z===void 0)continue;D===void 0&&(D=z);const b=z-D,$=p[w];u[$]+=1,c[$]+=b,m[$]+=b*b,g+=1,v+=b,F+=b*b}if(D!==void 0)for(let w=0;w<f;w++){const B=u[w],z=g-B;if(B<i.minimumSampleSize||z<i.minimumSampleSize)continue;const b=c[w]/B,M=(v-c[w])/z,S=b+D,R=M+D,P=B>1?Math.max(0,m[w]-B*b*b)/(B-1):0,C=z>1?Math.max(0,F-m[w]-z*M*M)/(z-1):0,{pValue:V,effectSize:x,delta:k,z:O}=welchFromStats(B,S,P,z,R,C),N=t[w],{label:K,unit:E,...Q}=Jt(h,o),H=R!==0?k/Math.abs(R):void 0,G=re(N,{id:`test:${h}:${N.key}`,level:"wafer",severity:"info",variable:{kind:"test",measure:"mean",index:h,label:K,unit:E,...Q},comparison:{family:N.family,left:N.label,right:ee(N.family)},effect:{direction:k===0?"different":k>0?"higher":"lower",absoluteDelta:k,relativeDelta:H,effectSize:x},stats:{method:"welch-z-approx",pValue:V,sampleSizeLeft:B,sampleSizeRight:z},summary:Fe(N.label,K,k,H,N.family,E),highlight:{kind:"region",regionFamily:N.family,regionKeys:[N.key],dieKeys:[...N.dieKeys]}}),y={n:B,sum:c[w],sq:m[w],restN:z,restSum:v-c[w],restSq:F-m[w],shift:D};xe.set(G,y),Je(G,O,void 0,y),r.push(G)}}adjustPValues(r);const l=r.filter(h=>{const g=h.stats.adjustedPValue??h.stats.pValue??1,v=Math.abs(h.effect.effectSize??0);return g<=i.significanceLevel&&v>=i.minimumEffectSize}),d=confirmRegionalFindings(l,nt,(h,g)=>sn(h,g,i));return l.filter(h=>d.has(h)).map(h=>({...h,severity:severityForScore(h.stats.adjustedPValue??h.stats.pValue??1,h.effect.effectSize??0)}))}function rn(e,t,s,o){if(!s?.length)return[];const i=s.filter(f=>Z(f)&&(f.limitLow!==void 0||f.limitHigh!==void 0));if(!i.length)return[];const n=[];for(const f of i){const a=f.testNumber;for(const p of t){const r=ve(e,p),u=[],c=new Map;let m=0,l=0;for(const[d,h]of r){let g=0,v=0;for(const F of h){const D=W(F,a);D!==void 0&&(g++,De(ge(D,f))&&v++)}c.set(d,{valid:g,fail:v}),m+=g,l+=v}for(const d of p){const h=c.get(d.key),g=h.valid,v=m-h.valid;if(g<o.minimumSampleSize||v<o.minimumSampleSize)continue;const F=h.fail,D=l-h.fail,w=F/g,B=D/v,z=w-B,{pValue:b,method:$}=j(F,g,D,v);u.push(Se(re(d,{id:`specLimit:${a}:${d.key}`,level:"wafer",severity:"info",variable:{kind:"test",measure:"limitFailRate",index:a,label:I(f,a),...he(f)},comparison:{family:d.family,left:d.label,right:ee(d.family)},effect:{direction:z===0?"different":z>0?"higher":"lower",absoluteDelta:z,relativeDelta:B===0?void 0:z/B,effectSize:z},stats:{method:$,pValue:b,sampleSizeLeft:g,sampleSizeRight:v},summary:Ne(d.label,I(f,a),z),highlight:{kind:"region",regionFamily:d.family,regionKeys:[d.key],dieKeys:[...d.dieKeys]}}),{hits:F,n:g,restHits:D,restN:v,passRate:!1}))}n.push(...u)}}return n}function Pe(e,t){return e==="softBin"?t.softEligibleDies:e==="test"?t.testDies:t.eligibleDies}function fn(e){return e.variable.measure==="limitFailRate"}function ue(e){return e.highlight.regionKeys??[]}function ln(e){const t=e.variable.bin??e.variable.index??"";return`${e.comparison.family}\0${ot(e)}\0${e.variable.kind}\0${t}\0${e.effect.direction}`}function cn(e,t){const s=J(e);return s.family==="ring"?s.ring??0:s.family==="sector"?qe(t).indexOf(s.sector??""):0}export function inQuadrantOrder(e){const t=new Set(e),s=$e.findIndex((i,n)=>t.has(i)&&!t.has($e[(n+3)%4])),o=s<0?0:s;return Array.from({length:4},(i,n)=>$e[(o+n)%4]).filter(i=>t.has(i))}export function findContiguousRuns(e,t,s,o){if(t==="quadrant"){const p=new Map;for(const m of e){const l=J(o(m)).quadrant;l&&p.set(l,m)}const r=[...p.keys()],u=new Set,c=[];for(const m of r){if(u.has(m))continue;const l=[],d=[m];for(u.add(m);d.length;){const h=d.pop();l.push(h);for(const g of r)!u.has(g)&&Mt(h,g)&&(u.add(g),d.push(g))}c.push(inQuadrantOrder(l).map(h=>p.get(h)))}return c}const i=p=>cn(o(p),s),n=[...e].sort((p,r)=>i(p)-i(r)),f=[];let a=[];for(const p of n){if(a.length===0){a.push(p);continue}const r=i(a[a.length-1]);i(p)-r===1?a.push(p):(f.push(a),a=[p])}if(a.length&&f.push(a),t==="sector"&&f.length>1){const r=qe(s).length,u=i(f[0][0]),c=i(f[f.length-1][f[f.length-1].length-1]);if(u===0&&c===r-1){const m=f.pop();f[0]=[...m,...f[0]]}}return f}export function mergedRegionLabel(e,t,s){if(e==="ring"){const i=t.map(p=>J(p).ring).filter(p=>p!==void 0).sort((p,r)=>p-r),n=i[0],f=i[i.length-1];let a="";return n===f&&n===1&&s>1?a=" (core)":n===f&&n===s&&s>1&&(a=" (edge)"),n===f?`Ring ${n}${a}`:`Rings ${n}\u2013${f}`}if(e==="sector"){const i=t.map(n=>J(n).sector??"");return i.length===1?`Sector ${i[0]}`:`Sectors ${i[0]}\u2013${i[i.length-1]}`}const o=t.map(i=>J(i).quadrant??"");return o.length===1?o[0]:o.length===2?`Quadrants ${o[0]} & ${o[1]}`:`Quadrants ${o.slice(0,-1).join(", ")} & ${o[o.length-1]}`}function Ve(e){return[...new Set(e)]}export function weakestMultiplier(e){return Lt(e.map(t=>{const s=t.stats.pValue??1;return s>0?(t.stats.adjustedPValue??s)/s:1}))}function ne(e,t){return Math.min(1,e*t)}function un(e,t){const s=e[0],o=s.comparison.family,i=s.variable.kind,n=Ve(e.flatMap(ue));let f,a;const p=e.map(et);if(p.every(b=>b!==void 0)){const b=new Set;f=[];for(const M of p){const S=U(M.dies);for(let R=0;R<S.length;R++)b.has(S[R])||(b.add(S[R]),f.push(M.dieKeys[R]))}const $=U(Pe(s.variable.kind,t));a=M=>b.has($[M])}else{f=Ve(e.flatMap(M=>M.highlight.dieKeys??[]));const b=new Set(f),$=en(Pe(s.variable.kind,t));a=M=>b.has($[M])}const r=mergedRegionLabel(o,e.map(b=>ue(b)[0]??""),t.ringCount),u=Pe(i,t),c=t.regionDies[o],m=U(u),l=[],d=[];for(let b=0;b<u.length;b++)c.has(m[b])&&(a(b)?l:d).push(u[b]);const h=weakestMultiplier(e);let g,v,F,D,w;if(fn(s)){const b=s.variable.index,$=t.testDefs?.find(N=>N.testNumber===b),M=N=>{let K=0,E=0;for(const Q of N){const H=W(Q,b);H!==void 0&&(K++,$&&De(ge(H,$))&&E++)}return{valid:K,fail:E}},S=M(l),R=M(d),P=S.valid>0?S.fail/S.valid:0,C=R.valid>0?R.fail/R.valid:0,V=P-C,{pValue:x,method:k}=j(S.fail,S.valid,R.fail,R.valid);g={direction:V===0?"different":V>0?"higher":"lower",absoluteDelta:V,relativeDelta:C===0?void 0:V/C,effectSize:V},v={method:k,pValue:x,sampleSizeLeft:S.valid,sampleSizeRight:R.valid};const O=ne(x,h);F=severityForFinding(O,V,rateRelativeEffect({hits:S.fail,n:S.valid,restHits:R.fail,restN:R.valid,passRate:!1})),D=Ne(r,I($,b),V),w=`specLimit:${b}`}else if(i==="test"){const b=s.variable.index,$=O=>W(O,b),M=l.map($).filter(O=>O!==void 0),S=d.map($).filter(O=>O!==void 0),{pValue:R,effectSize:P,delta:C}=on(M,S),V=pe(S),x=V!==0?C/Math.abs(V):void 0;g={direction:C===0?"different":C>0?"higher":"lower",absoluteDelta:C,relativeDelta:x,effectSize:P},v={method:"welch-z-approx",pValue:R,sampleSizeLeft:M.length,sampleSizeRight:S.length};const k=ne(R,h);F=severityForScore(k,P),D=Fe(r,s.variable.label,C,x,o,s.variable.unit),w=`test:${b}`}else if(i==="yield"){const b=new Set(t.passBins),$=l.filter(E=>E.hbin!==void 0),M=d.filter(E=>E.hbin!==void 0),S=$.length,R=M.length,P=$.filter(E=>b.has(E.hbin)).length,C=M.filter(E=>b.has(E.hbin)).length,V=S>0?P/S:0,x=R>0?C/R:0,k=V-x,{pValue:O,method:N}=j(P,S,C,R);g={direction:k===0?"different":k>0?"higher":"lower",absoluteDelta:k,relativeDelta:x===0?void 0:k/x,effectSize:k},v={method:N,pValue:O,sampleSizeLeft:S,sampleSizeRight:R};const K=ne(O,h);F=severityForFinding(K,k,rateRelativeEffect({hits:P,n:S,restHits:C,restN:R,passRate:!0})),D=Me(r,k,o),w="yield"}else if(i==="functionalTest"){const b=s.variable.index,$=t.testDefs?.find(K=>K.testNumber===b);let M=0,S=0,R=0,P=0;for(const K of l){const E=me(K,b,$);E!==void 0&&(S++,E&&M++)}for(const K of d){const E=me(K,b,$);E!==void 0&&(P++,E&&R++)}const C=S>0?M/S:0,V=P>0?R/P:0,x=C-V,{pValue:k,method:O}=j(M,S,R,P);g={direction:x===0?"different":x>0?"higher":"lower",absoluteDelta:x,relativeDelta:V===0?void 0:x/V,effectSize:x},v={method:O,pValue:k,sampleSizeLeft:S,sampleSizeRight:P};const N=ne(k,h);F=severityForFinding(N,x,rateRelativeEffect({hits:M,n:S,restHits:R,restN:P,passRate:!0})),D=Be(r,I($,b),x,o),w=`functional:${b}`}else{const b=s.variable.bin,$=N=>i==="softBin"?N.sbin:N.hbin,M=l.filter(N=>$(N)===b).length,S=d.filter(N=>$(N)===b).length,R=M/l.length,P=S/d.length,C=R-P,{pValue:V,method:x}=j(M,l.length,S,d.length);g={direction:C===0?"different":C>0?"higher":"lower",absoluteDelta:C,relativeDelta:P===0?void 0:C/P,effectSize:C},v={method:x,pValue:V,sampleSizeLeft:l.length,sampleSizeRight:d.length};const k=ne(V,h);F=severityForFinding(k,C,rateRelativeEffect({hits:M,n:l.length,restHits:S,restN:d.length,passRate:!1}));const O=i==="softBin"?t.sbinDefs:t.hbinDefs;D=ze(r,Ce(b,O,i==="softBin"?"SBin":"HBin"),C,o),w=`${i}:${b}`}v={...v,adjustedPValue:ne(v.pValue??1,h)};const B=Ve(n.map(b=>b.replace(`${o}:`,""))).join("-"),z=i==="hardBin"||i==="softBin"?{kind:"bin",bin:s.variable.bin,regionKeys:n,dieKeys:f}:{kind:"region",regionFamily:o,regionKeys:n,dieKeys:f};return{...s,id:`${w}:${o}:${B}`,severity:F,comparison:{family:o,left:r,right:ee(o)},effect:g,stats:v,summary:D,highlight:z,relatedIds:e.map(b=>b.id)}}function dn(e,t){const s=new Set(["ring","quadrant","sector"]),o=[],i=new Map;for(const f of e){if(!s.has(f.comparison.family)){o.push(f);continue}const a=ln(f),p=i.get(a)??[];p.push(f),i.set(a,p)}const n=[];for(const f of i.values()){if(f.length===1){n.push(f[0]);continue}const a=f[0].comparison.family;for(const p of findContiguousRuns(f,a,t.sectorCount,r=>ue(r)[0]??""))n.push(p.length===1?p[0]:un(p,t))}return[...o,...n]}function mn(e){const t=new Map,s=new Map;for(const i of e){const n=we(i);i.hbin!==void 0&&i.hbin!==null&&(t.get(i.hbin)??t.set(i.hbin,new Set).get(i.hbin)).add(n),i.sbin!==void 0&&i.sbin!==null&&(s.get(i.sbin)??s.set(i.sbin,new Set).get(i.sbin)).add(n)}const o=new Set;for(const[i,n]of t)for(const[f,a]of s){if(n.size!==a.size)continue;let p=!0;for(const r of n)if(!a.has(r)){p=!1;break}p&&o.add(`${i}:${f}`)}return o}function hn(e,t){const s=new Set(t);let o;for(const i of e){const n=oe(i,s);if(n!==void 0&&n){if(i.sbin==null||o!==void 0&&i.sbin!==o)return;o=i.sbin}}if(o!==void 0){for(const i of e)if(i.sbin===o&&oe(i,s)!==!0)return;return o}}function pn(e){return`${e.comparison.family}\0${e.comparison.left}`}export function redundancyFacts(e,t,s){return{coincident:mn(e),yieldSoftBin:hn(e,t),passBins:t,sectorCount:s}}const gn=3/5;function ot(e){return/^(?:lot-region:)?([^:|]+)/.exec(e.id)?.[1]??e.id}function bn(e){const t=ue(e);if(t.length)return t;const s=/(ring|sector|quadrant):([^:|]+)$/.exec(e.id);return s?s[2].split("-").map(o=>`${s[1]}:${o}`):[]}function at(e,t){const s=new Set;for(const o of bn(e)){const i=kt(o,t);if(!i)return;for(const n of i)s.add(n)}return s.size?s:void 0}export function collapseRedundantFindings(e,t){const{coincident:s,yieldSoftBin:o,passBins:i}=t,n=(r,u)=>{r.absorbedIds=[...r.absorbedIds??[],u.id]},f=new Map;for(const r of e){const u=pn(r);(f.get(u)??f.set(u,[]).get(u)).push(r)}const a=new Set;for(const r of f.values()){for(const c of r)if(!(c.variable.kind!=="hardBin"||c.variable.bin===void 0))for(const m of r){if(m.variable.kind!=="softBin"||m.variable.bin===void 0||a.has(m.id)||!s.has(`${c.variable.bin}:${m.variable.bin}`)||m.effect.direction!==c.effect.direction)continue;n(c,m),a.add(m.id);const l=c.variable.label.replace(/^HBin\s+/,""),d=m.variable.label.replace(/^SBin\s+/,""),h=l===d?`HBin and SBin ${l} (same dies)`:`${c.variable.label} and ${m.variable.label} (same dies)`;c.summary=c.summary.replace(c.variable.label,h),c.variable.label=h;break}const u=r.find(c=>c.variable.kind==="yield");if(u){for(const c of r)if(!(c===u||a.has(c.id)||!(c.variable.kind==="hardBin"&&i.length===1&&c.variable.bin===i[0]||c.variable.kind==="softBin"&&c.variable.bin===o))){n(u,c),a.add(c.id);for(const l of c.absorbedIds??[])u.absorbedIds=[...u.absorbedIds??[],l]}}}const p=new Map;for(const r of e){if(a.has(r.id)||r.comparison.family!=="sector"&&r.comparison.family!=="quadrant")continue;const u=[ot(r),r.variable.kind,r.variable.bin??"",r.variable.index??"",r.effect.direction].join("\0");(p.get(u)??p.set(u,[]).get(u)).push(r)}for(const r of p.values()){const u=[];for(const c of r.filter(m=>m.comparison.family==="sector")){const m=at(c,t.sectorCount);if(m)for(const l of r.filter(d=>d.comparison.family==="quadrant")){const d=at(l,t.sectorCount);if(!d)continue;let h=0;for(const v of m)d.has(v)&&h++;const g=m.size+d.size-h;h/g>=gn-1e-9&&u.push({sector:c,quadrant:l,overlap:h/g})}}u.sort((c,m)=>m.overlap-c.overlap);for(const{sector:c,quadrant:m}of u){if(a.has(c.id)||a.has(m.id))continue;const l=(m.stats.pValue??1)<(c.stats.pValue??1),[d,h]=l?[m,c]:[c,m];n(d,h),a.add(h.id),d.absorbedIds=[...d.absorbedIds??[],...h.absorbedIds??[]]}}}export function analyzeWaferMap(e,t={}){return analyzeWaferMapDecided(e,t)}export function analyzeWaferMapDecided(e,t={},s){const o=te,i=fe,n=[];te=n,fe=void 0;try{const f=yn(e,t,s);return Ze.set(f,{candidates:n,facts:fe}),f}finally{te=o,fe=i}}function yn(e,t,s){const{resolved:o,warnings:i}=resolveOptions(t),n=dt(e),f={...o,passBins:[...Nt(n,"analyzeWaferMap")],ringCount:xt(n,"analyzeWaferMap")},a=n.isLotStack,p=n.aggrMethod,r=St(a,p),u=r,c=n.dies.filter(y=>Ye(y)),m=c.filter(Ae),l=At(f,c.length);l.softPassBins=Ke(c,l.passBins).soft;const d=st(c,l.testNumbers,n.testDefs),h=l.enableTestValueAnalysis,g=h===!1?"off":h===!0?"done":s??mt(d.length*c.length),v=n.dies.filter(y=>X(y)),F=v.filter(Ae),D=r?c.filter(y=>y.sbin!==void 0):[],w=u&&c.some(y=>y.hbin!==void 0)||D.length>0||h!==!1,B=w?$t(F,n.wafer,l.ringCount):[],z=w?vt(F,n.wafer,l.ringCount):[],b=w?wt(F,n.reticleConfig):[],$=w?Dt(v,!1):[],M=w?Rt(F,n.wafer,l.sectorCount):[],S=[],R=[];u&&R.push(...le(c,B,l.passBins,l),...le(c,z,l.passBins,l),...le(c,b,l.passBins,l),...le(c,$,l.passBins,l),...le(c,M,l.passBins,l)),u&&R.push(...q(c,B,"hard",n.hbinDefs,"hardBin",l),...q(c,z,"hard",n.hbinDefs,"hardBin",l),...q(c,b,"hard",n.hbinDefs,"hardBin",l),...q(c,$,"hard",n.hbinDefs,"hardBin",l),...q(c,M,"hard",n.hbinDefs,"hardBin",l));{const y=D;R.push(...q(y,B,"soft",n.sbinDefs,"softBin",l),...q(y,z,"soft",n.sbinDefs,"softBin",l),...q(y,b,"soft",n.sbinDefs,"softBin",l),...q(y,$,"soft",n.sbinDefs,"softBin",l),...q(y,M,"soft",n.sbinDefs,"softBin",l))}const P=[...i];let C;if(h!==!1){if(g==="done"){for(const y of[B,z,b,$,M])S.push(...an(c,y,d,n.testDefs,l));C=d}R.push(...rn(c,[B,z,b,$,M],n.testDefs,l)),R.push(...ce(c,B,n.testDefs,l),...ce(c,z,n.testDefs,l),...ce(c,b,n.testDefs,l),...ce(c,$,n.testDefs,l),...ce(c,M,n.testDefs,l))}S.push(...tn(R,l));{const y=Tt(a,u,n.testDefs);if(!a||u||y!==void 0){const A=Ie(m,n.wafer,{...l,isFailingDie:y});S.push(...A),u&&S.push(..._t(m,n.wafer,n.hbinDefs,l,A))}}const V=dn(S,{eligibleDies:c,softEligibleDies:D,testDies:c,passBins:l.passBins,ringCount:l.ringCount,sectorCount:l.sectorCount,regionDies:{ring:new Set(B.flatMap(y=>U(y.dies))),quadrant:new Set(z.flatMap(y=>U(y.dies))),sector:new Set(M.flatMap(y=>U(y.dies)))},hbinDefs:n.hbinDefs,sbinDefs:n.sbinDefs,testDefs:n.testDefs});S.length=0,S.push(...V),claimForBinClusters(S);let x;if(u){const y=zt(m,n.wafer,{passBins:l.passBins,ringCount:l.ringCount});if(x=y??void 0,y!==null&&y.pattern!=="random"&&y.pattern!=="none"){const A=Ct[y.pattern],_=y.confidence==="high"?"unusual":y.confidence==="medium"?"notable":"info",T=y.features,ie=L=>`${(L*100).toFixed(0)}%`,rt=y.pattern==="edge-ring"||y.pattern==="edge-local"?`${ie(T.edgeRdd)} of edge dies failing`:y.pattern==="center"?`centroid at ${ie(T.centroidDistNorm)} of wafer radius from centre`:y.pattern==="donut"?`${ie(Math.max(T.radialFailRates[1],T.radialFailRates[2]))} of dies failing at mid-radius, ${ie(T.radialFailRates[0])} at the centre`:y.pattern==="scratch"?`a line ${Math.round(T.lineLength)} dies long and about ${Math.max(1,Math.round(T.lineWidth*2))} wide`:`${ie(T.globalRdd)} of dies failing`,ft=new Set(l.passBins),Ee=c.filter(L=>Ft(L,ft)===!0),{center:Le,radius:lt}=n.wafer,ct=new Map(m.map(L=>[de(L),Ot(L.physX-Le.x,L.physY-Le.y,lt,l.ringCount)])),ut=new Set(S.flatMap(L=>_e(L)?L.relatedIds??[]:[])),Oe=claimForPattern([y.pattern],_,S.filter(L=>!ut.has(L.id)),L=>L.comparison.family==="cluster"?[...new Set(L.highlight.kind==="dies"?L.highlight.dieKeys.map(se=>ct.get(se)??0):[])]:ue(L).map(se=>J(se).ring).filter(se=>se!==void 0),l.ringCount);S.push({id:`spatial-pattern:${y.pattern}`,level:"wafer",severity:_,variable:{kind:"spatialPattern",label:A},comparison:{family:"spatial-pattern",left:A,right:"Wafer"},effect:{direction:"different",effectSize:T.globalRdd},stats:{method:"geometry",sampleSizeLeft:Ee.length,sampleSizeRight:c.length},summary:`Spatial pattern: ${A.toLowerCase()} (${y.confidence} confidence) \u2014 ${rt}${y.note?` [${y.note}]`:""}`,highlight:{kind:"dies",dieKeys:Ee.map(L=>de(L))},relatedIds:Oe.length>0?Oe:void 0})}}S.sort((y,A)=>{const _=y.stats.adjustedPValue??y.stats.pValue??1,T=A.stats.adjustedPValue??A.stats.pValue??1;return _!==T?_-T:Math.abs(A.effect.absoluteDelta??0)-Math.abs(y.effect.absoluteDelta??0)});const k=Ut(n.dies,c.length,n.yield.yieldPercent,r);a&&(k.isLotStack=!0,p&&(k.aggregationMethod=p));const O=new Set(f.passBins),N={},K=(y,A)=>{const _=N[y]??={dieKeys:[],lostDies:0};_.dieKeys.push(de(A)),(!r||oe(A,O)!==!0)&&_.lostDies++},E=Qt(n.dies,n.testDefs,K);E&&(k.testSpecYield=E);const Q=computeFunctionalYield(n.dies,n.testDefs,K);if(Q&&(k.functionalYield=Q),Object.keys(N).length&&(k.testFailures=N),x&&(k.spatialPattern=x),C===void 0&&l.computePerTestStats&&(C=d),d.length&&(k.testValueAnalysis=ht(g,d.length,c.length)),C?.length){const y=Gt(n.dies,C,n.testDefs,l.minimumSampleSize);y&&(k.perTestStats=y);const A=pt([{dies:n.dies}],n.testDefs,C);A&&(k.capability=A)}Object.assign(k,gt(n.dies,n.testDefs));const H=bt([{dies:n.dies,wafer:n.wafer,passBins:l.passBins,ringCount:l.ringCount}]);H&&(k.regionYield=H),P.length>0&&(k.warnings=P);const G=redundancyFacts(c,l.passBins,l.sectorCount);return collapseRedundantFindings(S,G),te&&(fe=G),{level:"wafer",hasNotableFindings:S.some(y=>y.severity==="notable"||y.severity==="unusual"),findings:S,wafer:n.wafer.metadata??void 0,analysisOptions:recordedOptions(t),stats:k}}
1
+ import{normalizeInput as pt}from"./normalizeInput.js";import{autoDecision as gt,testValueStatus as bt}from"./testValueBudget.js";import{computeCapability as yt,computeTestFlagYield as St,computeRegionYield as vt}from"./summaryFigures.js";import{binPassSets as Te}from"../renderer/binColors.js";import{diePassStatus as ae,isYieldEligibleDie as Z,getDieKey as re,isPositionedDie as qe,positionKey as Re}from"../core/dies.js";import{dieHasValues as wt,testsPresent as Ie,testValue as Y}from"../core/dieTable.js";import{stackBinsAreData as $t}from"../core/aggregates.js";import{getTestPassStatus as pe,isParametricTest as J}from"../renderer/buildWaferMap.js";import{markedTestLabel as j,derivedFields as ge}from"../renderer/testLabel.js";import{buildQuadrantRegions as Rt,buildReticlePositionRegions as kt,buildRingRegions as Mt,buildSectorRegions as Dt,buildTestSiteRegions as zt,sectorCompassNames as je,areQuadrantsAdjacent as Bt,parseRegionKey as ee,QUADRANT_CYCLE as ke,regionAngleBins as Ft}from"./regions.js";import{buildClusterFindings as He}from"./clusterDetection.js";import{classifyPattern as Ct,classifyFailingDies as Nt,patternExplains as xt,patternFailVerdict as _e,PATTERN_LABELS as Pt}from"./patternClassification.js";import{requirePassBins as Vt}from"../core/passBins.js";import{requireRingCount as Et}from"../core/ringCount.js";import{benjaminiHochberg as Lt,fisherExact as Kt,fiveNumberSummary as Ot,sampleVariance as Me,zPValue as We}from"./math.js";import{mean as be,maxOf as At}from"../core/utils.js";import{classifySpec as ye,isOutOfSpec as De}from"../renderer/spec.js";import{ringOf as Tt}from"../core/classify.js";import{SEVERITY_ORDER as Ye,isOneBinCluster as Ue}from"./filterFindings.js";const qt={significanceLevel:{min:1e-6,max:1},minimumEffectSize:{min:0,max:1},minimumRelativeEffect:{min:0,max:Number.MAX_SAFE_INTEGER}},Qe=[4,8,16];export function resolveOptions(e){const t=Object.fromEntries(Object.entries(e).filter(([,a])=>a!==void 0)),s={...fe,...t},o=[],i=[];for(const a of["significanceLevel","minimumEffectSize","minimumRelativeEffect"]){const{min:d,max:r}=qt[a],l=s[a];if(typeof l!="number"||!Number.isFinite(l)){i.push(`${a}=${String(l)} is not a finite number (using ${fe[a]})`),s[a]=fe[a];continue}const u=Math.min(r,Math.max(d,l));u!==l&&(i.push(`${a}=${l} is outside ${d}\u2013${r} (using ${u})`),s[a]=u)}if(Qe.includes(s.sectorCount)||(i.push(`sectorCount=${s.sectorCount} is not one of ${Qe.join(", ")} (using ${fe.sectorCount})`),s.sectorCount=fe.sectorCount),i.length){const a=`analyzeWaferMap: ${i.join("; ")}. The analysis ran with the corrected values.`;console.warn(`[wafermap] ${a}`),o.push({code:"analysis-option-corrected",message:a,severity:"warning"})}const n=["passBins","ringCount"].filter(a=>t[a]!==void 0);if(n.length){const a=`analyzeWaferMap: ${n.join(" and ")} ${n.length>1?"are":"is"} no longer an analysis option and was ignored. Set ${n.length>1?"them":"it"} on buildWaferMap; the analysis used the value the map was built with.`;console.warn(`[wafermap] ${a}`),o.push({code:"analysis-option-corrected",message:a,severity:"warning"})}const f=["enableYieldAnalysis","enableHardBinAnalysis","enableSoftBinAnalysis","enableReticlePositionAnalysis","enableTestSiteAnalysis","enableClusterAnalysis","enableAngularAnalysis","enablePatternClassification"].filter(a=>t[a]!==void 0);if(f.length){const a=`analyzeWaferMap: ${f.join(", ")} ${f.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] ${a}`),o.push({code:"analysis-option-corrected",message:a,severity:"warning"})}return{resolved:s,warnings:o}}const fe={significanceLevel:.05,minimumEffectSize:.2,minimumRelativeEffect:1,minimumSampleSize:5,enableTestValueAnalysis:"auto",computePerTestStats:!1,sectorCount:8,minimumClusterSize:5};function It(e,t){const s={...e};return s.minimumClusterSize=Math.max(5,Math.round(t*.003)),s}function Ge(e){return Z(e)?e.hbin!==void 0||e.sbin!==void 0||wt(e):!1}function jt(e,t,s){if(!e||t)return;const o=(s??[]).filter(i=>J(i)&&(i.limitLow!==void 0||i.limitHigh!==void 0));if(o.length!==0)return i=>{for(const n of o)if(De(ye(Y(i,n.testNumber),n)))return!0;return!1}}const Ht=8,_t=.8,Wt=.8,Yt=.5;function Ut(e,t,s,o,i){const n=new Set(o.passBins),f=e.filter(m=>ae(m,n)!==void 0),a=new Map;let d=0;for(const m of f)ae(m,n)||(d++,m.hbin!==void 0&&a.set(m.hbin,(a.get(m.hbin)??0)+1));const r=[...a].filter(([,m])=>m>=o.minimumClusterSize&&m<=_t*d).sort((m,c)=>c[1]-m[1]||m[0]-c[0]).slice(0,Ht).map(([m])=>m);if(!r.length)return[];const l=i.filter(m=>m.comparison.family==="cluster").map(Se),u=[];for(const m of r){const c=He(f,t,{...o,significanceLevel:o.significanceLevel/r.length,isFailingDie:h=>h.hbin===m,bin:{bin:m,label:xe(m,s,"HBin")}});u.push(...c.filter(h=>!l.some(p=>Gt(Se(h),p))))}return u}const Qt=.5;export function claimForBinClusters(e){const t=e.filter(s=>(s.comparison.family==="ring"||s.comparison.family==="quadrant"||s.comparison.family==="sector")&&s.variable.kind==="hardBin"&&s.effect.direction==="higher");for(const s of e){if(!Ue(s))continue;const o=Se(s),i=t.filter(n=>{if(n.variable.bin!==s.variable.bin||Ye[n.severity]<Ye[s.severity])return!1;const f=(n.effect.absoluteDelta??0)*n.stats.sampleSizeLeft;let a=0;for(const d of Se(n))o.has(d)&&a++;return f>0&&a>=Qt*f});if(s.severity!=="info")for(const n of i)n.severity="info";i.length&&(s.relatedIds=i.map(n=>n.id))}}function Se(e){return new Set("dieKeys"in e.highlight?e.highlight.dieKeys??[]:[])}function Gt(e,t){let s=0;for(const o of e)t.has(o)&&s++;return s>=Wt*e.size&&e.size>=Yt*t.size}function Xt(e,t,s,o){const i=new Set,n=new Set,f=new Set,a=new Map,d=new Map;for(const r of Ie(e))i.add(r);for(const r of o?e:[])r.hbin!==void 0&&n.add(r.hbin),r.sbin!==void 0&&f.add(r.sbin),Z(r)&&(r.hbin!==void 0&&a.set(r.hbin,(a.get(r.hbin)??0)+1),r.sbin!==void 0&&d.set(r.sbin,(d.get(r.sbin)??0)+1));return{totalDies:e.length,analyzedDies:t,excludedDies:e.length-t,yieldPercent:s,testsConsidered:[...i].sort((r,l)=>r-l),hardBinsConsidered:[...n].sort((r,l)=>r-l),softBinsConsidered:[...f].sort((r,l)=>r-l),...a.size?{hardBinCounts:Object.fromEntries(a)}:{},...d.size?{softBinCounts:Object.fromEntries(d)}:{}}}function Zt(e,t,s){if(!t?.length)return;const o=t.filter(n=>J(n)&&(n.limitLow!==void 0||n.limitHigh!==void 0));if(!o.length)return;const i=[];for(const n of o){const f=n.testNumber;let a=0,d=0,r=0,l=0;for(const u of e){if(!Z(u))continue;const m=ye(Y(u,f),n);if(m!==null){if(l++,m==="failLow")d++;else if(m==="failHigh")r++;else{a++;continue}s?.(f,u)}}i.push({testNumber:f,label:j(n,f),passDies:a,failLowDies:d,failHighDies:r,totalDies:l,yieldPercent:l>0?a/l*100:null})}return i.length?i:void 0}export function computeFunctionalYield(e,t,s){if(!t?.length)return;const o=t.filter(n=>!J(n));if(!o.length)return;const i=[];for(const n of o){const f=n.testNumber;let a=0,d=0;for(const l of e){if(!Z(l))continue;const u=pe(l,f,n);if(u!==void 0){if(u){a++;continue}d++,s?.(f,l)}}const r=a+d;i.push({testNumber:f,label:j(n,f),...ge(n),passDies:a,failDies:d,totalDies:r,passRatePercent:r>0?a/r*100:null})}return i.length?i:void 0}function Jt(e,t,s,o){const i=[];for(const n of t){const f=[];for(const u of e){if(!Z(u))continue;const m=Y(u,n);m!==void 0&&Number.isFinite(m)&&f.push(m)}if(f.length<o)continue;const a=be(f),d=Math.sqrt(Me(f,a)),r=Ot(Float64Array.from(f)),l=s?.find(u=>u.testNumber===n)?.name??String(n);i.push({testNumber:n,label:l,count:f.length,min:r.min,max:r.max,mean:a,stddev:d,median:r.median,q1:r.q1,q3:r.q3})}return i.length?i:void 0}export function twoProportionZ(e,t,s,o){const i=(e+s)/(t+o),n=i*(1-i)*(1/t+1/o);return!Number.isFinite(n)||n<=0?0:(e/t-s/o)/Math.sqrt(n)}const en=5;function H(e,t,s,o){const i=t+o,n=e+s;if((i>0?Math.min(n,i-n)*Math.min(t,o)/i:0)<en)return{pValue:Kt(e,t-e,s,o-s),method:"fisher-exact"};const a=twoProportionZ(e,t,s,o);return{pValue:a===0?1:We(a),method:"two-proportion-z"}}function tn(e,t,s,o){return H(e,t,s,o).pValue}export function adjustPValues(e){const t=e.filter(o=>o.stats.pValue!==void 0),s=Lt(t.map(o=>o.stats.pValue));return t.forEach((o,i)=>{o.stats.adjustedPValue=s[i]}),e}export function rateRelativeEffect(e){const t=(e.passRate?e.n-e.hits:e.hits)/e.n,s=(e.passRate?e.restN-e.restHits:e.restHits)/e.restN;return s===0?t===0?0:1/0:Math.abs(t-s)/s}export function severityForFinding(e,t,s){const o=Math.abs(t),i=s;return e<=.01&&(o>=.3||i>=2.5)?"unusual":e<=.05&&(o>=.2||i>=1.5)?"notable":"info"}export function severityForScore(e,t){return e<=.01&&Math.abs(t)>=.5?"unusual":e<=.05&&Math.abs(t)>=.15?"notable":"info"}function ve(e){return e==="reticle-position"?"other reticle positions":e==="test-site"?"other test sites":"the rest of the map"}function te(e){return e==="reticle-position"?"Other reticle positions":e==="test-site"?"Other test sites":"Rest of map"}function ze(e,t,s){const o=(Math.abs(t)*100).toFixed(1);return`${e} yield is ${o} percentage points ${t>0?"higher":"lower"} than ${ve(s)}`}function Be(e,t){return t==="quadrant"&&!e.startsWith("Quadrant")?`quadrant ${e}`:e}function Xe(e){return/^(Rings|Sectors|Quadrants)\b/.test(e)?"have":"has"}function Fe(e,t,s,o){const i=Be(e,o),n=(Math.abs(s)*100).toFixed(1);return`${i} ${Xe(i)} ${t} occurrence ${n} percentage points ${s>0?"higher":"lower"} than ${ve(o)}`}function Ce(e,t,s,o){const i=Be(e,o),n=(Math.abs(s)*100).toFixed(1);return`${i} ${Xe(i)} ${t} pass rate ${n} percentage points ${s>0?"higher":"lower"} than ${ve(o)}`}function Ne(e,t,s,o,i,n){const f=Be(e,i),a=ve(i),d=s>0?"higher":"lower";if(o!==void 0&&Number.isFinite(o)){const l=(Math.abs(o)*100).toFixed(1);return`${f} mean ${t} is ${l}% ${d} than ${a}`}const r=n?` ${n}`:"";return`${f} mean ${t} is ${Math.abs(s).toPrecision(3)}${r} ${d} than ${a}`}function xe(e,t,s){const o=t?.find(i=>i.bin===e);return o?.name?`${s} ${e} (${o.name})`:`${s} ${e}`}function nn(e,t){const s=t?.find(o=>o.testNumber===e);return{label:j(s,e),unit:s?.unit,...ge(s)}}const Ze=new WeakMap,Je=new WeakMap,et=new WeakMap;function le(e,t){const s=t.highlight.dieKeys;return s&&et.set(s,e),t}let ne=null,ce;const tt=new WeakMap;export function candidatesOf(e){return tt.get(e)}function nt(e,t,s,o){if(!ne)return;const i=it(e);if(!i)return;const n=e.id.slice(0,e.id.indexOf(":")),f=n==="specLimit"?"limitFail":n,{kind:a,bin:d,index:r}=e.variable;ne.push({key:[f,a,d??"",r??"",i.family,i.key].join("|"),source:f,variable:e.variable,label:e.variable.label,comparison:e.comparison,region:i,z:t,delta:e.effect.absoluteDelta??0,effectSize:e.effect.effectSize??0,relativeDelta:e.effect.relativeDelta,rate:s,mean:o})}export function describeRegional(e,t,s){const o=e.comparison.left,i=e.region.family;switch(e.source){case"yield":return ze(o,t,i);case"hardBin":case"softBin":return Fe(o,e.label,t,i);case"functional":return Ce(o,e.label.replace(/ pass rate$/,""),t,i);case"limitFail":return Pe(o,e.label,t);case"test":return Ne(o,e.label,t,s,i,e.variable.unit)}}function Pe(e,t,s){return`${e} limit fail rate for ${t} is ${(Math.abs(s)*100).toFixed(1)} pp ${s>0?"higher":"lower"} than the rest of the wafer`}const U=new WeakMap;function we(e,t){return U.set(e,t),e}function it(e){const t=e.highlight.dieKeys;return t?et.get(t):void 0}const st=new WeakMap;function Q(e){let t=st.get(e);return t||st.set(e,t=e.map(Re)),t}function sn(e){let t=Ze.get(e);return t||Ze.set(e,t=e.map(re)),t}function $e(e,t){let s=Je.get(e);s||Je.set(e,s={members:new Set(e),byFamily:new WeakMap});const o=s.byFamily.get(t);if(o)return o;const{members:i}=s,n=new Map;for(const f of t)n.set(f.key,f.dies.filter(a=>i.has(a)));return s.byFamily.set(t,n),n}function on(e,t){adjustPValues(e);for(const i of e){const n=U.get(i);nt(i,twoProportionZ(n.hits,n.n,n.restHits,n.restN),n)}const s=e.filter(i=>passesRateGate(i.stats.adjustedPValue??i.stats.pValue??1,i.effect.absoluteDelta??0,rateRelativeEffect(U.get(i)),t)),o=confirmRegionalFindings(s,ot,(i,n)=>an(i,n,t),i=>isRateLoss(U.get(i)),e);return s.filter(i=>o.has(i)).map(i=>({...i,severity:severityForFinding(i.stats.adjustedPValue??i.stats.pValue??1,i.effect.absoluteDelta??0,rateRelativeEffect(U.get(i)))}))}export function passesRateGate(e,t,s,o){return e<=o.significanceLevel&&(Math.abs(t)>=o.minimumEffectSize||s>=o.minimumRelativeEffect)}export function claimForPattern(e,t,s,o,i){const n=[];for(const f of s){const a=f.comparison.family,d=a==="ring"||a==="cluster"?o(f):[];e.some(r=>xt(r,a,d,i))&&(n.push(f.id),t!=="info"&&(a==="ring"||a==="quadrant"||a==="sector")&&(f.severity="info"))}return n}export function confirmRegionalFindings(e,t,s,o,i=e){const n=new Map;for(const d of e)(n.get(t(d))??n.set(t(d),[]).get(t(d))).push(d);const f=new Map;if(o)for(const d of i)o(d)&&(f.get(t(d))??f.set(t(d),[]).get(t(d))).push(d);const a=new Set;for(const[d,r]of n){const l=f.get(d)??[],u=(h,p)=>o&&!o(h)?s(h,[...new Set([...p,...l])].filter(g=>g!==h)):s(h,p);if(r.length===1&&(!o||o(r[0])||l.length===0)){a.add(r[0]);continue}const m=[];let c=[...r];for(;;){let h;for(const p of c){const g=u(p,m);if(g==="baseline-too-small"||!g.passes)continue;const S=o?.(p)??!1;(!h||S&&!h.loss||S===h.loss&&g.pValue<h.p)&&(h={t:p,p:g.pValue,loss:S})}if(!h)break;m.push(h.t),c=c.filter(p=>p!==h.t)}for(;;){let h;for(const p of m){const g=u(p,m.filter(S=>S!==p));g==="baseline-too-small"||g.passes||(!h||g.pValue>h.p)&&(h={t:p,p:g.pValue})}if(!h)break;m.splice(m.indexOf(h.t),1)}for(const h of m)a.add(h)}return a}function ot(e){return[e.variable.kind,e.variable.bin??"",e.variable.index??"",e.comparison.family].join("\0")}function at(e){const t=e.stats.pValue??1;return t>0?(e.stats.adjustedPValue??t)/t:1}export function isRateLoss(e){const t=e.hits/e.n-e.restHits/e.restN;return e.passRate?t<0:t>0}function an(e,t,s){const o=U.get(e);let{restHits:i,restN:n}=o;for(const r of t){const l=U.get(r);l&&(i-=l.hits,n-=l.n)}if(n<s.minimumSampleSize)return"baseline-too-small";const f=o.hits/o.n-i/n,a=Math.min(1,tn(o.hits,o.n,i,n)*at(e)),d=Math.sign(f)===Math.sign(e.effect.absoluteDelta??0)&&passesRateGate(a,f,rateRelativeEffect({...o,restHits:i,restN:n}),s);return{pValue:a,passes:d}}const Ve=new WeakMap;export function welchOfSums(e,t,s,o){const i=(n,f,a)=>a>1?Math.max(0,n-f*f/a)/(a-1):0;return welchFromStats(e.n,e.sum/e.n,i(e.sq,e.sum,e.n),t,s/t,i(o,s,t))}function rn(e,t,s){const o=Ve.get(e);let{restN:i,restSum:n,restSq:f}=o;for(const m of t){const c=Ve.get(m);c&&(i-=c.n,n-=c.sum,f-=c.sq)}if(i<s.minimumSampleSize)return"baseline-too-small";const{pValue:a,effectSize:d,delta:r}=welchOfSums(o,i,n,f),l=Math.min(1,a*at(e)),u=Math.sign(r)===Math.sign(e.effect.absoluteDelta??0)&&l<=s.significanceLevel&&Math.abs(d)>=s.minimumEffectSize;return{pValue:l,passes:u}}function ue(e,t,s,o){const i=new Set(s),n=$e(e,t),f=new Map,a=new Map;for(const[r,l]of n){let u=0,m=0;for(const c of l)c.hbin!==void 0&&(m++,i.has(c.hbin)&&u++);f.set(r,u),a.set(r,m)}const d=[];for(const r of t){const l=a.get(r.key)??0,u=f.get(r.key)??0;let m=0,c=0;for(const[k,v]of a)k!==r.key&&(m+=v,c+=f.get(k)??0);if(l<o.minimumSampleSize||m<o.minimumSampleSize)continue;const h=u/l,p=c/m,g=h-p,{pValue:S,method:F}=H(u,l,c,m);d.push(we(le(r,{id:`yield:${r.key}`,level:"wafer",severity:"info",variable:{kind:"yield",label:"Yield"},comparison:{family:r.family,left:r.label,right:te(r.family)},effect:{direction:g===0?"different":g>0?"higher":"lower",absoluteDelta:g,relativeDelta:p===0?void 0:g/p,effectSize:g},stats:{method:F,pValue:S,sampleSizeLeft:l,sampleSizeRight:m},summary:ze(r.label,g,r.family),highlight:{kind:"region",regionFamily:r.family,regionKeys:[r.key],dieKeys:[...r.dieKeys]}}),{hits:u,n:l,restHits:c,restN:m,passRate:!0}))}return d}function q(e,t,s,o,i,n){const f=h=>s==="soft"?h.sbin:h.hbin,a=[...new Set(e.map(f).filter(h=>h!==void 0))].sort((h,p)=>h-p),d=$e(e,t),r=new Map,l=new Map;for(const[h,p]of d){const g=new Map;for(const S of p){const F=f(S);F!==void 0&&g.set(F,(g.get(F)??0)+1)}r.set(h,g),l.set(h,p.length)}const u=[],m=i==="hardBin"?"HBin":"SBin",c=s==="hard"?new Set(n.passBins):n.softPassBins??Te(e,n.passBins).soft;for(const h of t){const p=l.get(h.key)??0,g=r.get(h.key);let S=0;const F=new Map;for(const[k,v]of r)if(k!==h.key){S+=l.get(k)??0;for(const[B,z]of v)F.set(B,(F.get(B)??0)+z)}if(!(p<n.minimumSampleSize||S<n.minimumSampleSize))for(const k of a){const v=g.get(k)??0,B=F.get(k)??0,z=v/p,b=B/S,w=z-b,{pValue:M,method:y}=H(v,p,B,S),$=xe(k,o,m);u.push(we(le(h,{id:`${i}:${k}:${h.key}`,level:"wafer",severity:"info",variable:{kind:i,bin:k,label:$},comparison:{family:h.family,left:h.label,right:te(h.family)},effect:{direction:w===0?"different":w>0?"higher":"lower",absoluteDelta:w,relativeDelta:b===0?void 0:w/b,effectSize:w},stats:{method:y,pValue:M,sampleSizeLeft:p,sampleSizeRight:S},summary:Fe(h.label,$,w,h.family),highlight:{kind:"bin",bin:k,regionKeys:[h.key],dieKeys:[...h.dieKeys]}}),{hits:v,n:p,restHits:B,restN:S,passRate:c.has(k)}))}}return u}function de(e,t,s,o){const i=(s??[]).filter(l=>!J(l));if(!i.length)return[];const n=i.map(l=>l.testNumber),f=$e(e,t),a=new Map,d=new Map;for(const[l,u]of f){const m=new Uint32Array(i.length),c=new Uint32Array(i.length);for(const h of u)for(let p=0;p<i.length;p++){const g=pe(h,n[p],i[p]);g!==void 0&&(c[p]++,g&&m[p]++)}a.set(l,m),d.set(l,c)}const r=[];for(const l of t){const u=a.get(l.key),m=d.get(l.key);for(let c=0;c<i.length;c++){let h=0,p=0;for(const[w,M]of d)w!==l.key&&(p+=M[c],h+=a.get(w)[c]);const g=m[c],S=u[c];if(g<o.minimumSampleSize||p<o.minimumSampleSize)continue;const F=S/g,k=h/p,v=F-k,{pValue:B,method:z}=H(S,g,h,p),b=n[c];r.push(we(le(l,{id:`functional:${b}:${l.key}`,level:"wafer",severity:"info",variable:{kind:"functionalTest",index:b,label:`${j(i[c],b)} pass rate`,...ge(i[c])},comparison:{family:l.family,left:l.label,right:te(l.family)},effect:{direction:v===0?"different":v>0?"higher":"lower",absoluteDelta:v,relativeDelta:k===0?void 0:v/k,effectSize:v},stats:{method:z,pValue:B,sampleSizeLeft:g,sampleSizeRight:p},summary:Ce(l.label,j(i[c],b),v,l.family),highlight:{kind:"region",regionFamily:l.family,regionKeys:[l.key],dieKeys:[...l.dieKeys]}}),{hits:S,n:g,restHits:h,restN:p,passRate:!0}))}}return r}export function welchFromStats(e,t,s,o,i,n){const f=Math.sqrt(s/e+n/o),a=t-i;if(!Number.isFinite(f)||f===0)return{pValue:1,effectSize:0,delta:a,z:0};const d=a/f,r=Math.sqrt(Math.max(0,(s+n)/2)),l=r===0?a:a/r;return{pValue:We(d),effectSize:l,delta:a,z:d}}function fn(e,t){const s=be(e),o=be(t);return welchFromStats(e.length,s,Me(e,s),t.length,o,Me(t,o))}function rt(e,t,s){const o=new Map;for(const n of s??[])o.has(n.testNumber)||o.set(n.testNumber,n);const i=n=>n.filter(f=>J(o.get(f)));return i(t?t.slice().sort((n,f)=>n-f):Ie(e,"values"))}export function testValueSize(e,t){const s=e.dies.filter(Ge);return{tests:rt(s,t.testNumbers,e.testDefs).length,dies:s.length}}export function recordedOptions(e){const t={};return e.enableTestValueAnalysis!==void 0&&(t.enableTestValueAnalysis=e.enableTestValueAnalysis),e.computePerTestStats!==void 0&&(t.computePerTestStats=e.computePerTestStats),e.sectorCount!==void 0&&(t.sectorCount=e.sectorCount),e.testNumbers!==void 0&&(t.testNumbers=[...e.testNumbers]),t}function ln(e,t,s,o,i){const n=new Map;for(let p=0;p<t.length;p++)for(const g of Q(t[p].dies))n.set(g,p);const f=t.length,a=[],d=[];for(const p of e){const g=n.get(Re(p));g!==void 0&&(a.push(p),d.push(g))}const r=[],l=new Float64Array(f),u=new Float64Array(f),m=new Float64Array(f);for(const p of s){l.fill(0),u.fill(0),m.fill(0);let g=0,S=0,F=0,k;for(let v=0;v<a.length;v++){const B=a[v],z=Y(B,p);if(z===void 0)continue;k===void 0&&(k=z);const b=z-k,w=d[v];l[w]+=1,u[w]+=b,m[w]+=b*b,g+=1,S+=b,F+=b*b}if(k!==void 0)for(let v=0;v<f;v++){const B=l[v],z=g-B;if(B<i.minimumSampleSize||z<i.minimumSampleSize)continue;const b=u[v]/B,M=(S-u[v])/z,y=b+k,$=M+k,P=B>1?Math.max(0,m[v]-B*b*b)/(B-1):0,C=z>1?Math.max(0,F-m[v]-z*M*M)/(z-1):0,{pValue:V,effectSize:x,delta:D,z:O}=welchFromStats(B,y,P,z,$,C),N=t[v],{label:A,unit:L,...G}=nn(p,o),_=$!==0?D/Math.abs($):void 0,X=le(N,{id:`test:${p}:${N.key}`,level:"wafer",severity:"info",variable:{kind:"test",measure:"mean",index:p,label:A,unit:L,...G},comparison:{family:N.family,left:N.label,right:te(N.family)},effect:{direction:D===0?"different":D>0?"higher":"lower",absoluteDelta:D,relativeDelta:_,effectSize:x},stats:{method:"welch-z-approx",pValue:V,sampleSizeLeft:B,sampleSizeRight:z},summary:Ne(N.label,A,D,_,N.family,L),highlight:{kind:"region",regionFamily:N.family,regionKeys:[N.key],dieKeys:[...N.dieKeys]}}),R={n:B,sum:u[v],sq:m[v],restN:z,restSum:S-u[v],restSq:F-m[v],shift:k};Ve.set(X,R),nt(X,O,void 0,R),r.push(X)}}adjustPValues(r);const c=r.filter(p=>{const g=p.stats.adjustedPValue??p.stats.pValue??1,S=Math.abs(p.effect.effectSize??0);return g<=i.significanceLevel&&S>=i.minimumEffectSize}),h=confirmRegionalFindings(c,ot,(p,g)=>rn(p,g,i));return c.filter(p=>h.has(p)).map(p=>({...p,severity:severityForScore(p.stats.adjustedPValue??p.stats.pValue??1,p.effect.effectSize??0)}))}function cn(e,t,s,o){if(!s?.length)return[];const i=s.filter(f=>J(f)&&(f.limitLow!==void 0||f.limitHigh!==void 0));if(!i.length)return[];const n=[];for(const f of i){const a=f.testNumber;for(const d of t){const r=$e(e,d),l=[],u=new Map;let m=0,c=0;for(const[h,p]of r){let g=0,S=0;for(const F of p){const k=Y(F,a);k!==void 0&&(g++,De(ye(k,f))&&S++)}u.set(h,{valid:g,fail:S}),m+=g,c+=S}for(const h of d){const p=u.get(h.key),g=p.valid,S=m-p.valid;if(g<o.minimumSampleSize||S<o.minimumSampleSize)continue;const F=p.fail,k=c-p.fail,v=F/g,B=k/S,z=v-B,{pValue:b,method:w}=H(F,g,k,S);l.push(we(le(h,{id:`specLimit:${a}:${h.key}`,level:"wafer",severity:"info",variable:{kind:"test",measure:"limitFailRate",index:a,label:j(f,a),...ge(f)},comparison:{family:h.family,left:h.label,right:te(h.family)},effect:{direction:z===0?"different":z>0?"higher":"lower",absoluteDelta:z,relativeDelta:B===0?void 0:z/B,effectSize:z},stats:{method:w,pValue:b,sampleSizeLeft:g,sampleSizeRight:S},summary:Pe(h.label,j(f,a),z),highlight:{kind:"region",regionFamily:h.family,regionKeys:[h.key],dieKeys:[...h.dieKeys]}}),{hits:F,n:g,restHits:k,restN:S,passRate:!1}))}n.push(...l)}}return n}function Ee(e,t){return e==="softBin"?t.softEligibleDies:t.eligibleDies}function un(e){return e.variable.measure==="limitFailRate"}function dn(e,t,s,o,i,n){if(e.pattern!=="scratch")return;const f=t.filter(l=>l.comparison.family==="reticle-position"&&l.severity!=="info"&&l.highlight.kind==="region");if(!f.length)return;const a=new Set(f.flatMap(l=>l.highlight.kind==="region"?l.highlight.dieKeys??[]:[])),d=Nt(s().filter(l=>!a.has(re(l))),o,i,n);if(!d||d.pattern==="scratch")return;const r=f[0].comparison.left;return{...d,note:`${r.charAt(0).toLowerCase()}${r.slice(1)}'s failures set aside`}}function me(e){return e.highlight.regionKeys??[]}function mn(e){const t=e.variable.bin??e.variable.index??"";return`${e.comparison.family}\0${ft(e)}\0${e.variable.kind}\0${t}\0${e.effect.direction}`}function hn(e,t){const s=ee(e);return s.family==="ring"?s.ring??0:s.family==="sector"?je(t).indexOf(s.sector??""):0}export function inQuadrantOrder(e){const t=new Set(e),s=ke.findIndex((i,n)=>t.has(i)&&!t.has(ke[(n+3)%4])),o=s<0?0:s;return Array.from({length:4},(i,n)=>ke[(o+n)%4]).filter(i=>t.has(i))}export function findContiguousRuns(e,t,s,o){if(t==="quadrant"){const d=new Map;for(const m of e){const c=ee(o(m)).quadrant;c&&d.set(c,m)}const r=[...d.keys()],l=new Set,u=[];for(const m of r){if(l.has(m))continue;const c=[],h=[m];for(l.add(m);h.length;){const p=h.pop();c.push(p);for(const g of r)!l.has(g)&&Bt(p,g)&&(l.add(g),h.push(g))}u.push(inQuadrantOrder(c).map(p=>d.get(p)))}return u}const i=d=>hn(o(d),s),n=[...e].sort((d,r)=>i(d)-i(r)),f=[];let a=[];for(const d of n){if(a.length===0){a.push(d);continue}const r=i(a[a.length-1]);i(d)-r===1?a.push(d):(f.push(a),a=[d])}if(a.length&&f.push(a),t==="sector"&&f.length>1){const r=je(s).length,l=i(f[0][0]),u=i(f[f.length-1][f[f.length-1].length-1]);if(l===0&&u===r-1){const m=f.pop();f[0]=[...m,...f[0]]}}return f}export function mergedRegionLabel(e,t,s){if(e==="ring"){const i=t.map(d=>ee(d).ring).filter(d=>d!==void 0).sort((d,r)=>d-r),n=i[0],f=i[i.length-1];let a="";return n===f&&n===1&&s>1?a=" (core)":n===f&&n===s&&s>1&&(a=" (edge)"),n===f?`Ring ${n}${a}`:`Rings ${n}\u2013${f}`}if(e==="sector"){const i=t.map(n=>ee(n).sector??"");return i.length===1?`Sector ${i[0]}`:`Sectors ${i[0]}\u2013${i[i.length-1]}`}const o=t.map(i=>ee(i).quadrant??"");return o.length===1?o[0]:o.length===2?`Quadrants ${o[0]} & ${o[1]}`:`Quadrants ${o.slice(0,-1).join(", ")} & ${o[o.length-1]}`}function Le(e){return[...new Set(e)]}export function weakestMultiplier(e){return At(e.map(t=>{const s=t.stats.pValue??1;return s>0?(t.stats.adjustedPValue??s)/s:1}))}function ie(e,t){return Math.min(1,e*t)}function pn(e,t){const s=e[0],o=s.comparison.family,i=s.variable.kind,n=Le(e.flatMap(me));let f,a;const d=e.map(it);if(d.every(b=>b!==void 0)){const b=new Set;f=[];for(const M of d){const y=Q(M.dies);for(let $=0;$<y.length;$++)b.has(y[$])||(b.add(y[$]),f.push(M.dieKeys[$]))}const w=Q(Ee(s.variable.kind,t));a=M=>b.has(w[M])}else{f=Le(e.flatMap(M=>M.highlight.dieKeys??[]));const b=new Set(f),w=sn(Ee(s.variable.kind,t));a=M=>b.has(w[M])}const r=mergedRegionLabel(o,e.map(b=>me(b)[0]??""),t.ringCount),l=Ee(i,t),u=t.regionDies[o],m=Q(l),c=[],h=[];for(let b=0;b<l.length;b++)u.has(m[b])&&(a(b)?c:h).push(l[b]);const p=weakestMultiplier(e);let g,S,F,k,v;if(un(s)){const b=s.variable.index,w=t.testDefs?.find(N=>N.testNumber===b),M=N=>{let A=0,L=0;for(const G of N){const _=Y(G,b);_!==void 0&&(A++,w&&De(ye(_,w))&&L++)}return{valid:A,fail:L}},y=M(c),$=M(h),P=y.valid>0?y.fail/y.valid:0,C=$.valid>0?$.fail/$.valid:0,V=P-C,{pValue:x,method:D}=H(y.fail,y.valid,$.fail,$.valid);g={direction:V===0?"different":V>0?"higher":"lower",absoluteDelta:V,relativeDelta:C===0?void 0:V/C,effectSize:V},S={method:D,pValue:x,sampleSizeLeft:y.valid,sampleSizeRight:$.valid};const O=ie(x,p);F=severityForFinding(O,V,rateRelativeEffect({hits:y.fail,n:y.valid,restHits:$.fail,restN:$.valid,passRate:!1})),k=Pe(r,j(w,b),V),v=`specLimit:${b}`}else if(i==="test"){const b=s.variable.index,w=O=>Y(O,b),M=c.map(w).filter(O=>O!==void 0),y=h.map(w).filter(O=>O!==void 0),{pValue:$,effectSize:P,delta:C}=fn(M,y),V=be(y),x=V!==0?C/Math.abs(V):void 0;g={direction:C===0?"different":C>0?"higher":"lower",absoluteDelta:C,relativeDelta:x,effectSize:P},S={method:"welch-z-approx",pValue:$,sampleSizeLeft:M.length,sampleSizeRight:y.length};const D=ie($,p);F=severityForScore(D,P),k=Ne(r,s.variable.label,C,x,o,s.variable.unit),v=`test:${b}`}else if(i==="yield"){const b=new Set(t.passBins),w=c.filter(L=>L.hbin!==void 0),M=h.filter(L=>L.hbin!==void 0),y=w.length,$=M.length,P=w.filter(L=>b.has(L.hbin)).length,C=M.filter(L=>b.has(L.hbin)).length,V=y>0?P/y:0,x=$>0?C/$:0,D=V-x,{pValue:O,method:N}=H(P,y,C,$);g={direction:D===0?"different":D>0?"higher":"lower",absoluteDelta:D,relativeDelta:x===0?void 0:D/x,effectSize:D},S={method:N,pValue:O,sampleSizeLeft:y,sampleSizeRight:$};const A=ie(O,p);F=severityForFinding(A,D,rateRelativeEffect({hits:P,n:y,restHits:C,restN:$,passRate:!0})),k=ze(r,D,o),v="yield"}else if(i==="functionalTest"){const b=s.variable.index,w=t.testDefs?.find(A=>A.testNumber===b);let M=0,y=0,$=0,P=0;for(const A of c){const L=pe(A,b,w);L!==void 0&&(y++,L&&M++)}for(const A of h){const L=pe(A,b,w);L!==void 0&&(P++,L&&$++)}const C=y>0?M/y:0,V=P>0?$/P:0,x=C-V,{pValue:D,method:O}=H(M,y,$,P);g={direction:x===0?"different":x>0?"higher":"lower",absoluteDelta:x,relativeDelta:V===0?void 0:x/V,effectSize:x},S={method:O,pValue:D,sampleSizeLeft:y,sampleSizeRight:P};const N=ie(D,p);F=severityForFinding(N,x,rateRelativeEffect({hits:M,n:y,restHits:$,restN:P,passRate:!0})),k=Ce(r,j(w,b),x,o),v=`functional:${b}`}else{const b=s.variable.bin,w=N=>i==="softBin"?N.sbin:N.hbin,M=c.filter(N=>w(N)===b).length,y=h.filter(N=>w(N)===b).length,$=M/c.length,P=y/h.length,C=$-P,{pValue:V,method:x}=H(M,c.length,y,h.length);g={direction:C===0?"different":C>0?"higher":"lower",absoluteDelta:C,relativeDelta:P===0?void 0:C/P,effectSize:C},S={method:x,pValue:V,sampleSizeLeft:c.length,sampleSizeRight:h.length};const D=ie(V,p);F=severityForFinding(D,C,rateRelativeEffect({hits:M,n:c.length,restHits:y,restN:h.length,passRate:!1}));const O=i==="softBin"?t.sbinDefs:t.hbinDefs;k=Fe(r,xe(b,O,i==="softBin"?"SBin":"HBin"),C,o),v=`${i}:${b}`}S={...S,adjustedPValue:ie(S.pValue??1,p)};const B=Le(n.map(b=>b.replace(`${o}:`,""))).join("-"),z=i==="hardBin"||i==="softBin"?{kind:"bin",bin:s.variable.bin,regionKeys:n,dieKeys:f}:{kind:"region",regionFamily:o,regionKeys:n,dieKeys:f};return{...s,id:`${v}:${o}:${B}`,severity:F,comparison:{family:o,left:r,right:te(o)},effect:g,stats:S,summary:k,highlight:z,relatedIds:e.map(b=>b.id)}}function gn(e,t){const s=new Set(["ring","quadrant","sector"]),o=[],i=new Map;for(const f of e){if(!s.has(f.comparison.family)){o.push(f);continue}const a=mn(f),d=i.get(a)??[];d.push(f),i.set(a,d)}const n=[];for(const f of i.values()){if(f.length===1){n.push(f[0]);continue}const a=f[0].comparison.family;for(const d of findContiguousRuns(f,a,t.sectorCount,r=>me(r)[0]??""))n.push(d.length===1?d[0]:pn(d,t))}return[...o,...n]}function bn(e){const t=new Map,s=new Map;for(const i of e){const n=Re(i);i.hbin!==void 0&&i.hbin!==null&&(t.get(i.hbin)??t.set(i.hbin,new Set).get(i.hbin)).add(n),i.sbin!==void 0&&i.sbin!==null&&(s.get(i.sbin)??s.set(i.sbin,new Set).get(i.sbin)).add(n)}const o=new Set;for(const[i,n]of t)for(const[f,a]of s){if(n.size!==a.size)continue;let d=!0;for(const r of n)if(!a.has(r)){d=!1;break}d&&o.add(`${i}:${f}`)}return o}function yn(e,t){const s=new Set(t);let o;for(const i of e){const n=ae(i,s);if(n!==void 0&&n){if(i.sbin==null||o!==void 0&&i.sbin!==o)return;o=i.sbin}}if(o!==void 0){for(const i of e)if(i.sbin===o&&ae(i,s)!==!0)return;return o}}function Sn(e){return`${e.comparison.family}\0${e.comparison.left}`}export function redundancyFacts(e,t,s){return{coincident:bn(e),yieldSoftBin:yn(e,t),passBins:t,sectorCount:s}}const vn=3/5;function ft(e){return/^(?:lot-region:)?([^:|]+)/.exec(e.id)?.[1]??e.id}function wn(e){const t=me(e);if(t.length)return t;const s=/(ring|sector|quadrant):([^:|]+)$/.exec(e.id);return s?s[2].split("-").map(o=>`${s[1]}:${o}`):[]}function lt(e,t){const s=new Set;for(const o of wn(e)){const i=Ft(o,t);if(!i)return;for(const n of i)s.add(n)}return s.size?s:void 0}export function collapseRedundantFindings(e,t){const{coincident:s,yieldSoftBin:o,passBins:i}=t,n=(r,l)=>{r.absorbedIds=[...r.absorbedIds??[],l.id]},f=new Map;for(const r of e){const l=Sn(r);(f.get(l)??f.set(l,[]).get(l)).push(r)}const a=new Set;for(const r of f.values()){for(const u of r)if(!(u.variable.kind!=="hardBin"||u.variable.bin===void 0))for(const m of r){if(m.variable.kind!=="softBin"||m.variable.bin===void 0||a.has(m.id)||!s.has(`${u.variable.bin}:${m.variable.bin}`)||m.effect.direction!==u.effect.direction)continue;n(u,m),a.add(m.id);const c=u.variable.label.replace(/^HBin\s+/,""),h=m.variable.label.replace(/^SBin\s+/,""),p=c===h?`HBin and SBin ${c} (same dies)`:`${u.variable.label} and ${m.variable.label} (same dies)`;u.summary=u.summary.replace(u.variable.label,p),u.variable.label=p;break}const l=r.find(u=>u.variable.kind==="yield");if(l){for(const u of r)if(!(u===l||a.has(u.id)||!(u.variable.kind==="hardBin"&&i.length===1&&u.variable.bin===i[0]||u.variable.kind==="softBin"&&u.variable.bin===o))){n(l,u),a.add(u.id);for(const c of u.absorbedIds??[])l.absorbedIds=[...l.absorbedIds??[],c]}}}const d=new Map;for(const r of e){if(a.has(r.id)||r.comparison.family!=="sector"&&r.comparison.family!=="quadrant")continue;const l=[ft(r),r.variable.kind,r.variable.bin??"",r.variable.index??"",r.effect.direction].join("\0");(d.get(l)??d.set(l,[]).get(l)).push(r)}for(const r of d.values()){const l=[];for(const u of r.filter(m=>m.comparison.family==="sector")){const m=lt(u,t.sectorCount);if(m)for(const c of r.filter(h=>h.comparison.family==="quadrant")){const h=lt(c,t.sectorCount);if(!h)continue;let p=0;for(const S of m)h.has(S)&&p++;const g=m.size+h.size-p;p/g>=vn-1e-9&&l.push({sector:u,quadrant:c,overlap:p/g})}}l.sort((u,m)=>m.overlap-u.overlap);for(const{sector:u,quadrant:m}of l){if(a.has(u.id)||a.has(m.id))continue;const c=(m.stats.pValue??1)<(u.stats.pValue??1),[h,p]=c?[m,u]:[u,m];n(h,p),a.add(p.id),h.absorbedIds=[...h.absorbedIds??[],...p.absorbedIds??[]]}}}export function analyzeWaferMap(e,t={}){return analyzeWaferMapDecided(e,t)}export function analyzeWaferMapDecided(e,t={},s){const o=ne,i=ce,n=[];ne=n,ce=void 0;try{const f=$n(e,t,s);return tt.set(f,{candidates:n,facts:ce}),f}finally{ne=o,ce=i}}function $n(e,t,s){const{resolved:o,warnings:i}=resolveOptions(t),n=pt(e),f={...o,passBins:[...Vt(n,"analyzeWaferMap")],ringCount:Et(n,"analyzeWaferMap")},a=n.isLotStack,d=n.aggrMethod,r=$t(a,d),l=r,u=n.dies.filter(R=>Ge(R)),m=u.filter(qe),c=It(f,u.length);c.softPassBins=Te(u,c.passBins).soft;const h=rt(u,c.testNumbers,n.testDefs),p=c.enableTestValueAnalysis,g=p===!1?"off":p===!0?"done":s??gt(h.length*u.length),S=n.dies.filter(R=>Z(R)),F=S.filter(qe),k=r?u.filter(R=>R.sbin!==void 0):[],v=l&&u.some(R=>R.hbin!==void 0)||k.length>0||p!==!1,B=v?Mt(F,n.wafer,c.ringCount):[],z=v?Rt(F,n.wafer,c.ringCount):[],b=v?kt(F,n.reticleConfig):[],w=v?zt(S,!1):[],M=v?Dt(F,n.wafer,c.sectorCount):[],y=[],$=[];l&&$.push(...ue(u,B,c.passBins,c),...ue(u,z,c.passBins,c),...ue(u,b,c.passBins,c),...ue(u,w,c.passBins,c),...ue(u,M,c.passBins,c)),l&&$.push(...q(u,B,"hard",n.hbinDefs,"hardBin",c),...q(u,z,"hard",n.hbinDefs,"hardBin",c),...q(u,b,"hard",n.hbinDefs,"hardBin",c),...q(u,w,"hard",n.hbinDefs,"hardBin",c),...q(u,M,"hard",n.hbinDefs,"hardBin",c));{const R=k;$.push(...q(R,B,"soft",n.sbinDefs,"softBin",c),...q(R,z,"soft",n.sbinDefs,"softBin",c),...q(R,b,"soft",n.sbinDefs,"softBin",c),...q(R,w,"soft",n.sbinDefs,"softBin",c),...q(R,M,"soft",n.sbinDefs,"softBin",c))}const P=[...i];let C;if(p!==!1){if(g==="done"){for(const R of[B,z,b,w,M])y.push(...ln(u,R,h,n.testDefs,c));C=h}$.push(...cn(u,[B,z,b,w,M],n.testDefs,c)),$.push(...de(u,B,n.testDefs,c),...de(u,z,n.testDefs,c),...de(u,b,n.testDefs,c),...de(u,w,n.testDefs,c),...de(u,M,n.testDefs,c))}y.push(...on($,c));{const R=jt(a,l,n.testDefs);if(!a||l||R!==void 0){const T=He(m,n.wafer,{...c,isFailingDie:R});y.push(...T),l&&y.push(...Ut(m,n.wafer,n.hbinDefs,c,T))}}const V=gn(y,{eligibleDies:u,softEligibleDies:k,passBins:c.passBins,ringCount:c.ringCount,sectorCount:c.sectorCount,regionDies:{ring:new Set(B.flatMap(R=>Q(R.dies))),quadrant:new Set(z.flatMap(R=>Q(R.dies))),sector:new Set(M.flatMap(R=>Q(R.dies)))},hbinDefs:n.hbinDefs,sbinDefs:n.sbinDefs,testDefs:n.testDefs});y.length=0,y.push(...V),claimForBinClusters(y);let x;if(l){const R=Ct(m,n.wafer,{passBins:c.passBins,ringCount:c.ringCount});x=R??void 0;const T=R?dn(R,y,()=>{const W=new Set(c.passBins);return m.filter(he=>_e(he,W)===!0)},m,n.wafer,c.ringCount):void 0,E=T??R;if(T&&(x=T),E!=null&&E.pattern!=="random"&&E.pattern!=="none"){const W=Pt[E.pattern],he=E.confidence==="high"?"unusual":E.confidence==="medium"?"notable":"info",I=E.features,se=K=>`${(K*100).toFixed(0)}%`,ct=E.pattern==="edge-ring"||E.pattern==="edge-local"?`${se(I.edgeRdd)} of edge dies failing`:E.pattern==="center"?`centroid at ${se(I.centroidDistNorm)} of wafer radius from centre`:E.pattern==="donut"?`${se(Math.max(I.radialFailRates[1],I.radialFailRates[2]))} of dies failing at mid-radius, ${se(I.radialFailRates[0])} at the centre`:E.pattern==="scratch"?`a line ${Math.round(I.lineLength)} dies long and about ${Math.max(1,Math.round(I.lineWidth*2))} wide`:`${se(I.globalRdd)} of dies failing`,ut=new Set(c.passBins),Ke=u.filter(K=>_e(K,ut)===!0),{center:Oe,radius:dt}=n.wafer,mt=new Map(m.map(K=>[re(K),Tt(K.physX-Oe.x,K.physY-Oe.y,dt,c.ringCount)])),ht=new Set(y.flatMap(K=>Ue(K)?K.relatedIds??[]:[])),Ae=claimForPattern([E.pattern],he,y.filter(K=>!ht.has(K.id)),K=>K.comparison.family==="cluster"?[...new Set(K.highlight.kind==="dies"?K.highlight.dieKeys.map(oe=>mt.get(oe)??0):[])]:me(K).map(oe=>ee(oe).ring).filter(oe=>oe!==void 0),c.ringCount);y.push({id:`spatial-pattern:${E.pattern}`,level:"wafer",severity:he,variable:{kind:"spatialPattern",label:W},comparison:{family:"spatial-pattern",left:W,right:"Wafer"},effect:{direction:"different",effectSize:I.globalRdd},stats:{method:"geometry",sampleSizeLeft:Ke.length,sampleSizeRight:u.length},summary:`Spatial pattern: ${W.toLowerCase()} (${E.confidence} confidence) \u2014 ${ct}${E.note?` [${E.note}]`:""}`,highlight:{kind:"dies",dieKeys:Ke.map(K=>re(K))},relatedIds:Ae.length>0?Ae:void 0})}}y.sort((R,T)=>{const E=R.stats.adjustedPValue??R.stats.pValue??1,W=T.stats.adjustedPValue??T.stats.pValue??1;return E!==W?E-W:Math.abs(T.effect.absoluteDelta??0)-Math.abs(R.effect.absoluteDelta??0)});const D=Xt(n.dies,u.length,n.yield.yieldPercent,r);a&&(D.isLotStack=!0,d&&(D.aggregationMethod=d));const O=new Set(f.passBins),N={},A=(R,T)=>{const E=N[R]??={dieKeys:[],lostDies:0};E.dieKeys.push(re(T)),(!r||ae(T,O)!==!0)&&E.lostDies++},L=Zt(n.dies,n.testDefs,A);L&&(D.testSpecYield=L);const G=computeFunctionalYield(n.dies,n.testDefs,A);if(G&&(D.functionalYield=G),Object.keys(N).length&&(D.testFailures=N),x&&(D.spatialPattern=x),C===void 0&&c.computePerTestStats&&(C=h),h.length&&(D.testValueAnalysis=bt(g,h.length,u.length)),C?.length){const R=Jt(n.dies,C,n.testDefs,c.minimumSampleSize);R&&(D.perTestStats=R);const T=yt([{dies:n.dies}],n.testDefs,C);T&&(D.capability=T)}Object.assign(D,St(n.dies,n.testDefs));const _=vt([{dies:n.dies,wafer:n.wafer,passBins:c.passBins,ringCount:c.ringCount}]);_&&(D.regionYield=_),P.length>0&&(D.warnings=P);const X=redundancyFacts(u,c.passBins,c.sectorCount);return collapseRedundantFindings(y,X),ne&&(ce=X),{level:"wafer",hasNotableFindings:y.some(R=>R.severity==="notable"||R.severity==="unusual"),findings:y,wafer:n.wafer.metadata??void 0,analysisOptions:recordedOptions(t),stats:D}}
@@ -1 +1 @@
1
- import{GUIDE_SECTIONS as e}from"./guideSections.js";export const CHART_CATALOGUE=[{id:"bin-map",kind:"map",title:"Bin map",mode:["hardBin","softBin"],example:"display-control.html",about:"Each die coloured by its hard or soft bin, passing bins in greens and failing bins in other colours, to show where the failures are.",see:["test-value-map","bin-pareto"]},{id:"test-value-map",kind:"map",title:"Test value map",mode:["value"],example:"test-values.html",about:"Each die coloured by one test\u2019s value on a colour scale, with the test\u2019s limits on the colour bar, to show where on the wafer the value shifts.",see:["bin-map","limit-passfail-map","test-passfail-map","value-histogram"]},{id:"limit-passfail-map",kind:"map",title:"Limit pass/fail map",example:"test-values.html",about:"Each die coloured by whether its value for one test lies inside the test\u2019s limits, with the dies below the low limit and above the high limit marked apart, to show where a test fails its limits.",see:["test-value-map","test-passfail-map","pass-rate-by-test"]},{id:"test-passfail-map",kind:"map",title:"Test pass/fail map",example:"test-values.html",about:"Each die coloured by the pass or fail the tester recorded for one test, to show where a test failed, whether or not it has a measured value.",see:["limit-passfail-map","test-value-map","pass-rate-by-test"]},{id:"die-attribute-map",kind:"map",title:"Die attribute map",mode:["metadata"],example:"metadata-mode.html",about:"Each die coloured by an attribute the data carries (a test site, a probe step, a zone), to show whether a pattern follows it.",see:["bin-map"]},{id:"stacked-map",kind:"map",title:"Stacked map",mode:["stackedBins","stackedSoftBins","stackedValues"],example:"lot-stack-analysis.html",about:"The wafers of a lot laid over one another die by die: how often a bin occurs, or a value\u2019s mean, median or spread at each position, to show what repeats from wafer to wafer.",see:["difference-map","reticle-cell-yield"]},{id:"pat-verdict-map",kind:"map",title:"PAT verdict map",tab:"overview",about:"Each die coloured by its part average testing verdict (within the limits, an outlier or failing), on the map or on every wafer of a gallery, to show where the PAT outliers sit.",see:["part-average-testing-pat","bin-map","test-value-map"]},{id:"difference-map",kind:"map",title:"Difference map",card:"difference-map",tab:"distributions",about:"One group\u2019s wafer map less another\u2019s, die position by die position, to show where on the wafer they differ.",guide:[e.heatmap],see:["stacked-map","comparison-by-group"]},{id:"yield-by-wafer",kind:"chart",title:"Yield by wafer",cards:["card-yield"],tab:"overview",about:"Yield of each wafer or group: passing dies as a share of judged dies, with partial and edge-excluded dies left out. The line is the median bar.",see:["bin-pareto","what-divides-yield"]},{id:"bin-pareto",kind:"chart",title:"Bin pareto",cards:["card-bin-pareto"],tab:"overview",about:"Dies in each bin, largest first, so the bins that cost the most yield lead. Shown alone, the line is the running share of all dies.",see:["bin-map","pareto"]},{id:"pass-rate-by-test",kind:"chart",title:"Pass rate by test",cards:["card-pass-rate"],tab:"overview",about:"The share of judged dies that pass each test, lowest first, so the tests that fail the most dies lead.",see:["process-capability","bin-pareto"]},{id:"ring-yield",kind:"chart",title:"Ring yield",card:"ring-yield",tab:"overview",about:"Yield of each ring, from the wafer centre to its edge, to show a radial pattern.",see:["quadrant-yield","bin-map"]},{id:"quadrant-yield",kind:"chart",title:"Quadrant yield",card:"quadrant-yield",tab:"overview",about:"Yield of each quarter of the wafer, to show a one-sided pattern.",see:["ring-yield","bin-map"]},{id:"reticle-cell-yield",kind:"chart",title:"Reticle cell yield",card:"reticle-yield",tab:"overview",about:"Yield of each position in the reticle, pooled over every shot on every wafer. A cell low everywhere points at the mask rather than the wafer.",see:["stacked-map","ring-yield"]},{id:"test-value-distribution",kind:"chart",title:"Test value distribution",cards:["card-box"],tab:"distributions",about:"How one test\u2019s values spread on each wafer or group: the box holds the middle half of the dies, the line inside it is the median, and the whiskers reach the lowest and highest values.",see:["box-plot","value-histogram"]},{id:"value-histogram",kind:"chart",title:"Value histogram",cards:["card-histogram"],tab:"distributions",about:"How one test\u2019s values are distributed: the number of dies in each value range, with the test\u2019s limits marked.",see:["histogram","probability-plot","test-value-map"]},{id:"histogram-of-the-dies-picked",kind:"chart",title:"Histogram of the dies picked",cards:["drill-histogram"],tab:"drilldown",about:"How one test\u2019s values are distributed over the dies picked: the number of dies in each value range, with the test\u2019s limits marked.",see:["value-histogram"]},{id:"wafer-to-wafer-trend",kind:"chart",title:"Wafer-to-wafer trend",cards:["card-trend"],tab:"distributions",about:"Each wafer\u2019s mean of one test in wafer order, with a band of one standard deviation either side, to show drift through the lot.",guide:[e.bands],see:["control-chart","line-chart"]},{id:"test-scatter",kind:"chart",title:"Test scatter",cards:["card-scatter"],tab:"correlation",about:"One test against another, a point per die, to show whether the two move together. r is the correlation coefficient and n the number of dies.",guide:[e.fit],see:["test-correlation-matrix","scatter-plot"]},{id:"test-correlation-matrix",kind:"chart",title:"Test correlation matrix",card:"correlation",tab:"correlation",about:"The correlation of every pair of tests. A strong colour means two tests move together; click a cell to show the pair in the scatter.",see:["test-scatter","heatmap"]},{id:"process-capability",kind:"chart",title:"Process capability",card:"capability",tab:"distributions",about:"Every test with limits on one scale, the low limit at 0 and the high limit at 1, sorted lowest Ppk first, so the tests closest to their limits lead.",guide:[e.goal],see:["capability-goal-plot","pass-rate-by-test"]},{id:"comparison-by-group",kind:"table",title:"Comparison by group",card:"comparison",tab:"distributions",about:"Yield and each test compared between groups, counting each wafer once, with how likely a difference this large is by chance.",guide:[e.groups],see:["what-divides-yield","difference-map","box-plot"]},{id:"what-divides-yield",kind:"table",title:"What divides yield",card:"commonality",tab:"overview",about:"The wafer and lot fields ranked by how strongly they divide yield, as places to look for a cause.",guide:[e.dividesYield],see:["comparison-by-group","yield-by-wafer"]},{id:"part-average-testing-pat",kind:"table",title:"Part average testing (PAT)",card:"pat",tab:"overview",about:"Dies outside part average testing limits, set from each wafer\u2019s own spread of each test (the AEC-Q001 method), by wafer and by test.",guide:[e.pat],see:["pat-verdict-map","process-capability","scatter-plot"]},{id:"scatter-plot",kind:"chart",title:"Scatter plot",chart:"scatter",tab:"plots",about:"One field against another, a point per die or per wafer, to show whether they move together.",guide:[e.fit],see:["test-scatter","heatmap"]},{id:"histogram",kind:"chart",title:"Histogram",chart:"histogram",tab:"plots",about:"How a value is distributed: the number of dies or wafers in each value range.",see:["value-histogram","probability-plot","box-plot"]},{id:"box-plot",kind:"chart",title:"Box plot",chart:"box",tab:"plots",about:"How a value spreads in each category: the box holds the middle half, the line inside it is the median, and the whiskers reach the lowest and highest values.",guide:[e.groups],see:["test-value-distribution","nested-categories","probability-plot"]},{id:"bar-chart",kind:"chart",title:"Bar chart",chart:"bar",tab:"plots",about:"A count, a share or a summary value for each category, side by side.",see:["pareto","stacked-bars-and-shares","yield-by-wafer"]},{id:"line-chart",kind:"chart",title:"Line chart",chart:"line",tab:"plots",about:"A summary value in order along the X axis (wafer order, a test, a condition), to show a trend.",guide:[e.bands],see:["control-chart","sweep","wafer-to-wafer-trend"]},{id:"sweep",kind:"chart",title:"Sweep",chart:"sweep",tab:"plots",about:"A measured value against a swept condition, a curve per series, to show how the part responds across the range.",see:["line-chart"]},{id:"probability-plot",kind:"chart",title:"Probability plot",chart:"probability",tab:"plots",about:"The share of values at or below each value, a curve per colour, so whole distributions compare, tails included.",guide:[e.probability],see:["histogram","box-plot"]},{id:"control-chart",kind:"chart",title:"Control chart",chart:"control",tab:"plots",about:"One value per wafer in order against its centre line and control limits, with the points that break a Western Electric rule marked.",guide:[e.control],see:["wafer-to-wafer-trend","line-chart","capability-goal-plot"]},{id:"capability-goal-plot",kind:"chart",title:"Capability goal plot",chart:"goal",tab:"plots",about:"Each test with both limits placed by how far its mean is off centre and how wide its spread is, as shares of its limit window. A test outside the solid triangle is short of Ppk 1.33.",guide:[e.goal],see:["process-capability","control-chart"]},{id:"heatmap",kind:"chart",title:"Heatmap",chart:"heatmap",tab:"plots",about:"A value for every pair of two categories, as a colour, to show where the two interact.",guide:[e.heatmap],see:["test-correlation-matrix","difference-map","bar-chart"]},{id:"pareto",kind:"chart",title:"Pareto",tab:"plots",about:"Categories largest first with a line for their running share, to show which few account for most of the total.",see:["bin-pareto","bar-chart"]},{id:"stacked-bars-and-shares",kind:"chart",title:"Stacked bars and shares",tab:"plots",about:"Each bar split into its colours, as counts or as each colour\u2019s share of its own total, to show what a category is made of.",see:["bar-chart"]},{id:"nested-categories",kind:"chart",title:"Nested categories",tab:"plots",about:"A box or bar with categories inside categories, such as lots with their wafers, to show whether variation sits between or within the groups.",guide:[e.ranges],see:["box-plot","bar-chart"]},{id:"panels-small-multiples",kind:"chart",title:"Panels (small multiples)",tab:"plots",about:"One small chart per value of a field, on shared axes, to compare the same view across groups side by side.",guide:[e.ranges],see:["box-plot","scatter-plot","histogram"]},{id:"statistics-table",kind:"table",title:"Statistics table",tab:"data",about:"One row per test and group: the count, mean, spread, extremes, limits and capability, to read the numbers behind the charts.",see:["dies-table","process-capability"]},{id:"dies-table",kind:"table",title:"Dies table",tab:"data",about:"One row per die with its position, bin and values, to see exactly which dies a chart counts; it exports to CSV.",see:["wafers-table","statistics-table"]},{id:"wafers-table",kind:"table",title:"Wafers table",tab:"data",about:"One row per wafer with its attributes and its yield, to check what each wafer is and to compare them.",see:["dies-table","yield-by-wafer"]}];export function catalogueEntry(t){return CHART_CATALOGUE.find(a=>a.id===t)}
1
+ import{GUIDE_SECTIONS as e}from"./guideSections.js";export const CHART_CATALOGUE=[{id:"bin-map",kind:"map",title:"Bin map",mode:["hardBin","softBin"],example:"display-control.html",about:"Each die coloured by its hard or soft bin, passing bins in greens and failing bins in other colours, to show where the failures are.",see:["test-value-map","bin-pareto"]},{id:"test-value-map",kind:"map",title:"Test value map",mode:["value"],example:"test-values.html",about:"Each die coloured by one test\u2019s value on a colour scale, with the test\u2019s limits on the colour bar, to show where on the wafer the value shifts.",see:["bin-map","limit-passfail-map","test-passfail-map","value-histogram"]},{id:"limit-passfail-map",kind:"map",title:"Limit pass/fail map",example:"test-values.html",about:"Each die coloured by whether its value for one test lies inside the test\u2019s limits, with the dies below the low limit and above the high limit marked apart, to show where a test fails its limits.",see:["test-value-map","test-passfail-map","pass-rate-by-test"]},{id:"test-passfail-map",kind:"map",title:"Test pass/fail map",example:"test-values.html",about:"Each die coloured by the pass or fail the tester recorded for one test, to show where a test failed, whether or not it has a measured value.",see:["limit-passfail-map","test-value-map","pass-rate-by-test"]},{id:"die-attribute-map",kind:"map",title:"Die attribute map",mode:["metadata"],example:"metadata-mode.html",about:"Each die coloured by an attribute the data carries (a test site, a probe step, a zone), to show whether a pattern follows it.",see:["bin-map"]},{id:"stacked-map",kind:"map",title:"Stacked map",mode:["stackedBins","stackedSoftBins","stackedValues"],example:"lot-stack-analysis.html",about:"The wafers of a lot laid over one another die by die: how often a bin occurs, or a value\u2019s mean, median or spread at each position, to show what repeats from wafer to wafer.",see:["difference-map","reticle-cell-yield"]},{id:"pat-verdict-map",kind:"map",title:"PAT verdict map",tab:"overview",about:"Each die coloured by its part average testing verdict (within the limits, an outlier or failing), on the map or on every wafer of a gallery, to show where the PAT outliers sit.",see:["part-average-testing-pat","bin-map","test-value-map"]},{id:"difference-map",kind:"map",title:"Difference map",card:"difference-map",tab:"distributions",about:"One group\u2019s wafer map less another\u2019s, die position by die position, to show where on the wafer they differ.",guide:[e.heatmap],see:["stacked-map","comparison-by-group"]},{id:"yield-by-wafer",kind:"chart",title:"Yield by wafer",cards:["card-yield"],tab:"overview",about:"Yield of each wafer or group: passing dies as a share of judged dies, with partial and edge-excluded dies left out. The line is the median bar.",see:["bin-pareto","what-divides-yield"]},{id:"bin-pareto",kind:"chart",title:"Bin pareto",cards:["card-bin-pareto"],tab:"overview",about:"Dies in each bin, largest first, so the bins that cost the most yield lead. Shown alone, the line is the running share of all dies.",see:["bin-map","pareto"]},{id:"pass-rate-by-test",kind:"chart",title:"Pass rate by test",cards:["card-pass-rate"],tab:"overview",about:"The share of judged dies that pass each test, lowest first, so the tests that fail the most dies lead.",see:["process-capability","bin-pareto"]},{id:"ring-yield",kind:"chart",title:"Ring yield",card:"ring-yield",tab:"overview",about:"Yield of each ring, from the wafer centre to its edge, to show a radial pattern.",see:["ring-yield-by-wafer","quadrant-yield","bin-map"]},{id:"ring-yield-by-wafer",kind:"chart",title:"Ring yield by wafer",cards:["card-ring-wafer"],tab:"overview",about:"Yield of each ring on each wafer (or group), as a colour, to show whether a radial pattern is on every wafer or on one.",guide:[e.heatmap],see:["ring-yield","heatmap"]},{id:"quadrant-yield",kind:"chart",title:"Quadrant yield",card:"quadrant-yield",tab:"overview",about:"Yield of each quarter of the wafer, to show a one-sided pattern.",see:["quadrant-yield-by-wafer","ring-yield","bin-map"]},{id:"quadrant-yield-by-wafer",kind:"chart",title:"Quadrant yield by wafer",cards:["card-quadrant-wafer"],tab:"overview",about:"Yield of each quarter of the wafer on each wafer (or group), as a colour, to show whether a one-sided pattern is on every wafer or on one.",guide:[e.heatmap],see:["quadrant-yield","ring-yield-by-wafer","heatmap"]},{id:"reticle-cell-yield",kind:"chart",title:"Reticle cell yield",card:"reticle-yield",tab:"overview",about:"Yield of each position in the reticle, pooled over every shot on every wafer. A cell low everywhere points at the mask rather than the wafer.",see:["stacked-map","ring-yield"]},{id:"yield-by-site",kind:"chart",title:"Yield by site",cards:["card-site"],tab:"overview",about:"Yield of each test site (probe position): passing dies as a share of judged dies, over every wafer. Shown when the dies come from two sites or more.",see:["yield-by-wafer","reticle-cell-yield"]},{id:"re-probed-dies",kind:"chart",title:"Re-probed dies",cards:["card-reprobed"],tab:"overview",about:"The share of dies that were probed more than once, by ring on each wafer (or group), to show where the retests are. Drawn when the lot has re-probed dies.",guide:[e.heatmap],see:["yield-by-site","ring-yield-by-wafer","heatmap"]},{id:"tests-by-wafer",kind:"chart",title:"Tests by wafer",cards:["card-tests-wafer"],tab:"distributions",about:"The tests whose wafers (or groups) differ most, one row each, as a grid of z-scores: where a wafer is above or below that test\u2019s average.",guide:[e.heatmap],see:["heatmap","test-value-distribution","comparison-by-group"]},{id:"test-value-distribution",kind:"chart",title:"Test value distribution",cards:["card-box"],tab:"distributions",about:"How one test\u2019s values spread on each wafer or group: the box holds the middle half of the dies, the line inside it is the median, and the whiskers reach the lowest and highest values.",see:["box-plot","value-histogram"]},{id:"value-histogram",kind:"chart",title:"Value histogram",cards:["card-histogram"],tab:"distributions",about:"How one test\u2019s values are distributed: the number of dies in each value range, with the test\u2019s limits marked.",see:["histogram","probability-plot","test-value-map"]},{id:"histogram-of-the-dies-picked",kind:"chart",title:"Histogram of the dies picked",cards:["drill-histogram"],tab:"drilldown",about:"How one test\u2019s values are distributed over the dies picked: the number of dies in each value range, with the test\u2019s limits marked.",see:["value-histogram"]},{id:"wafer-to-wafer-trend",kind:"chart",title:"Wafer-to-wafer trend",cards:["card-trend"],tab:"distributions",about:"Each wafer\u2019s mean of one test in wafer order, with a band of one standard deviation either side, to show drift through the lot.",guide:[e.bands],see:["control-chart","line-chart"]},{id:"test-scatter",kind:"chart",title:"Test scatter",cards:["card-scatter"],tab:"correlation",about:"One test against another, a point per die, to show whether the two move together. r is the correlation coefficient and n the number of dies.",guide:[e.fit],see:["test-correlation-matrix","scatter-plot"]},{id:"test-correlation-matrix",kind:"chart",title:"Test correlation matrix",card:"correlation",tab:"correlation",about:"The correlation of every pair of tests. A strong colour means two tests move together; click a cell to show the pair in the scatter.",see:["test-scatter","heatmap"]},{id:"process-capability",kind:"chart",title:"Process capability",card:"capability",tab:"distributions",about:"Every test with limits on one scale, the low limit at 0 and the high limit at 1, sorted lowest Ppk first, so the tests closest to their limits lead.",guide:[e.goal],see:["capability-goal-plot","pass-rate-by-test"]},{id:"comparison-by-group",kind:"table",title:"Comparison by group",card:"comparison",tab:"distributions",about:"Yield and each test compared between groups, counting each wafer once, with how likely a difference this large is by chance.",guide:[e.groups],see:["what-divides-yield","difference-map","box-plot"]},{id:"what-divides-yield",kind:"table",title:"What divides yield",card:"commonality",tab:"overview",about:"The wafer and lot fields ranked by how strongly they divide yield, as places to look for a cause.",guide:[e.dividesYield],see:["comparison-by-group","yield-by-wafer"]},{id:"part-average-testing-pat",kind:"table",title:"Part average testing (PAT)",card:"pat",tab:"overview",about:"Dies outside part average testing limits, set from each wafer\u2019s own spread of each test (the AEC-Q001 method), by wafer and by test.",guide:[e.pat],see:["pat-verdict-map","process-capability","scatter-plot"]},{id:"scatter-plot",kind:"chart",title:"Scatter plot",chart:"scatter",tab:"plots",about:"One field against another, a point per die or per wafer, to show whether they move together.",guide:[e.fit],see:["test-scatter","heatmap"]},{id:"histogram",kind:"chart",title:"Histogram",chart:"histogram",tab:"plots",about:"How a value is distributed: the number of dies or wafers in each value range.",see:["value-histogram","probability-plot","box-plot"]},{id:"box-plot",kind:"chart",title:"Box plot",chart:"box",tab:"plots",about:"How a value spreads in each category: the box holds the middle half, the line inside it is the median, and the whiskers reach the lowest and highest values.",guide:[e.groups],see:["test-value-distribution","nested-categories","probability-plot"]},{id:"bar-chart",kind:"chart",title:"Bar chart",chart:"bar",tab:"plots",about:"A count, a share or a summary value for each category, side by side.",see:["pareto","stacked-bars-and-shares","yield-by-wafer"]},{id:"line-chart",kind:"chart",title:"Line chart",chart:"line",tab:"plots",about:"A summary value in order along the X axis (wafer order, a test, a condition), to show a trend.",guide:[e.bands],see:["control-chart","sweep","wafer-to-wafer-trend"]},{id:"sweep",kind:"chart",title:"Sweep",chart:"sweep",tab:"plots",about:"A measured value against a swept condition, a curve per series, to show how the part responds across the range.",see:["line-chart"]},{id:"probability-plot",kind:"chart",title:"Probability plot",chart:"probability",tab:"plots",about:"The share of values at or below each value, a curve per colour, so whole distributions compare, tails included.",guide:[e.probability],see:["histogram","box-plot"]},{id:"control-chart",kind:"chart",title:"Control chart",chart:"control",tab:"plots",about:"One value per wafer in order against its centre line and control limits, with the points that break a Western Electric rule marked.",guide:[e.control],see:["wafer-to-wafer-trend","line-chart","capability-goal-plot"]},{id:"capability-goal-plot",kind:"chart",title:"Capability goal plot",chart:"goal",tab:"plots",about:"Each test with both limits placed by how far its mean is off centre and how wide its spread is, as shares of its limit window. A test outside the solid triangle is short of Ppk 1.33.",guide:[e.goal],see:["process-capability","control-chart"]},{id:"heatmap",kind:"chart",title:"Heatmap",chart:"heatmap",tab:"plots",about:"A value for every pair of two categories, as a colour, to show where the two interact.",guide:[e.heatmap],see:["test-correlation-matrix","difference-map","bar-chart"]},{id:"pareto",kind:"chart",title:"Pareto",tab:"plots",about:"Categories largest first with a line for their running share, to show which few account for most of the total.",see:["bin-pareto","bar-chart"]},{id:"stacked-bars-and-shares",kind:"chart",title:"Stacked bars and shares",tab:"plots",about:"Each bar split into its colours, as counts or as each colour\u2019s share of its own total, to show what a category is made of.",see:["bar-chart"]},{id:"nested-categories",kind:"chart",title:"Nested categories",tab:"plots",about:"A box or bar with categories inside categories, such as lots with their wafers, to show whether variation sits between or within the groups.",guide:[e.ranges],see:["box-plot","bar-chart"]},{id:"panels-small-multiples",kind:"chart",title:"Panels (small multiples)",tab:"plots",about:"One small chart per value of a field, on shared axes, to compare the same view across groups side by side.",guide:[e.ranges],see:["box-plot","scatter-plot","histogram"]},{id:"statistics-table",kind:"table",title:"Statistics table",tab:"data",about:"One row per test and group: the count, mean, spread, extremes, limits and capability, to read the numbers behind the charts.",see:["dies-table","process-capability"]},{id:"dies-table",kind:"table",title:"Dies table",tab:"data",about:"One row per die with its position, bin and values, to see exactly which dies a chart counts; it exports to CSV.",see:["wafers-table","statistics-table"]},{id:"wafers-table",kind:"table",title:"Wafers table",tab:"data",about:"One row per wafer with its attributes and its yield, to check what each wafer is and to compare them.",see:["dies-table","yield-by-wafer"]}];export function catalogueEntry(t){return CHART_CATALOGUE.find(a=>a.id===t)}
@@ -1 +1 @@
1
- import{seededRandom as nt}from"./math.js";import{ringOf as it}from"../core/classify.js";import{compassBucket as st,sectorCompassNames as ot}from"./regions.js";import{diePassStatus as j,getDieKey as rt,gridKey as L}from"../core/dies.js";import{findConnectedComponents as at,LargestComponentSizer as ct}from"./connectedComponents.js";function lt(t,i){return ot(16)[st(t,i,16)]}function ut(t){if(t.length<2)return 0;const i=[...t].sort((s,n)=>s-n);let e=i[0]+2*Math.PI-i[i.length-1];for(let s=1;s<i.length;s++)e=Math.max(e,i[s]-i[s-1]);return 2*Math.PI-e}function ft(t,i,e,s){const n=s!==void 0?Math.abs(s):0;return t<=.01&&(i>=.25||n>=2||e>=.1)?"unusual":t<=.05&&(i>=.15||n>=1||e>=.03)?"notable":"info"}const ht=99,mt=9999,G=10;class dt{sizer;failCount;maxima=[];random;order;failing;constructor(i,e,s,n){this.sizer=i,this.failCount=s,this.random=nt(n),this.order=new Int32Array(e);for(let h=0;h<e;h++)this.order[h]=h;this.failing=new Uint8Array(e)}at(i){const{order:e,failing:s,failCount:n,random:h}=this,g=e.length;for(;this.maxima.length<=i;){for(let r=0;r<n;r++){const S=r+Math.floor(h()*(g-r)),p=e[r];e[r]=e[S],e[S]=p,s[e[r]]=1}this.maxima.push(this.sizer.largest(s));for(let r=0;r<n;r++)s[e[r]]=0}return this.maxima[i]}pValue(i,e){let s=0;for(let n=0;n<e;n++)if(this.at(n)>=i&&++s===G)return G/(n+1);return(1+s)/(1+e)}}function gt(t){let i=0,e=0;for(let s=0;s<t.length;s++){let n=Math.imul(t[s].x|0,2654435761)^Math.imul(t[s].y|0,2246822507);n=Math.imul(n^n>>>16,2146121005),n=Math.imul(n^n>>>15,2221713035),i=i+(n^n>>>16)|0,e=e+Math.imul(n,668265263)+374761393|0}return`${t.length}:${i>>>0}:${e>>>0}`}function pt(t,i){return t<=20?t:Math.min(i,Math.ceil(20*1.05**Math.ceil(Math.log(t/20)/Math.log(1.05))))}const yt=new Map,bt=new Map;function Z(t,i,e,s){let n=t.get(i);return n===void 0&&(n=s(),t.set(i,n),t.size>e&&t.delete(t.keys().next().value)),n}function xt(t,i,e,s){const n=t.length,h=Math.min(mt,Math.max(ht,Math.ceil(1/s))),g=gt(t),r=pt(i,n),S=Z(bt,`${g}:${r}`,16,()=>{const p=Z(yt,g,4,()=>new ct([...t].sort((x,m)=>x.y-m.y||x.x-m.x))),[,F,R]=g.split(":").map(Number);return new dt(p,n,r,(F^Math.imul(R,739982445)^Math.imul(r+1,2246822507))>>>0)});return e.map(p=>S.pValue(p,h))}export function buildClusterFindings(t,i,e){const{passBins:s,significanceLevel:n,minimumEffectSize:h,minimumRelativeEffect:g,minimumSampleSize:r,minimumClusterSize:S,ringCount:p}=e,F=new Set(s);if(e.isFailingDie||(t=t.filter(o=>j(o,F)!==void 0)),t.length<r)return[];const R=e.isFailingDie??(o=>j(o,F)===!1),x=t.filter(R),m=x.length/t.length;if(x.length===0)return[];if(m===1&&h>0&&g>0)return[];const D=t[0],V=D?D.width:10,K=D?D.height:10,X=Math.max(V,K)*1.5,B=new Map;for(const o of t)B.set(L(o.x,o.y),o);const T=Math.ceil(X/V),O=Math.ceil(X/K),q=at(x),U=[],v=[],Y=i.center.x,I=i.center.y,H=i.radius;for(const o of q){if(o.length<S)continue;const l=new Set(o.map(f=>L(f.x,f.y)));for(const f of o)for(let a=-O;a<=O;a++)for(let C=-T;C<=T;C++){const w=L(f.x+C,f.y+a);if(l.has(w))continue;const P=B.get(w);P&&Math.hypot(P.physX-f.physX,P.physY-f.physY)<=X&&l.add(w)}const u=[...l].map(f=>B.get(f)).filter(Boolean),d=o.length,y=u.length;if(y<r)continue;const M=d/y,z=M-m,$=m>0?z/m:void 0;(z>=h||$!==void 0&&$>=g)&&v.push({component:o,k:d,clusterRate:M,delta:z,relativeDelta:$})}if(!v.length)return[];const J=xt(t,x.length,v.map(o=>o.k),n);for(let o=0;o<v.length;o++){const{component:l,k:u,clusterRate:d,delta:y,relativeDelta:M}=v[o],z=J[o],$=z;if($>n)continue;const A=l.reduce((c,E)=>c+E.physX,0)/u,f=l.reduce((c,E)=>c+E.physY,0)/u;let a=l[0],C=1/0;for(const c of l){const E=Math.hypot(c.physX-A,c.physY-f);E<C&&(C=E,a=c)}const w=ut(l.map(c=>Math.atan2(c.physY-I,c.physX-Y)))*180/Math.PI,k=l.filter(c=>it(c.physX-Y,c.physY-I,H,p)===p).length>u/2&&w<120;if(k&&e.bin)continue;const N=k?"edge-arc":"cluster",_=lt(A-Y,f-I),b=e.bin,Q=k?`Edge arc ~${_}`:`Cluster at (${a.x}, ${a.y})`,W=u/t.length,tt=ft($,y,W,M),et=l.map(c=>rt(c));U.push({id:b?`${N}:hardBin:${b.bin}:${a.x},${a.y}`:`${N}:${a.x},${a.y}`,level:"wafer",severity:tt,variable:b?{kind:"hardBin",bin:b.bin,label:b.label}:{kind:"yield",label:"Yield"},comparison:{family:N,left:Q,right:"Rest of wafer"},effect:b?{direction:"higher",absoluteDelta:y,relativeDelta:M,effectSize:y}:{direction:"lower",absoluteDelta:-y,relativeDelta:M!==void 0?-M:void 0,effectSize:y},stats:{method:"permutation",pValue:z,adjustedPValue:$,sampleSizeLeft:u,sampleSizeRight:t.length-u},summary:k?`Edge arc near ${_}: ${u} contiguous failing dies (${(d*100).toFixed(0)}% vs ${(m*100).toFixed(0)}% background)`:b?`${b.label} cluster at (${a.x}, ${a.y}): ${u} contiguous dies (${(d*100).toFixed(0)}% vs ${(m*100).toFixed(0)}% background)`:`Failure cluster at (${a.x}, ${a.y}): ${u} contiguous failing dies (${(d*100).toFixed(0)}% vs ${(m*100).toFixed(0)}% background)`,highlight:{kind:"dies",dieKeys:et}})}return U.sort((o,l)=>{const u=o.stats.pValue??1,d=l.stats.pValue??1;return u!==d?u-d:Math.abs(l.effect.effectSize??0)-Math.abs(o.effect.effectSize??0)})}
1
+ import{seededRandom as ot}from"./math.js";import{ringOf as at}from"../core/classify.js";import{compassBucket as rt,sectorCompassNames as lt}from"./regions.js";import{diePassStatus as G,getDieKey as ct,gridKey as V}from"../core/dies.js";import{findConnectedComponents as ut,LargestComponentSizer as ft}from"./connectedComponents.js";import{median as H}from"../core/utils.js";function ht(t,i){return lt(16)[rt(t,i,16)]}function mt(t){if(t.length<2)return 0;const i=[...t].sort((s,n)=>s-n);let e=i[0]+2*Math.PI-i[i.length-1];for(let s=1;s<i.length;s++)e=Math.max(e,i[s]-i[s-1]);return 2*Math.PI-e}function dt(t,i,e,s){const n=s!==void 0?Math.abs(s):0;return t<=.01&&(i>=.25||n>=2||e>=.1)?"unusual":t<=.05&&(i>=.15||n>=1||e>=.03)?"notable":"info"}const gt=99,pt=9999,W=10;class yt{sizer;failCount;maxima=[];random;order;failing;constructor(i,e,s,n){this.sizer=i,this.failCount=s,this.random=ot(n),this.order=new Int32Array(e);for(let h=0;h<e;h++)this.order[h]=h;this.failing=new Uint8Array(e)}at(i){const{order:e,failing:s,failCount:n,random:h}=this,g=e.length;for(;this.maxima.length<=i;){for(let a=0;a<n;a++){const S=a+Math.floor(h()*(g-a)),p=e[a];e[a]=e[S],e[S]=p,s[e[a]]=1}this.maxima.push(this.sizer.largest(s));for(let a=0;a<n;a++)s[e[a]]=0}return this.maxima[i]}pValue(i,e){let s=0;for(let n=0;n<e;n++)if(this.at(n)>=i&&++s===W)return W/(n+1);return(1+s)/(1+e)}}function bt(t){let i=0,e=0;for(let s=0;s<t.length;s++){let n=Math.imul(t[s].x|0,2654435761)^Math.imul(t[s].y|0,2246822507);n=Math.imul(n^n>>>16,2146121005),n=Math.imul(n^n>>>15,2221713035),i=i+(n^n>>>16)|0,e=e+Math.imul(n,668265263)+374761393|0}return`${t.length}:${i>>>0}:${e>>>0}`}function xt(t,i){return t<=20?t:Math.min(i,Math.ceil(20*1.05**Math.ceil(Math.log(t/20)/Math.log(1.05))))}const Mt=new Map,$t=new Map;function Z(t,i,e,s){let n=t.get(i);return n===void 0&&(n=s(),t.set(i,n),t.size>e&&t.delete(t.keys().next().value)),n}function St(t,i,e,s){const n=t.length,h=Math.min(pt,Math.max(gt,Math.ceil(1/s))),g=bt(t),a=xt(i,n),S=Z($t,`${g}:${a}`,16,()=>{const p=Z(Mt,g,4,()=>new ft([...t].sort((x,m)=>x.y-m.y||x.x-m.x))),[,F,D]=g.split(":").map(Number);return new yt(p,n,a,(F^Math.imul(D,739982445)^Math.imul(a+1,2246822507))>>>0)});return e.map(p=>S.pValue(p,h))}export function buildClusterFindings(t,i,e){const{passBins:s,significanceLevel:n,minimumEffectSize:h,minimumRelativeEffect:g,minimumSampleSize:a,minimumClusterSize:S,ringCount:p}=e,F=new Set(s);if(e.isFailingDie||(t=t.filter(o=>G(o,F)!==void 0)),t.length<a)return[];const D=e.isFailingDie??(o=>G(o,F)===!1),x=t.filter(D),m=x.length/t.length;if(x.length===0)return[];if(m===1&&h>0&&g>0)return[];const q=Math.max(1,Math.floor(t.length/1001)),R=[],X=[];for(let o=0;o<t.length;o+=q)R.push(t[o].width),X.push(t[o].height);const K=R.length?H(R):10,T=X.length?H(X):10,B=Math.max(K,T)*1.5,Y=new Map;for(const o of t)Y.set(V(o.x,o.y),o);const O=Math.ceil(B/K),U=Math.ceil(B/T),J=ut(x),_=[],v=[],I=i.center.x,A=i.center.y,Q=i.radius;for(const o of J){if(o.length<S)continue;const c=new Set(o.map(f=>V(f.x,f.y)));for(const f of o)for(let r=-U;r<=U;r++)for(let C=-O;C<=O;C++){const w=V(f.x+C,f.y+r);if(c.has(w))continue;const P=Y.get(w);P&&Math.hypot(P.physX-f.physX,P.physY-f.physY)<=B&&c.add(w)}const u=[...c].map(f=>Y.get(f)).filter(Boolean),d=o.length,y=u.length;if(y<a)continue;const M=d/y,z=M-m,$=m>0?z/m:void 0;(z>=h||$!==void 0&&$>=g)&&v.push({component:o,k:d,clusterRate:M,delta:z,relativeDelta:$})}if(!v.length)return[];const tt=St(t,x.length,v.map(o=>o.k),n);for(let o=0;o<v.length;o++){const{component:c,k:u,clusterRate:d,delta:y,relativeDelta:M}=v[o],z=tt[o],$=z;if($>n)continue;const N=c.reduce((l,E)=>l+E.physX,0)/u,f=c.reduce((l,E)=>l+E.physY,0)/u;let r=c[0],C=1/0;for(const l of c){const E=Math.hypot(l.physX-N,l.physY-f);E<C&&(C=E,r=l)}const w=mt(c.map(l=>Math.atan2(l.physY-A,l.physX-I)))*180/Math.PI,k=c.filter(l=>at(l.physX-I,l.physY-A,Q,p)===p).length>u/2&&w<120;if(k&&e.bin)continue;const L=k?"edge-arc":"cluster",j=ht(N-I,f-A),b=e.bin,et=k?`Edge arc ~${j}`:`Cluster at (${r.x}, ${r.y})`,nt=u/t.length,it=dt($,y,nt,M),st=c.map(l=>ct(l));_.push({id:b?`${L}:hardBin:${b.bin}:${r.x},${r.y}`:`${L}:${r.x},${r.y}`,level:"wafer",severity:it,variable:b?{kind:"hardBin",bin:b.bin,label:b.label}:{kind:"yield",label:"Yield"},comparison:{family:L,left:et,right:"Rest of wafer"},effect:b?{direction:"higher",absoluteDelta:y,relativeDelta:M,effectSize:y}:{direction:"lower",absoluteDelta:-y,relativeDelta:M!==void 0?-M:void 0,effectSize:y},stats:{method:"permutation",pValue:z,adjustedPValue:$,sampleSizeLeft:u,sampleSizeRight:t.length-u},summary:k?`Edge arc near ${j}: ${u} contiguous failing dies (${(d*100).toFixed(0)}% vs ${(m*100).toFixed(0)}% background)`:b?`${b.label} cluster at (${r.x}, ${r.y}): ${u} contiguous dies (${(d*100).toFixed(0)}% vs ${(m*100).toFixed(0)}% background)`:`Failure cluster at (${r.x}, ${r.y}): ${u} contiguous failing dies (${(d*100).toFixed(0)}% vs ${(m*100).toFixed(0)}% background)`,highlight:{kind:"dies",dieKeys:st}})}return _.sort((o,c)=>{const u=o.stats.pValue??1,d=c.stats.pValue??1;return u!==d?u-d:Math.abs(c.effect.effectSize??0)-Math.abs(o.effect.effectSize??0)})}
@@ -0,0 +1,11 @@
1
+ import type { Die } from '../core/dies.js';
2
+ import { type TestDef } from '../renderer/buildWaferMap.js';
3
+ import type { CorrelationMatrix } from './correlation.js';
4
+ /** At most this many tests, the ones that fail on most dies, enter the matrix. */
5
+ export declare const CO_FAILURE_TESTS = 100;
6
+ /**
7
+ * The failing dies of every test with limits that fails on two dies or more, compared pair by pair. A pair's `r` is the share
8
+ * of dies failing either that fail both (null when neither fails anywhere) and its `n` is the dies failing either.
9
+ */
10
+ export declare function buildCoFailureMatrix(dies: readonly Die[], testDefs: readonly TestDef[]): CorrelationMatrix;
11
+ //# sourceMappingURL=coFailure.d.ts.map
@@ -0,0 +1 @@
1
+ import{isParametricTest as d}from"../renderer/buildWaferMap.js";import{markedTestLabel as x,derivedFields as b}from"../renderer/testLabel.js";import{dieFailsTest as F}from"./testPassRate.js";export const CO_FAILURE_TESTS=100;const I=r=>r.limitLow!==void 0||r.limitHigh!==void 0;export function buildCoFailureMatrix(r,g){const i=g.filter(t=>t.testNumber!==void 0&&d(t)&&I(t));if(i.length<2)return{tests:[],cells:[]};const o=new Map,h=[];for(const t of r){let e;for(let n=0;n<i.length;n++)F(t,i[n],"spec")===!0&&((e??=[]).push(n),o.set(n,(o.get(n)??0)+1));e&&h.push(e)}const s=[...o.entries()].filter(([,t])=>t>=2).sort((t,e)=>e[1]-t[1]).slice(0,CO_FAILURE_TESTS).map(([t])=>t).sort((t,e)=>t-e);if(s.length<2)return{tests:[],cells:[]};const u=new Map(s.map((t,e)=>[t,e])),a=new Float64Array(s.length*s.length);for(const t of h){const e=t.filter(n=>u.has(n)).map(n=>u.get(n));for(let n=0;n<e.length;n++)for(let l=n+1;l<e.length;l++)a[e[n]*s.length+e[l]]++}const p=s.map(t=>({testNumber:i[t].testNumber,label:x(i[t],i[t].testNumber),unit:i[t].unit,...b(i[t])})),f=[];for(let t=0;t<s.length;t++)for(let e=0;e<s.length;e++){if(e===t){f.push({xIndex:e,yIndex:t,r:1,n:o.get(s[e])??0});continue}const n=Math.min(e,t),l=Math.max(e,t),m=a[n*s.length+l],c=(o.get(s[e])??0)+(o.get(s[t])??0)-m;f.push({xIndex:e,yIndex:t,r:c>0?m/c:null,n:c})}return{tests:p,cells:f}}
@@ -110,6 +110,13 @@ export declare const CORRELATION_WORK_BUDGET = 250000000;
110
110
  export declare const CORRELATION_SCORE_BUDGET = 25000000;
111
111
  /** The sentence a panel puts next to a matrix built from a sample of the dies or the tests. */
112
112
  export declare function correlationSampleNote(m: Pick<CorrelationMatrix, 'sample' | 'testSample'>): string | undefined;
113
+ /**
114
+ * The dies of several groups with each group's mean taken off every test's values, as dies of test values only, for a
115
+ * correlation within groups: the correlation that is left when a difference between groups (a corner lot's slow and fast
116
+ * wafers moving every test together) is removed. A group with one value of a test contributes none of it. Above the die
117
+ * budget an even spread of the dies is kept, as the matrix itself would; the means are those of every die.
118
+ */
119
+ export declare function demeanWithinGroups(groups: ReadonlyArray<ReadonlyArray<Die>>, testDefs: TestDef[]): Die[];
113
120
  /**
114
121
  * Pearson correlation matrix for the parametric tests in `testDefs` across the
115
122
  * dies in `dies` — every test up to `CORRELATION_TEST_BUDGET` (above it, the
@@ -1 +1 @@
1
- import{dieHasValues as Y,testValue as E}from"../core/dieTable.js";import{isParametricTest as v}from"../renderer/buildWaferMap.js";import{markedTestLabel as P,derivedFields as k}from"../renderer/testLabel.js";export function pearsonFromSums(e,o,i,d,m,c){if(e<3)return null;const g=o/e,u=i/e,a=c/e-g*u,p=d/e-g*g,b=m/e-u*u,M=Math.sqrt(p*b);return M===0?null:Math.max(-1,Math.min(1,a/M))}export function pearsonOfPairs(e){let o=0,i=0,d=0,m=0,c=0,g=0;for(let u=0;u<e.length;u++){const{x:a,y:p}=e[u];!Number.isFinite(a)||!Number.isFinite(p)||(o++,i+=a,d+=p,m+=a*a,c+=p*p,g+=a*p)}return{r:pearsonFromSums(o,i,d,m,c,g),n:o}}export const CORRELATION_DIE_BUDGET=25e3;function O(e,o){const i=[],d=e/o;for(let m=0;m<o;m++)i.push(Math.floor(m*d));return i}export const CORRELATION_TEST_BUDGET=300,CORRELATION_WORK_BUDGET=25e7,CORRELATION_SCORE_BUDGET=25e6;export function correlationSampleNote(e){const o=[];return e.testSample&&o.push(`Among the ${e.testSample.used.toLocaleString()} of ${e.testSample.of.toLocaleString()} tests with the most dies outside their limits, then the widest spread`),e.sample&&o.push(`${o.length?"from":"From"} a ${e.sample.used.toLocaleString()}-die sample of ${e.sample.of.toLocaleString()}, spread evenly across the lot`),o.length?o.join(", "):void 0}function D(e,o,i,d){const m=e.length,c=new Float64Array(m),g=new Float64Array(m),u=new Float64Array(m),a=new Float64Array(m),p=e.map(r=>o.get(r.testNumber)?.limitLow),b=e.map(r=>o.get(r.testNumber)?.limitHigh);for(const r of i)for(let n=0;n<m;n++){const t=E(r,e[n].testNumber);t===void 0||!Number.isFinite(t)||(c[n]++,g[n]+=t,u[n]+=t*t,(p[n]!==void 0&&t<p[n]||b[n]!==void 0&&t>b[n])&&a[n]++)}const M=r=>{if(c[r]<3)return-1;const n=g[r]/c[r],t=Math.sqrt(Math.max(0,u[r]/c[r]-n*n)),f=p[r]!==void 0&&b[r]!==void 0?b[r]-p[r]:Math.abs(n);return f>0?t/f:0},h=e.map((r,n)=>({i:n,fails:c[n]<3?-1:a[n],spread:M(n)}));return h.sort((r,n)=>n.fails-r.fails||n.spread-r.spread||r.i-n.i),h.slice(0,d).map(r=>r.i).sort((r,n)=>r-n).map(r=>e[r])}function z(e){return e.filter(o=>o.testNumber!==void 0&&v(o)).map(o=>({testNumber:o.testNumber,label:P(o,o.testNumber),unit:o.unit,...k(o)}))}export function buildCorrelationMatrix(e,o){const i=z(o);if(i.length<2)return{tests:i,cells:[]};const d=e.filter(Y),c=d.length>CORRELATION_DIE_BUDGET?O(d.length,CORRELATION_DIE_BUDGET).map(s=>d[s]):d,g=i.length>CORRELATION_TEST_BUDGET,u=g?D(i,new Map(o.flatMap(s=>s.testNumber===void 0?[]:[[s.testNumber,s]])),c.length*i.length>CORRELATION_SCORE_BUDGET?O(c.length,Math.max(1,Math.floor(CORRELATION_SCORE_BUDGET/i.length))).map(s=>c[s]):c,CORRELATION_TEST_BUDGET):i,a=u.length*(u.length-1)/2,p=Math.max(1,Math.floor(CORRELATION_WORK_BUDGET/Math.max(1,a))),b=c.length>p?O(c.length,p).map(s=>c[s]):c,M=b.length<d.length,h=u.length,r=u.map(s=>s.testNumber),n=h*(h-1)/2,t=new Float64Array(n),f=new Float64Array(h),x=new Float64Array(n),N=new Float64Array(n),y=new Float64Array(n),w=new Float64Array(n),S=new Float64Array(n);function C(s,l){return s*h-(s*(s+1)>>1)+(l-s-1)}const _=new Float64Array(h),T=new Uint8Array(h);for(const s of b){T.fill(0);for(let l=0;l<h;l++){const I=E(s,r[l]);I!==void 0&&Number.isFinite(I)&&(_[l]=I,T[l]=1)}for(let l=0;l<h;l++){if(!T[l])continue;f[l]++;const I=_[l];for(let F=l+1;F<h;F++){if(!T[F])continue;const A=_[F],R=C(l,F);t[R]++,x[R]+=I,N[R]+=A,y[R]+=I*I,w[R]+=A*A,S[R]+=I*A}}}const X=s=>pearsonFromSums(t[s],x[s],N[s],y[s],w[s],S[s]),L=[];for(let s=0;s<h;s++)for(let l=0;l<h;l++){if(l===s){L.push({xIndex:l,yIndex:s,r:1,n:f[l]});continue}const I=Math.min(l,s),F=Math.max(l,s),A=C(I,F);L.push({xIndex:l,yIndex:s,r:X(A),n:t[A]})}return{tests:u,cells:L,...M?{sample:{of:d.length,used:b.length}}:{},...g?{testSample:{of:i.length,used:u.length}}:{}}}export function filterCorrelationMatrix(e,{threshold:o=.3,minTests:i=6,maxTests:d=20}={}){const m=[];let c=0,g=0,u=null;for(const t of e.cells){if(t.xIndex>=t.yIndex||t.r===null)continue;const f=Math.abs(t.r);m.push({xi:t.xIndex,yi:t.yIndex,absR:f}),(u===null||f>Math.abs(u.r))&&(u={xLabel:e.tests[t.xIndex].label,yLabel:e.tests[t.yIndex].label,r:t.r})}m.sort((t,f)=>f.absR-t.absR);const a=new Set;for(const{xi:t,yi:f,absR:x}of m){const N=x<o;a.size>=d||N&&a.size>=i||(a.add(t),a.size<d&&a.add(f))}if(a.size<Math.min(i,e.tests.length))for(let t=0;t<e.tests.length&&a.size<Math.min(d,i,e.tests.length);t++)a.add(t);const p=(()=>{const t=Array.from(a),f=new Map,x=new Map;for(const{xi:y,yi:w,absR:S}of m)!a.has(y)||!a.has(w)||(f.set(y,(f.get(y)??0)+S),f.set(w,(f.get(w)??0)+S),x.set(y,(x.get(y)??0)+1),x.set(w,(x.get(w)??0)+1));const N=y=>(x.get(y)??0)>0?f.get(y)/x.get(y):0;return t.sort((y,w)=>N(w)-N(y))})(),b=p.map(t=>e.tests[t]),M=new Map(p.map((t,f)=>[t,f])),h=new Set(b.map(t=>t.testNumber)),r=e.cells.filter(t=>h.has(e.tests[t.xIndex].testNumber)&&h.has(e.tests[t.yIndex].testNumber)).map(t=>({xIndex:M.get(t.xIndex),yIndex:M.get(t.yIndex),r:t.r,n:t.n}));let n=0;for(const{xi:t,yi:f,absR:x}of m)a.has(t)&&a.has(f)?x>=.7?c++:x>=.4&&g++:x<o&&n++;return{matrix:{tests:b,cells:r},strongPairs:c,moderatePairs:g,hiddenWeakPairs:n,strongestPair:u}}
1
+ import{dieHasValues as C,testValue as _}from"../core/dieTable.js";import{isParametricTest as k}from"../renderer/buildWaferMap.js";import{markedTestLabel as P,derivedFields as D}from"../renderer/testLabel.js";export function pearsonFromSums(e,o,u,h,l,d){if(e<3)return null;const c=o/e,i=u/e,n=d/e-c*i,f=h/e-c*c,g=l/e-i*i,x=Math.sqrt(f*g);return x===0?null:Math.max(-1,Math.min(1,n/x))}export function pearsonOfPairs(e){let o=0,u=0,h=0,l=0,d=0,c=0;for(let i=0;i<e.length;i++){const{x:n,y:f}=e[i];!Number.isFinite(n)||!Number.isFinite(f)||(o++,u+=n,h+=f,l+=n*n,d+=f*f,c+=n*f)}return{r:pearsonFromSums(o,u,h,l,d,c),n:o}}export const CORRELATION_DIE_BUDGET=25e3;function E(e,o){const u=[],h=e/o;for(let l=0;l<o;l++)u.push(Math.floor(l*h));return u}export const CORRELATION_TEST_BUDGET=300,CORRELATION_WORK_BUDGET=25e7,CORRELATION_SCORE_BUDGET=25e6;export function correlationSampleNote(e){const o=[];return e.testSample&&o.push(`Among the ${e.testSample.used.toLocaleString()} of ${e.testSample.of.toLocaleString()} tests with the most dies outside their limits, then the widest spread`),e.sample&&o.push(`${o.length?"from":"From"} a ${e.sample.used.toLocaleString()}-die sample of ${e.sample.of.toLocaleString()}, spread evenly across the lot`),o.length?o.join(", "):void 0}function z(e,o,u,h){const l=e.length,d=new Float64Array(l),c=new Float64Array(l),i=new Float64Array(l),n=new Float64Array(l),f=e.map(a=>o.get(a.testNumber)?.limitLow),g=e.map(a=>o.get(a.testNumber)?.limitHigh);for(const a of u)for(let s=0;s<l;s++){const t=_(a,e[s].testNumber);t===void 0||!Number.isFinite(t)||(d[s]++,c[s]+=t,i[s]+=t*t,(f[s]!==void 0&&t<f[s]||g[s]!==void 0&&t>g[s])&&n[s]++)}const x=a=>{if(d[a]<3)return-1;const s=c[a]/d[a],t=Math.sqrt(Math.max(0,i[a]/d[a]-s*s)),p=f[a]!==void 0&&g[a]!==void 0?g[a]-f[a]:Math.abs(s);return p>0?t/p:0},y=e.map((a,s)=>({i:s,fails:d[s]<3?-1:n[s],spread:x(s)}));return y.sort((a,s)=>s.fails-a.fails||s.spread-a.spread||a.i-s.i),y.slice(0,h).map(a=>a.i).sort((a,s)=>a-s).map(a=>e[a])}function X(e){return e.filter(o=>o.testNumber!==void 0&&k(o)).map(o=>({testNumber:o.testNumber,label:P(o,o.testNumber),unit:o.unit,...D(o)}))}export function demeanWithinGroups(e,o){const u=X(o).map(c=>c.testNumber),h=e.map(c=>u.map(i=>{let n=0,f=0;for(const g of c){const x=_(g,i);x!==void 0&&Number.isFinite(x)&&(n++,f+=x)}return n?f/n:0})),l=[];return e.forEach((c,i)=>{for(const n of c)C(n)&&l.push({die:n,group:i})}),(l.length>CORRELATION_DIE_BUDGET?E(l.length,CORRELATION_DIE_BUDGET).map(c=>l[c]):l).map(({die:c,group:i})=>{const n={};return u.forEach((f,g)=>{const x=_(c,f);x!==void 0&&Number.isFinite(x)&&(n[f]=x-h[i][g])}),{x:c.x,y:c.y,testValues:n}})}export function buildCorrelationMatrix(e,o){const u=X(o);if(u.length<2)return{tests:u,cells:[]};const h=e.filter(C),d=h.length>CORRELATION_DIE_BUDGET?E(h.length,CORRELATION_DIE_BUDGET).map(r=>h[r]):h,c=u.length>CORRELATION_TEST_BUDGET,i=c?z(u,new Map(o.flatMap(r=>r.testNumber===void 0?[]:[[r.testNumber,r]])),d.length*u.length>CORRELATION_SCORE_BUDGET?E(d.length,Math.max(1,Math.floor(CORRELATION_SCORE_BUDGET/u.length))).map(r=>d[r]):d,CORRELATION_TEST_BUDGET):u,n=i.length*(i.length-1)/2,f=Math.max(1,Math.floor(CORRELATION_WORK_BUDGET/Math.max(1,n))),g=d.length>f?E(d.length,f).map(r=>d[r]):d,x=g.length<h.length,y=i.length,a=i.map(r=>r.testNumber),s=y*(y-1)/2,t=new Float64Array(s),p=new Float64Array(y),b=new Float64Array(s),M=new Float64Array(s),w=new Float64Array(s),I=new Float64Array(s),S=new Float64Array(s);function v(r,m){return r*y-(r*(r+1)>>1)+(m-r-1)}const L=new Float64Array(y),T=new Uint8Array(y);for(const r of g){T.fill(0);for(let m=0;m<y;m++){const N=_(r,a[m]);N!==void 0&&Number.isFinite(N)&&(L[m]=N,T[m]=1)}for(let m=0;m<y;m++){if(!T[m])continue;p[m]++;const N=L[m];for(let F=m+1;F<y;F++){if(!T[F])continue;const A=L[F],R=v(m,F);t[R]++,b[R]+=N,M[R]+=A,w[R]+=N*N,I[R]+=A*A,S[R]+=N*A}}}const Y=r=>pearsonFromSums(t[r],b[r],M[r],w[r],I[r],S[r]),O=[];for(let r=0;r<y;r++)for(let m=0;m<y;m++){if(m===r){O.push({xIndex:m,yIndex:r,r:1,n:p[m]});continue}const N=Math.min(m,r),F=Math.max(m,r),A=v(N,F);O.push({xIndex:m,yIndex:r,r:Y(A),n:t[A]})}return{tests:i,cells:O,...x?{sample:{of:h.length,used:g.length}}:{},...c?{testSample:{of:u.length,used:i.length}}:{}}}export function filterCorrelationMatrix(e,{threshold:o=.3,minTests:u=6,maxTests:h=20}={}){const l=[];let d=0,c=0,i=null;for(const t of e.cells){if(t.xIndex>=t.yIndex||t.r===null)continue;const p=Math.abs(t.r);l.push({xi:t.xIndex,yi:t.yIndex,absR:p}),(i===null||p>Math.abs(i.r))&&(i={xLabel:e.tests[t.xIndex].label,yLabel:e.tests[t.yIndex].label,r:t.r})}l.sort((t,p)=>p.absR-t.absR);const n=new Set;for(const{xi:t,yi:p,absR:b}of l){const M=b<o;n.size>=h||M&&n.size>=u||(n.add(t),n.size<h&&n.add(p))}if(n.size<Math.min(u,e.tests.length))for(let t=0;t<e.tests.length&&n.size<Math.min(h,u,e.tests.length);t++)n.add(t);const f=(()=>{const t=Array.from(n),p=new Map,b=new Map;for(const{xi:w,yi:I,absR:S}of l)!n.has(w)||!n.has(I)||(p.set(w,(p.get(w)??0)+S),p.set(I,(p.get(I)??0)+S),b.set(w,(b.get(w)??0)+1),b.set(I,(b.get(I)??0)+1));const M=w=>(b.get(w)??0)>0?p.get(w)/b.get(w):0;return t.sort((w,I)=>M(I)-M(w))})(),g=f.map(t=>e.tests[t]),x=new Map(f.map((t,p)=>[t,p])),y=new Set(g.map(t=>t.testNumber)),a=e.cells.filter(t=>y.has(e.tests[t.xIndex].testNumber)&&y.has(e.tests[t.yIndex].testNumber)).map(t=>({xIndex:x.get(t.xIndex),yIndex:x.get(t.yIndex),r:t.r,n:t.n}));let s=0;for(const{xi:t,yi:p,absR:b}of l)n.has(t)&&n.has(p)?b>=.7?d++:b>=.4&&c++:b<o&&s++;return{matrix:{tests:g,cells:a},strongPairs:d,moderatePairs:c,hiddenWeakPairs:s,strongestPair:i}}