main.js (2607B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive; 24 var incrpcorr = require( './../../../incr/pcorr' ); 25 var abs = require( '@stdlib/math/base/special/abs' ); 26 27 28 // MAIN // 29 30 /** 31 * Returns an accumulator function which incrementally computes a sample absolute Pearson product-moment correlation coefficient. 32 * 33 * @param {number} [meanx] - mean value 34 * @param {number} [meany] - mean value 35 * @throws {TypeError} first argument must be a number primitive 36 * @throws {TypeError} second argument must be a number primitive 37 * @returns {Function} accumulator function 38 * 39 * @example 40 * var accumulator = incrapcorr(); 41 * 42 * var ar = accumulator(); 43 * // returns null 44 * 45 * ar = accumulator( 2.0, 1.0 ); 46 * // returns 0.0 47 * 48 * ar = accumulator( -5.0, 3.14 ); 49 * // returns ~1.0 50 * 51 * ar = accumulator(); 52 * // returns ~1.0 53 * 54 * @example 55 * var accumulator = incrapcorr( 2.0, -3.0 ); 56 */ 57 function incrapcorr( meanx, meany ) { 58 var acc; 59 var N; 60 if ( arguments.length ) { 61 if ( !isNumber( meanx ) ) { 62 throw new TypeError( 'invalid argument. First argument must be a number primitive. Value: `' + meanx + '`.' ); 63 } 64 if ( !isNumber( meany ) ) { 65 throw new TypeError( 'invalid argument. Second argument must be a number primitive. Value: `' + meany + '`.' ); 66 } 67 acc = incrpcorr( meanx, meany ); 68 } else { 69 acc = incrpcorr(); 70 } 71 N = 0; 72 return accumulator; 73 74 /** 75 * If provided input values, the accumulator function returns an updated sample correlation coefficient. If not provided input values, the accumulator function returns the current sample correlation coefficient. 76 * 77 * @private 78 * @param {number} [x] - new value 79 * @param {number} [y] - new value 80 * @returns {(number|null)} sample absolute correlation coefficient or null 81 */ 82 function accumulator( x, y ) { 83 if ( arguments.length === 0 ) { 84 if ( N === 0 ) { 85 return null; 86 } 87 return abs( acc() ); 88 } 89 N += 1; 90 return abs( acc( x, y ) ); 91 } 92 } 93 94 95 // EXPORTS // 96 97 module.exports = incrapcorr;