-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathhypothesis.js
104 lines (88 loc) · 2.6 KB
/
hypothesis.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
'use strict';
const OneDataSet = require('./hypothesis/one-data-set.js');
const TwoDataSet = require('./hypothesis/two-data-set.js');
const Welch = require('./hypothesis/welch.js');
const Summary = require('summary');
const ALTERNATIVE_MAP = Object.assign(Object.create(null), {
'not equal': 0,
'less': -1,
'greater': 1
});
function isSummary(data) {
return data && (typeof data.mean === 'function' &&
typeof data.variance === 'function' &&
typeof data.size === 'function');
}
function isCalculated(data) {
return data && (typeof data.mean === 'number' &&
typeof data.variance === 'number' &&
typeof data.size === 'number');
}
function isCompatible(structure) {
return Array.isArray(structure) ||
isSummary(structure) ||
isCalculated(structure);
}
function toData(data) {
if (Array.isArray(data) || isSummary(data)) {
const summary = isSummary(data) ? data : new Summary(data);
return {
mean: summary.mean(),
variance: summary.variance(),
size: summary.size()
};
} else {
return data;
}
}
function hypothesis(left, right, options) {
// Vertify required arguments
if (!isCompatible(left)) {
throw new TypeError(
'left value in hypothesis test must be an array or data summary'
);
}
if (!isCompatible(right)) {
options = right;
right = undefined;
}
// Set the default options
options = Object.assign({
mu: 0,
varEqual: false,
alpha: 0.05,
alternative: 'not equal'
}, options);
// Convert alternative value
options.alternative = ALTERNATIVE_MAP[options.alternative];
// Vertify mu option
if (typeof options.mu !== 'number') {
throw new TypeError('mu option must be a number');
}
// Vertify varEqual option
if (typeof options.varEqual !== 'boolean') {
throw new TypeError('varEqual option must be a boolean');
}
// Vertify alpha option
if (typeof options.alpha !== 'number') {
throw new TypeError('alpha option must be a number');
}
if (options.alpha >= 1) {
throw new RangeError('alpha must be below 1.0');
}
// Vertify alternative option
if (typeof options.alternative === 'undefined') {
throw new Error('alternative must be either "not equal", "less" or "greater"');
}
// Perform the student's t test
if (isCompatible(right)) {
if (options.varEqual) {
return new TwoDataSet(toData(left), toData(right), options);
} else {
return new Welch(toData(left), toData(right), options);
}
} else {
return new OneDataSet(toData(left), options);
}
}
module.exports = hypothesis;