-
Notifications
You must be signed in to change notification settings - Fork 12
/
xHistogram.ts
116 lines (107 loc) · 2.62 KB
/
xHistogram.ts
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import { DataXY, NumberArray } from 'cheminfo-types';
import { createFromToArray } from '../utils';
import { xAbsolute } from './xAbsolute';
import { xCheck } from './xCheck';
import { xMaxValue } from './xMaxValue';
import { xMinValue } from './xMinValue';
export interface XHistogramOptions {
/**
* Center the X value. We will enlarge the first and
* @default true
* */
centerX?: boolean;
/**
* Previously existing histogram to continue to fill
* @default {x:[],y:[]}
* */
histogram?: DataXY;
/**
* Number of slots
* @default 256
* */
nbSlots?: number;
/**
* We can first apply a log on x axis
* */
logBaseX?: number;
/**
* We can apply a log on the resulting histogram
*/
logBaseY?: number;
/**
* Take the absolute value
*/
absolute?: boolean;
/**
* Maximal value to calculate used to calculate slot size
* @default maxValue
* */
max?: number;
/**
* Minimum value to calculate used to calculate slot size
* @default minValue
* */
min?: number;
}
/**
* Calculates a histogram of defined number of slots
*
* @param array - Array containing values
* @param options - options
* @returns - result of the histogram
*/
export function xHistogram(
array: NumberArray,
options: XHistogramOptions = {},
): DataXY {
xCheck(array);
const histogram = options.histogram;
const {
centerX = true,
nbSlots = typeof histogram === 'undefined' ? 256 : histogram.x.length,
logBaseX,
logBaseY,
absolute = false,
} = options;
if (absolute) {
array = xAbsolute(array);
}
if (logBaseX) {
array = array.slice();
const logOfBase = Math.log10(logBaseX);
for (let i = 0; i < array.length; i++) {
array[i] = Math.log10(array[i]) / logOfBase;
}
}
const { min = xMinValue(array), max = xMaxValue(array) } = options;
const slotSize = (max - min) / (nbSlots + Number.EPSILON);
const y =
typeof histogram === 'undefined' ? new Float64Array(nbSlots) : histogram.y;
const x =
typeof histogram === 'undefined'
? Array.from(
createFromToArray({
from: min + (centerX ? slotSize / 2 : 0),
to: max - (centerX ? slotSize / 2 : 0),
length: nbSlots,
}),
)
: histogram.x;
for (const element of array) {
const index = Math.max(
Math.min(
Math.floor((element - min - Number.EPSILON) / slotSize),
nbSlots - 1,
),
0,
);
y[index]++;
}
if (logBaseY) {
const logOfBase = Math.log10(logBaseY);
for (let i = 0; i < y.length; i++) {
y[i] = Math.log10(y[i] + 1) / logOfBase;
}
}
return { x, y };
}