-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumarray.ts
More file actions
574 lines (518 loc) · 23.5 KB
/
numarray.ts
File metadata and controls
574 lines (518 loc) · 23.5 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
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
interface Linear {
dot(arr: NumArray): number;
}
interface Mathematical {
add(value: number | NumArray): NumArray;
ceil(): NumArray;
cos(radians: boolean): NumArray;
cumprod(): NumArray;
cumsum(): NumArray;
divide(arr: NumArray): NumArray;
exp(): NumArray;
exp10(): NumArray;
floor(): NumArray;
log(): NumArray;
log10(): NumArray;
max(): number;
maximum(arr: NumArray): NumArray;
min(): number;
minimum(arr: NumArray): NumArray;
multiply(value: number | NumArray): NumArray;
round(decimals: number): NumArray;
sin(radians: boolean): NumArray;
subtract(arr: NumArray): NumArray;
sum(): number;
tan(radians: boolean): NumArray;
}
interface Random {
choice(): number;
sample(size: number, replace: boolean): NumArray;
shuffle(): NumArray;
}
interface Statistical {
average(weights: number[]): number;
iqr(): number;
mean(): number;
median(): number;
percentile(p: number): number;
quantile(q: number): number[];
std(population: boolean): number;
variance(population: boolean): number;
}
export class NumArray implements Linear, Mathematical, Random, Statistical {
private readonly data: number[];
/**
* Creates a new numeric array instance from the given data. A NumArray is basically
* a regular array with some additional methods which regularly come up and which are
* conveniently collected in this class. Inspired by Python's NumPy.
*
* @param numbers The data to initialize the array with. Can be a collection of numbers
* or an iterable object (array, set, ...). Can also be left empty, in which
* case an empty NumArray is created.
*/
constructor(...numbers: number[] | [Iterable<number>]) {
// Input: separate elements or array / set / ...?
let values: number[] = [];
if (numbers.length === 1 && Symbol.iterator in Object(numbers) && typeof numbers[0] === "object") {
// An iterable object has been passed (array, set, ...): [[..., ..., ...]]
// Note that the typeof check is added to prevent single number entries from ending
// up in this branch.
// @ts-ignore: TypeScript complains about "no overload matches this call"
values = Array.from(numbers[0]);
} else {
// Separate numbers / elements have been passed [..., ..., ...]
// @ts-ignore: TypeScript complains about "no overload matches this call"
values = Array.from(numbers);
}
// Make sure that only numbers are passed in and that there are no NaNs.
if (!values.every((value) => typeof value === "number" && !Number.isNaN(value))) {
throw new Error("Input contains non-numeric values: only numbers are allowed.");
}
this.data = values;
}
/**
* STATIC METHOD. Constructs a new numeric array where the elements are separated
* by the specified step value (linear spacing). The start value is always included
* in the generated range of values, the stop value can be included or excluded
* depending on the step value.
*
* @param start The start value of the generated range of values in the array (inclusive).
* @param stop The stop value of the generated range of values in the array (inclusive / exclusive).
* @param step The step value of the generated range of values in the array.
* @returns A new NumArray with values separated by the specified step value.
*/
static arange(start: number, stop: number, step: number = 1): NumArray {
if (step === 0) throw new Error("The step value can not be 0.");
if (start === stop) return new NumArray();
if (start < stop && step < 0) return new NumArray();
if (start > stop && step > 0) return new NumArray();
return new NumArray(Array.from({ length: 1 + (stop - start) / step }, (_, index) => start + index * step));
}
/**
* STATIC METHOD. Constructs a new numeric array with all elements set to the
* specified value.
*
* @param length The number of elements in the resulting NumArray (>=0, integer value).
* @param fillValue The value to fill the NumArray with.
* @returns A new NumArray with all elements set to 'fillValue'.
*/
static fill(length: number, fillValue: number): NumArray {
if (length < 0 || length % 1 !== 0) throw new Error("Length must be a positive integer.");
return new NumArray(Array.from({ length: length }, () => fillValue));
}
/**
* STATIC METHOD. Constructs a new numeric array from the specified string. The string
* will be parsed to generate a list of numbers, given the specified separator (default ;).
* If the string contains any non-numeric values, an error will be thrown. NaN values are also
* considered to be non-numeric values. An empty string will result in an empty NumArray.
*
* @param numbers The string with numeric values, separated by the specified separator.
* @param separator The separator used to separate / identify the values in the string (default ;).
* @returns A new NumArray.
*/
static fromString(numbers: string, separator: string = ";"): NumArray {
if (numbers.trim() === "") return new NumArray();
const values: number[] = numbers.split(separator).map((value) => Number(value));
return new NumArray(values);
}
/**
* STATIC METHOD. Constructs a new numeric array with the specified number of
* elements, linearly spaced between the start and stop values. If the specified
* number of elements is 1 and / or the start and stop values are equal, then
* the start value will be returned. The generated range of values is including
* the start and stop values.
*
* @param start The start value of the generated range of values in the array.
* @param stop The stop value of the generated range of values in the array.
* @param length The number of elements in the resulting NumArray.
* @returns A new NumArray with linearly spaced values between start (inclusive) and stop (inclusive).
*/
static linspace(start: number, stop: number, length: number): NumArray {
if (length < 0 || length % 1 !== 0) throw new Error("Length must be a positive integer.");
if (length === 1 || start === stop) return new NumArray(start);
return new NumArray(
Array.from({ length: length }, (_, index) => start + ((stop - start) * index) / (length - 1))
);
}
/**
* STATIC METHOD. Constructs a new numeric array with all elements set to 1.
*
* @param length The number of elements in the resulting NumArray (>=0, integer value).
* @returns A new NumArray with all elements set to 1.
*/
static ones(length: number): NumArray {
return this.fill(length, 1);
}
/**
* STATIC METHOD. Constructs a new numeric array with all elements set to a random
* value (float). The random values are sampled from a uniform distribution between
* 0 and 1.
*
* @param length The number of elements in the resulting NumArray (>=0, integer value).
* @returns A new NumArray with all elements set to a random value.
*/
static random(length: number): NumArray {
if (length < 0 || length % 1 !== 0) throw new Error("Length must be a positive integer.");
return new NumArray(Array.from({ length: length }, () => Math.random()));
}
/**
* STATIC METHOD. Constructs a new numeric array with all elements set to a random
* integer value between a minimum value (inclusive) and a maximum value (inclusive).
* The random values are sampled from a uniform distribution.
*
* @param min The minimum value for the random integers (integer value).
* @param max The maximum value for the random integers (integer value).
* @param length The number of elements in the resulting NumArray (>=0, integer value).
* @returns A new NumArray with all elements set to a random integer value.
*/
static randomInt(min: number, max: number, length: number): NumArray {
if (length < 0 || length % 1 !== 0) throw new Error("Length must be a positive integer.");
if (min % 1 !== 0 || max % 1 !== 0) throw new Error("Minimum and maximum values must be integers.");
if (min >= max) throw new Error("Minimum value must be smaller than maximum value.");
return new NumArray(Array.from({ length: length }, () => Math.floor(Math.random() * (max - min + 1)) + min));
}
/**
* STATIC METHOD. Constructs a new numeric array with all elements set to a random
* value (float) between a minimum value (inclusive) and a maximum value (exclusive).
* The random values are sampled from a uniform distribution.
*
* @param min The minimum value for the random values..
* @param max The maximum value for the random values.
* @param length The number of elements in the resulting NumArray (>=0, integer value).
* @returns A new NumArray with all elements set to a random value (float).
*/
static randomFloat(min: number, max: number, length: number): NumArray {
if (length < 0 || length % 1 !== 0) throw new Error("Length must be a positive integer.");
if (min >= max) throw new Error("Minimum value must be smaller than maximum value.");
return new NumArray(Array.from({ length: length }, () => Math.random() * (max - min) + min));
}
/**
* STATIC METHOD. Constructs a new numeric array with all elements set to 0.
*
* @param length The number of elements in the resulting NumArray (>=0, integer value).
* @returns A new NumArray with all elements set to 0.
*/
static zeros(length: number): NumArray {
return this.fill(length, 0);
}
// ========================================================================
// Linear algebra
// ========================================================================
/**
* Computes the dot product of the current NumArray and the given NumArray.
*
* @param arr The NumArray to compute the dot product with.
* @returns The dot product of this NumArray and the given NumArray.
*/
dot(arr: NumArray): number {
if (this.data.length != arr.length) {
throw new Error("Array lengths must be equal to calculate the dot product.");
}
return this.data.reduce((acc, current, index) => acc + current * arr.element(index), 0);
}
// ========================================================================
// Mathematical functions
// ========================================================================
/**
* Adds the given number or NumArray to this NumArray (element-wise addition).
*
* @param value The array to add to this array (element-wise).
* @returns A new array that is the sum of this array and the given array.
*/
add(value: number | NumArray): NumArray {
// Scalar addition: value is a number
if (typeof value === "number") {
return new NumArray(this.data.map((el) => el + value));
}
// Array addition: value is an array
if (this.data.length != value.length) {
throw new Error("Array lengths must be equal for addition.");
}
return new NumArray(this.data.map((el, index) => el + value.element(index)));
}
/**
* Rounds all elements in the array to the nearest, larger integer.
*
* @returns A new array with all elements rounded up.
*/
ceil(): NumArray {
return new NumArray(this.data.map((el) => Math.ceil(el)));
}
/**
* Computes the cosine of all elements in the array (element-wise) and returns a new array.
*
* @param radians If true, then the array is assumed to contain elements in radians and
* the cosine is computed in radians. Otherwise, the array is assumed to
* contain elements in degrees and the cosine is computed in degrees.
* @returns A new array where all elements are the cosine of their original value.
*/
cos(radians: boolean): NumArray {
if (radians) return new NumArray(this.data.map((el) => Math.cos(el)));
return new NumArray(this.data.map((el) => Math.cos((Math.PI / 180) * el)));
}
cumprod(): NumArray {
// Transform vector into a cumulative product vector
let prod = 1;
return new NumArray(this.data.map((num) => (prod *= num)));
}
cumsum(): NumArray {
// Transform vector into a cumulative sum vector
let sum = 0;
return new NumArray(this.data.map((num) => (sum += num)));
}
divide(value: number | NumArray): NumArray {
// Scalar division: value is a number
if (typeof value === "number") {
return new NumArray(this.data.map((el) => el / value));
}
// Array division: value is an array
if (this.data.length != value.length) {
throw new Error("Array lengths must be equal for division.");
}
if (value.elements.some((el) => el === 0)) {
throw new Error("Cannot divide by zero.");
}
return new NumArray(this.data.map((el, index) => el / value.element(index)));
}
exp(): NumArray {
// Transform entries to the exponential of their value
return new NumArray(this.data.map((el) => Math.exp(el)));
}
exp10(): NumArray {
// Transform entries to the base-10 exponential of their value
return new NumArray(this.data.map((el) => Math.pow(10, el)));
}
/**
* Rounds all elements in the array to the nearest, smaller integer.
*
* @returns A new array with all elements rounded down.
*/
floor(): NumArray {
return new NumArray(this.data.map((el) => Math.floor(el)));
}
log(): NumArray {
// Transform entries to the natural logarithm of their value
return new NumArray(this.data.map((el) => Math.log(el)));
}
log10(): NumArray {
// Transform entries to the base-10 logarithm of their value
return new NumArray(this.data.map((el) => Math.log10(el)));
}
max(): number {
// Maximum value
return this.data.reduce((acc, current) => (current > acc ? current : acc));
}
maximum(arr: NumArray): NumArray {
// Maximum value
if (this.data.length != arr.length) {
throw new Error("Array lengths must be equal for calculating the maximum.");
}
return new NumArray(this.data.map((el, index) => (el > arr.element(index) ? el : arr.element(index))));
}
min(): number {
// Minimum value
return this.data.reduce((acc, current) => (current < acc ? current : acc));
}
minimum(arr: NumArray): NumArray {
// Minimum value
if (this.data.length != arr.length) {
throw new Error("Array lengths must be equal for calculating the minimum.");
}
return new NumArray(this.data.map((el, index) => (el < arr.element(index) ? el : arr.element(index))));
}
multiply(value: number | NumArray): NumArray {
// Scalar multiplication: value is a number
if (typeof value === "number") {
return new NumArray(this.data.map((el) => el * value));
}
// Array multiplication: value is an array
if (this.data.length != value.length) {
throw new Error("Array lengths must be equal for multiplication.");
}
return new NumArray(this.data.map((el, index) => el * value.element(index)));
}
round(decimals: number): NumArray {
// Round entries to the specified number of decimals
return new NumArray(this.data.map((el) => Number(el.toFixed(decimals))));
}
/**
* Computes the sine of all elements in the array (element-wise) and returns a new array.
*
* @param radians If true, then the array is assumed to contain elements in radians and
* the sine is computed in radians. Otherwise, the array is assumed to
* contain elements in degrees and the sine is computed in degrees.
* @returns A new array where all elements are the sine of their original value.
*/
sin(radians: boolean = true): NumArray {
if (radians) return new NumArray(this.data.map((el) => Math.sin(el)));
return new NumArray(this.data.map((el) => Math.sin((Math.PI / 180) * el)));
}
subtract(value: number | NumArray): NumArray {
// Scalar subtraction: value is a number
if (typeof value === "number") {
return new NumArray(this.data.map((el) => el - value));
}
// Array subtraction: value is an array
if (this.data.length != value.length) {
throw new Error("Array lengths must be equal for subtraction.");
}
return new NumArray(this.data.map((el, index) => el - value.element(index)));
}
sum(): number {
// Sum of entries
return this.data.reduce((acc, current) => acc + current, 0);
}
/**
* Computes the tangent of all elements in the array (element-wise) and returns a new array.
*
* @param radians If true, then the array is assumed to contain elements in radians and
* the tangent is computed in radians. Otherwise, the array is assumed to
* contain elements in degrees and the tangent is computed in degrees.
* @returns A new array where all elements are the tangent of their original value.
*/
tan(radians: boolean = true): NumArray {
if (radians) return new NumArray(this.data.map((el) => Math.tan(el)));
return new NumArray(this.data.map((el) => Math.tan((Math.PI / 180) * el)));
}
// ========================================================================
// Random functions
// ========================================================================
/**
* Picks a random value from the array and returns it.
*
* @returns A random value from the array.
*/
choice(): number {
if (this.data.length === 0) throw new Error("Array is empty: no value can be chosen.");
const index = Math.floor(Math.random() * this.data.length);
return this.data[index];
}
/**
* Returns a sample of values from the array. Sampling can be done with
* replacement or without replacement.
*
* @param size The number of values to sample.
* @param replace Sample with / without replacement. Default: with replacement.
* @returns A new array containing the sampled values.
*/
sample(size: number, replace: boolean = true): NumArray {
if (size < 0 || size % 1 !== 0) throw new Error("Size must be a positive integer.");
const result: number[] = [];
if (replace) {
// Sample with replacement
for (let i = 1; i <= size; i++) {
result.push(this.choice());
}
} else {
// Sample without replacement
if (size > this.data.length) {
throw new Error("Sample size can not exceed array length.");
}
const sampleData: number[] = [...this.data];
let numSamples = 0;
for (let i = 1; i <= size; i++) {
// const index = Math.floor(Math.random() * (sampleData.length - numSamples));
const index = Math.floor(Math.random() * sampleData.length);
result.push(sampleData[index]);
sampleData.splice(index, 1);
numSamples += 1;
}
}
return new NumArray(result);
}
/**
* Shuffles the values in the array and returns a new, shuffled array.
*
* @returns A new, shuffled array.
*/
shuffle(): NumArray {
const shuffleData: number[] = [...this.data];
if (shuffleData.length === 1) return new NumArray(shuffleData);
for (let i = 0; i < this.data.length; i++) {
const swapIndex = NumArray.randomInt(0, this.data.length - 1, 1).element(0);
[shuffleData[i], shuffleData[swapIndex]] = [shuffleData[swapIndex], shuffleData[i]];
}
return new NumArray(shuffleData);
}
// ========================================================================
// Statistical functions
// ========================================================================
average(weights: number[]): number {
if (weights.length != this.data.length) {
throw new Error("Number of weights must be equal to the array length to calculate the weighted average.");
}
const sumOfWeights = weights.reduce((acc, current) => acc + current, 0);
const weightedVector = this.data.map((el, index) => (el * weights[index]) / sumOfWeights);
return weightedVector.reduce((acc, current) => acc + current, 0);
}
iqr(): number {
// Interquartile range
return this.percentile(75) - this.percentile(25);
}
mean(): number {
// Arithmetic mean
return this.sum() / this.data.length;
}
median(): number {
// Median value
return this.percentile(50);
}
percentile(p: number): number {
// Percentile (linear method)
if (p < 0 || p > 100) {
throw new Error("Percentile should be between 0 and 100 (inclusive).");
}
// Sort data and determine index of percentile value
const sorted = [...this.data].sort((a, b) => a - b);
const index = (sorted.length - 1) * (p / 100);
const indexFloor = Math.floor(index);
const indexCeil = Math.ceil(index);
// Percentile: unique index => value, two indices => calculated value
if (indexFloor === indexCeil) return sorted[indexFloor];
return sorted[indexFloor] * (indexCeil - index) + sorted[indexCeil] * (index - indexFloor);
}
quantile(q: number): number[] {
// Examples:
// 2-quantile = median.
// 3-quantiles = tertiles
// 4-quantiles = quartiles
// ...
const result: number[] = [];
for (let i = 0; i < q - 1; i++) {
result.push(this.percentile((100 / q) * (i + 1)));
}
return result;
}
std(population: boolean = true): number {
// Standard deviation
return Math.sqrt(this.variance(population));
}
variance(population: boolean = true): number {
// Variance, population / sample.
return (
this.data.map((el) => Math.pow(Math.abs(el - this.mean()), 2)).reduce((acc, current) => acc + current, 0) /
(population ? this.data.length : this.data.length - 1)
);
}
// ========================================================================
// Miscellaneous functions
// ========================================================================
get elements(): number[] {
// Return copy of the data as an array
return [...this.data];
}
element(index: number): number {
if (index < 0 || index >= this.data.length || index % 1 !== 0) {
throw new Error("Index out of bounds.");
}
return this.data[index];
}
get length(): number {
// Return the number of elements
return this.data.length;
}
push(value: number): void {
// Add an element to the end of the array
this.data.push(value);
}
}