-
Notifications
You must be signed in to change notification settings - Fork 12
/
xNormed.ts
83 lines (76 loc) · 2.25 KB
/
xNormed.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
import { NumberArray } from 'cheminfo-types';
import { getOutputArray } from './getOutputArray';
import { xCheck } from './xCheck';
import { xMaxValue } from './xMaxValue';
import { xSum } from './xSum';
export interface XNormedOptions<ArrayType extends NumberArray = Float64Array> {
/** algorithm can be 'sum' 'max' or 'absolute'
* @default 'absolute'
*/
algorithm?: 'absolute' | 'max' | 'sum';
/** max or sum value
* @default 1
*/
value?: number;
/** output into which the result should be placed if needed */
output?: ArrayType;
}
/**
* Divides the data with either the sum, the absolute sum or the maximum of the data
* @param input - Array containing values
* @param options - options
* @returns - normalized data
*/
export function xNormed<ArrayType extends NumberArray = Float64Array>(
input: NumberArray,
options: XNormedOptions<ArrayType> = {},
): ArrayType {
const { algorithm = 'absolute', value = 1 } = options;
xCheck(input);
const output = getOutputArray(options.output, input.length);
if (input.length === 0) {
throw new Error('input must not be empty');
}
switch (algorithm) {
case 'absolute': {
const absoluteSumValue = absoluteSum(input) / value;
if (absoluteSumValue === 0) {
throw new Error('trying to divide by 0');
}
for (let i = 0; i < input.length; i++) {
output[i] = input[i] / absoluteSumValue;
}
return output;
}
case 'max': {
const currentMaxValue = xMaxValue(input);
if (currentMaxValue === 0) {
throw new Error('trying to divide by 0');
}
const factor = value / currentMaxValue;
for (let i = 0; i < input.length; i++) {
output[i] = input[i] * factor;
}
return output;
}
case 'sum': {
const sumFactor = xSum(input) / value;
if (sumFactor === 0) {
throw new Error('trying to divide by 0');
}
for (let i = 0; i < input.length; i++) {
output[i] = input[i] / sumFactor;
}
return output;
}
default:
throw new Error(`unknown algorithm: ${String(algorithm)}`);
}
}
function absoluteSum(input: NumberArray) {
let sumValue = 0;
for (let i = 0; i < input.length; i++) {
sumValue += Math.abs(input[i]);
}
return sumValue;
}