-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
654 lines (614 loc) · 19 KB
/
index.js
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
/**
* @module linear-regression-model
* Represents the linear model class
* of a dataset behaviour overtime
* @author Nikolas B Virionis <[email protected]>
*/
class LinearModelOverTime {
/**
* @attributes
* - _data
* - _xValues <br>
* Both protected in order to only be accessed internally, <br>
* and in its subclass
*/
_data;
_xValues;
/**
* @constructor
* @param {number[]} data
* The dataset to be modeled,
* on it's behavior over time.
*
*/
constructor(data) {
if (!data) {
throw "It is necessary to provide the dataset";
}
if (data.length < 2) {
throw "In order to design a linear model, you must provide at least 2 data points";
}
if (!Array.isArray(data)) {
throw "Constructor parameter is not an array";
}
try {
data = data.map(el => Number(el));
} catch (e) {
throw `Some value in the dataset is invalid, or impossible to convert to number, \nError: ${e}`;
}
this._data = data;
this._xValues = LinearModelOverTime._getXAxisValues(data);
}
/**
*
* @param {number} rad angle measured in radians
* @returns {number}
* returns the angle measured in degrees
* to better visualize the behaviour of the model
*/
static radsToDegs = rad => (rad * 180) / Math.PI;
/**
*
* @method
* @returns {number} length of the dataset
*/
getDatasetLength() {
return this._data.length;
}
/**
* @method
* Protected method for internal use, right on class creation
* @param {number[]} dataset
* returns the length of the dataset
* @returns {number}
*/
static _getDatasetLength(dataset) {
return dataset.length;
}
/**
* Utility function to calculate the mean of a dataset
* @param {number[]} dataset
* @returns {number} the mean of the dataset
*/
static getMean(dataset) {
return (
dataset.reduce((sum, element) => sum + element, 0) / dataset.length
);
}
/**
* Utility function to calculate the mode of a dataset
* @param {number[]} dataset
* @returns {number[]} the mode of the dataset
* Let it be noted that it can be more than one,
* in that case, the array of modes will have more than one value
*/
static getMode(dataset) {
const datasetElements = {};
for (let element of dataset) {
if (!datasetElements[element]) {
datasetElements[element] = 1;
continue;
}
datasetElements[element]++;
}
let mode = [{key: -1, qtd: -1}];
for (let key in datasetElements) {
if (datasetElements[key] > mode[0].qtd) {
mode = [{key, qtd: datasetElements[key]}];
}
if (
datasetElements[key] == mode[0].qtd &&
!mode.map(el => el.key).includes(key)
) {
mode.push({key, qtd: datasetElements[key]});
}
}
return mode.map(({key}) => Number(key));
}
/**
* Utility function to calculate the median of a dataset
* @param {number[]} dataset
* @returns {number} the median of the dataset
*/
static getMedian(dataset) {
dataset = dataset.sort((a, b) => a - b);
if (dataset.length % 2 === 0) {
return LinearModelOverTime.getMean([
dataset[dataset.length / 2 - 1],
dataset[dataset.length / 2]
]);
} else {
return dataset[Math.ceil(dataset.length / 2)];
}
}
/**
* @method
* returns the dataset on the Y axis
* @returns {number[]}
*/
getDataset() {
return this._data;
}
/**
* @method
* In order to better describe the dataset's
* behaviour over time, we need to provide the
* x axis values to complete the data frame.
*/
getXAxisValues() {
let x = [...Array(this.getDatasetLength()).keys()];
x.push(x[x.length - 1] + 1);
x.shift();
return [...x];
}
/**
* returns the X axis dataset, when not informed previously
* @param {number[]} dataset
* @returns {number[]}
*/
static _getXAxisValues(dataset) {
let x = [
...Array(LinearModelOverTime._getDatasetLength(dataset)).keys()
];
x.push(x[x.length - 1] + 1);
x.shift();
return [...x];
}
/**
* @method
* @returns {number} sum of all dataset values
*/
getSumOfDatasetValues() {
let sumDataset = 0;
for (const iterator of this._data) {
sumDataset += iterator;
}
return sumDataset;
}
/**
* @method
* @returns {number} sum of all x axis values
*/
getSumOfXValues() {
let sumX = 0;
for (const iterator of this._xValues) {
sumX += iterator;
}
return sumX;
}
/**
* @method
* @returns {number} returns the slope of the "chart"
* which consists of the tangent of the angle
* which has the formula:
* - let the sum of equivalent elements times the dataset length as a
* - let the multiplication of the sum of all the values in both the datasets as b
* - let the sum of all squared x values times the dataset length as c
* - let the squared sum of all x values as d
* @returns slope = (a - b) / (c - d)
*/
getSlope() {
// slope => tan(x)
let slope =
(this.#getSumOfEquivalentElementsTimesLength() -
this.#getMultiplicationOfAxisValuesSum()) /
(this.#getXValuesSquaredSummedTimesLength() -
this.#getSumOfXValuesSquaredTimesLength());
return slope;
}
/**
* @method
* @returns {number} returns the sum of equivalent
* elements times the dataset length
*/
#getSumOfEquivalentElementsTimesLength() {
let sum = 0;
for (let i in this._xValues) {
sum += this._xValues[i] * this._data[i];
}
return this.getDatasetLength() * sum;
}
/**
* @method
* @returns {number} returns the multiplication of the sum of
* all the values in both the datasets
*/
#getMultiplicationOfAxisValuesSum() {
return this.getSumOfDatasetValues() * this.getSumOfXValues();
}
/**
* @method
* @returns {number} returns the sum of all squared x values
* times the dataset length
*/
#getXValuesSquaredSummedTimesLength() {
let xValuesSquared = this._xValues.map(el => el ** 2);
let sumOfXValuesSquared = [...xValuesSquared].reduce(
(ac, el) => (ac += el)
);
return this.getDatasetLength() * sumOfXValuesSquared;
}
/**
* @method
* @returns {number} returns the squared sum of all x values
*/
#getSumOfXValuesSquaredTimesLength() {
return this.getSumOfXValues() ** 2;
}
/**
* @method
* @returns {number} returns the angle in radians
* which consists of the arc tangent of the slope
* which corresponds of the tangent of the angle
* this way arctan(x)/tan(x) = x rad
*/
getAngleInRadians() {
return Math.atan(this.getSlope());
}
/**
* @method
* @returns {number} returns the angle in degrees
* which consists of the conversion of the angle in
* radians to degrees
*/
getAngleInDegrees() {
return LinearModelOverTime.radsToDegs(this.getAngleInRadians());
}
/**
* @method
* @returns {string} returns the overall behaviour
* of the dataset, being the options:
* - constant for a dataset that is nearly not changing significantly
* - increase for a dataset with an increasing pattern
* - reduction for a dataset with an decreasing pattern
*/
getDatasetBehavior() {
let deg = this.getAngleInDegrees();
if (deg >= -1 && deg <= 1) {
return "constant";
}
if (deg > 1) {
return "increase";
}
return "reduction";
}
/**
* @method
* @returns {string} returns the overall behavioural instensity
* of the dataset, being the options:
* - steady for a dataset that is nearly not changing significantly(constant)
* - mild for a dataset with up to 10° of inclination
* - moderate for a dataset with up to 25° of inclination
* - significant for a dataset with up to 40° of inclination
* - drastic for a dataset with more than 40° of inclination
*/
getDatasetBehavioralIntensity() {
let deg = Math.abs(this.getAngleInDegrees());
if (deg <= 1) {
return "steady";
}
if (deg < 10) {
return "mild";
}
if (deg < 25) {
return "moderate";
}
if (deg < 40) {
return "significant";
}
return "drastic";
}
/**
* @method
* @returns {number} returns the multiplication of the
* slope and the sum of all x axis values
*/
#getSlopeTimesSumOfXValues() {
return this.getSlope() * this.getSumOfXValues();
}
/**
* @method
* @returns {number} returns the linear coefficient
* which is represented as the division between
* the subtraction between the sum of the dataset values
* and the slope times the sum of x axis values
* and the length of the dataset, being the formula:
* - let the sum of the dataset values as a
* - let the slope times the sum of the x axis values as b
* - let the length of the dataset as n
* @returns linearCoefficient = (a - b) / n
*/
getLinearCoefficient() {
return (
(this.getSumOfDatasetValues() - this.#getSlopeTimesSumOfXValues()) /
this.getDatasetLength()
);
}
/**
* @method
* @returns {object} returns the angular coefficient(slope) and
* linear coefficient(y-intercept)
*/
getCoefficients() {
return {
angular: this.getSlope(),
linear: this.getLinearCoefficient()
};
}
/**
* @method
* @returns {object} returns equation as a string to be better displayed
* and visualized and the function itself to be used and make predictions
* ofthe dataset most probable behaviour
*
*/
getLinearEquation() {
return {
stringEquation: `f(x) = ${this.getSlope().toFixed(
3
)}x + ${this.getLinearCoefficient().toFixed(3)}`,
function: x => x * this.getSlope() + this.getLinearCoefficient()
};
}
/**
* @method
* shortcut to get the correlation of the datasets
* @returns {number}
* returns the correlation between the two datasets
* in an easier way
*/
getCorrelation() {
let corr = new Correlation(this._xValues, this._data);
return corr.getCorrelation();
}
/**
* @method
* shortcut to get the correlation interpretation
* @returns {number}
* returns the correlation interpretation between
* the two datasets in an easier way
*/
getCorrelationInterpretation() {
let corr = new Correlation(this._xValues, this._data);
return corr.getCorrelationInterpretation();
}
/**
* R² is the coefficient of the determination
* which, basically, verifies the accuracy of the
* linear model just calculated
* @returns {number} the coefficient of determination(R²)
*/
getR2() {
let totalSumOfSquares = [
...Correlation.getDifferenceFromMeanAndElements(this._data).map(
x => x ** 2
)
].reduce((sum, x) => sum + x, 0);
let residualSumOfSquares = this._data.reduce(
(sum, element, index) =>
sum +
(element -
(this.getSlope() * this._xValues[index] +
this.getLinearCoefficient())) **
2,
0
);
return 1 - residualSumOfSquares / totalSumOfSquares;
}
}
/**
* @module linear-regression-model
* Represents the linear model class
* of a dataset behaviour in relation
* to its counterpart
* @author Nikolas B Virionis <[email protected]>
*/
class LinearModel extends LinearModelOverTime {
/**
* @constructor
* @param {number[]} datasetX
* @param {number[]} datasetY
* The datasets to be modeled,
* on they're behavior in relation
* to one another.
*/
constructor(datasetX, datasetY) {
if (!datasetX || !datasetY) {
throw "Two arrays are necessary for LinearModel";
}
if (datasetX.length != datasetY.length) {
throw "The arrays have different lengths, which is not allowed";
}
if (!Array.isArray(datasetX) || !Array.isArray(datasetY)) {
throw "Constructor parameter is not an array";
}
if (datasetX.length < 2) {
throw "In order to design a linear model, you must provide at least 2 data points";
}
try {
datasetY = datasetY.map(el => Number(el));
datasetX = datasetX.map(el => Number(el));
} catch (e) {
throw `Some value in one of the datasets is invalid, or impossible to convert to number, \nError: ${e}`;
}
super(datasetY);
this._xValues = datasetX;
}
/**
*
* @override Overriden from the LinearModelOverTime class
* @returns {number} returns the x axis dataset which,
* on this class instance, was informed
*/
getXAxisValues() {
return this._xValues;
}
}
/**
* @module linear-regression-model
* Represents the correlation class
*
* @author Nikolas B Virionis <[email protected]>
*/
class Correlation {
/**
* @attributes
* - datasetY
* - datasetX <br>
* Both represent the datasets used
* for the correlation
*/
datasetY;
datasetX;
/**
* @constructor
* @param {number[]} datasetX
* @param {number[]} datasetY
* The datasets the correlation is made with
*/
constructor(datasetX, datasetY) {
if (!datasetX || !datasetY) {
throw "Two arrays are necessary for Correlation";
}
if (datasetX.length != datasetY.length) {
throw "The arrays have different lengths, which is not allowed";
}
if (!Array.isArray(datasetX) || !Array.isArray(datasetY)) {
throw "Constructor parameter is not an array";
}
if (datasetX.length < 2) {
throw "In order to design a linear model, you must provide at least 2 data points";
}
try {
datasetY = datasetY.map(el => Number(el));
datasetX = datasetX.map(el => Number(el));
} catch (e) {
throw `Some value in one of the datasets is invalid, or impossible to convert to number, \nError: ${e}`;
}
this.datasetY = datasetY;
this.datasetX = datasetX;
}
/**
* gets the mean of the dataset
* @param {number[]} dataset
* @returns {number} the mean, average, of the dataset
*/
static getMean(dataset) {
return Correlation.#sumDataset(dataset) / dataset.length;
}
/**
* gets the difference between the mean and the elements of the dataset
* @param {number[]} dataset
* @returns {number[]}
*/
static getDifferenceFromMeanAndElements(dataset) {
let data = dataset.map(
element => element - Correlation.getMean(dataset)
);
return data;
}
/**
* creates the secondary lists, used for the correlation
* @returns {number[][]} the secondary lists
*/
#getSecondaryLists() {
let dataY = Correlation.getDifferenceFromMeanAndElements(this.datasetY);
let dataX = Correlation.getDifferenceFromMeanAndElements(this.datasetX);
return this.#fillSecondaryLists(dataX, dataY);
}
/**
* fills the secondary lists, used for the
* correlation, with their respective data
* @param {number[]} dataX
* @param {number[]} dataY
* @returns {number[][]} the secondary lists
*/
#fillSecondaryLists(dataX, dataY) {
let ab = [];
let a2 = [];
let b2 = [];
for (let index in dataX) {
ab.push(dataX[index] * dataY[index]);
a2.push(dataX[index] ** 2);
b2.push(dataY[index] ** 2);
}
return [ab, a2, b2];
}
/**
* sums all the values of a dataset
* @param {number[]} dataset
* @returns {number}
*/
static #sumDataset(dataset) {
return dataset.reduce((sum, element) => sum + element, 0);
}
/**
* sums the secondary dataset values
* @param {number[]} ab
* @param {number[]} a2
* @param {number[]} b2
* @returns {number[]}
*/
#getSumOfCorrDatasets(ab, a2, b2) {
let sumAb = Correlation.#sumDataset(ab);
let sumA2 = Correlation.#sumDataset(a2);
let sumB2 = Correlation.#sumDataset(b2);
return [sumAb, sumA2, sumB2];
}
/**
* ends the formula of the correlation
* and returns its value
* @returns {number} the correlation itself
*/
getCorrelation() {
let [ab, a2, b2] = this.#getSecondaryLists();
let [sumAb, sumA2, sumB2] = this.#getSumOfCorrDatasets(ab, a2, b2);
return sumAb / (sumA2 * sumB2) ** (1 / 2);
}
/**
* @method
* returns the way the two datasets are correlated to each other
* @returns {string} the sign/way the datasets are correlated
*/
getCorrelationWay() {
let corr = this.getCorrelation();
if (this.getCorrelationIntensity() === "nearly independent") {
return "negligible way";
}
if (corr > 0) {
return "positive way";
}
return "negative way";
}
/**
* @method
* returns the intensity by which the two datasets are correlated to each other
* @returns {string} the correlation intensity itself
*/
getCorrelationIntensity() {
let corr = this.getCorrelation();
if (Math.abs(corr) > 0.9) {
return "highly correlated";
}
if (Math.abs(corr) > 0.7) {
return "strongly correlated";
}
if (Math.abs(corr) > 0.5) {
return "moderately correlated";
}
if (Math.abs(corr) > 0.3) {
return "barely correlated";
}
return "nearly independent";
}
/**
* @method
* returns the interpretation of the correlation index,
* so its easier to abstract an insight out of it
* @returns {string} the whole correlation interpretation
*/
getCorrelationInterpretation() {
return `${this.getCorrelationIntensity()} in a ${this.getCorrelationWay()}`;
}
}
module.exports = {LinearModelOverTime, LinearModel, Correlation};