-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathcomputeHistograms.js
More file actions
88 lines (83 loc) · 2.42 KB
/
Copy pathcomputeHistograms.js
File metadata and controls
88 lines (83 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import UpdateHistogramWorker from './UpdateHistogram.worker'
const haveSharedArrayBuffer = typeof window.SharedArrayBuffer === 'function'
import webWorkerPromiseWorkerPool from './webWorkerPromiseWorkerPool'
const numberOfWorkers = navigator.hardwareConcurrency
? Math.min(navigator.hardwareConcurrency, 6)
: 4
const updateHistogramWorkerPool = webWorkerPromiseWorkerPool(
numberOfWorkers,
UpdateHistogramWorker,
'updateHistogram'
)
updateHistogramWorkerPool.terminateWorkers()
export const computeHistogram = async (
values,
component,
numberOfComponents,
[min, max]
) => {
const numberOfSplits = numberOfWorkers
let numberOfBins = 256
if (
typeof values !== typeof Float32Array ||
typeof values !== typeof Float64Array
) {
const intBins = max - min + 1
if (intBins < numberOfBins) {
numberOfBins = intBins
}
}
const taskArgs = new Array(numberOfSplits)
if (haveSharedArrayBuffer && values.buffer instanceof SharedArrayBuffer) {
for (let split = 0; split < numberOfSplits; split++) {
taskArgs[split] = [
{
values,
min,
max,
numberOfBins,
component,
numberOfComponents,
},
]
}
} else {
let arrayStride = Math.floor(values.length / numberOfSplits) || 1
arrayStride += arrayStride % numberOfComponents
let arrayIndex = 0
for (let split = 0; split < numberOfSplits; split++) {
const arrayStart = arrayIndex
const arrayEnd = Math.min(arrayIndex + arrayStride, values.length - 1)
const subArray = values.slice(arrayStart, arrayEnd + 1)
taskArgs[split] = [
{
values: subArray,
min,
max,
numberOfBins,
component,
numberOfComponents,
},
[subArray.buffer],
]
arrayIndex += arrayStride
}
}
const histograms = await updateHistogramWorkerPool.runTasks(taskArgs).promise
const histogram = new Float32Array(numberOfBins)
histogram.fill(0.0)
for (let ii = 0; ii < histograms.length; ii++) {
for (let jj = 0; jj < numberOfBins; jj++) {
histogram[jj] += histograms[ii].result[jj]
}
}
let maxHistogram = 0.0
for (let ii = 0; ii < numberOfBins; ii++) {
maxHistogram = Math.max(histogram[ii], maxHistogram)
}
for (let ii = 0; ii < numberOfBins; ii++) {
histogram[ii] /= maxHistogram
}
updateHistogramWorkerPool.terminateWorkers()
return histogram
}