import { GROUP_COLORS } from './constants' import type { Detection, DiameterGroup } from './types' function diameterOf(d: Detection): number { return Math.min(d.xmax - d.xmin, d.ymax - d.ymin) } function kMeans1D(values: number[], k: number, iterations = 20): number[] { if (values.length === 0 || k <= 0) { return [] } const sorted = [...values].sort((a, b) => a - b) const centroids = Array.from({ length: k }, (_, i) => { const idx = Math.floor((i + 0.5) * (sorted.length / k)) return sorted[Math.min(idx, sorted.length - 1)] }) for (let iter = 0; iter < iterations; iter++) { const groups: number[][] = Array.from({ length: k }, () => []) for (const v of values) { let best = 0 let bestDist = Infinity for (let c = 0; c < k; c++) { const dist = Math.abs(v - centroids[c]) if (dist < bestDist) { bestDist = dist best = c } } groups[best].push(v) } for (let c = 0; c < k; c++) { if (groups[c].length > 0) { centroids[c] = groups[c].reduce((a, b) => a + b, 0) / groups[c].length } } } return centroids.sort((a, b) => a - b) } function autoK(values: number[]): number { if (values.length < 4) { return 1 } const sorted = [...values].sort((a, b) => a - b) const gaps: number[] = [] for (let i = 1; i < sorted.length; i++) { gaps.push(sorted[i] - sorted[i - 1]) } const medianGap = gaps.sort((a, b) => a - b)[Math.floor(gaps.length / 2)] || 1 const bigGaps = gaps.filter((g) => g > medianGap * 2.5) return Math.min(6, Math.max(1, bigGaps.length + 1)) } export function buildGroups(k: number, lang: 'en' | 'th'): DiameterGroup[] { return Array.from({ length: k }, (_, i) => ({ id: i, label: lang === 'th' ? `กลุ่ม ${i + 1}` : `Group ${i + 1}`, color: GROUP_COLORS[i % GROUP_COLORS.length], })) } export function assignDiameterGroups( detections: Detection[], groupCount: number | 'auto', lang: 'en' | 'th', ): { detections: Detection[]; groups: DiameterGroup[] } { if (detections.length === 0) { return { detections: [], groups: buildGroups(1, lang) } } const diameters = detections.map(diameterOf) const k = groupCount === 'auto' ? autoK(diameters) : Math.max(1, Math.min(6, groupCount)) const centroids = kMeans1D(diameters, k) const groups = buildGroups(k, lang).map((g, i) => ({ ...g, label: lang === 'th' ? `เส้นผ่านศูนย์กลาง ~${Math.round(centroids[i] || 0)}px` : `~${Math.round(centroids[i] || 0)}px`, })) const assigned = detections.map((d) => { const dia = diameterOf(d) let best = 0 let bestDist = Infinity for (let i = 0; i < centroids.length; i++) { const dist = Math.abs(dia - centroids[i]) if (dist < bestDist) { bestDist = dist best = i } } return { ...d, groupId: best } }) return { detections: assigned, groups } } export function countByGroup(detections: Detection[], groups: DiameterGroup[]): Record { const counts: Record = {} for (const g of groups) { counts[g.id] = 0 } for (const d of detections) { counts[d.groupId] = (counts[d.groupId] ?? 0) + 1 } return counts }