Line data Source code
1 : /**
2 : * Convert a histogram (arbitrary number of bins) into an SVG path string.
3 : * Applies square-root scaling and normalizes using the 99.5th percentile
4 : * to avoid outlier spikes.
5 : */
6 2 : export function histogramToPath(histogram: Uint32Array): string {
7 2 : const len = histogram.length
8 2 : if (len === 0) return ''
9 :
10 2 : const sqrtValues = new Float32Array(len)
11 512 : for (let i = 0; i < len; i++) sqrtValues[i] = Math.sqrt(histogram[i])
12 :
13 : const sorted = Array.from(sqrtValues).sort((a, b) => a - b)
14 2 : const max = sorted[Math.floor((len - 1) * 0.995)]
15 2 : if (max === 0) return ''
16 :
17 0 : const invMax = 1 / max
18 0 : const lastIdx = len - 1
19 0 : const parts: string[] = ['M0,1']
20 0 : for (let i = 0; i < len; i++) {
21 0 : const x = lastIdx === 0 ? 0.5 : i / lastIdx
22 0 : const y = 1 - Math.min(1, sqrtValues[i] * invMax)
23 0 : parts.push(`L${x},${y}`)
24 : }
25 0 : parts.push('L1,1 Z')
26 0 : return parts.join(' ')
27 : }
|