factory.js (2687B)
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 isNonNegativeInteger = require( '@stdlib/math/base/assert/is-nonnegative-integer' ); 24 var constantFunction = require( '@stdlib/utils/constant-function' ); 25 var isnan = require( '@stdlib/math/base/assert/is-nan' ); 26 var fln = require( '@stdlib/math/base/special/factorialln' ); 27 var max = require( '@stdlib/math/base/special/max' ); 28 var min = require( '@stdlib/math/base/special/min' ); 29 var NINF = require( '@stdlib/constants/float64/ninf' ); 30 var PINF = require( '@stdlib/constants/float64/pinf' ); 31 32 33 // MAIN // 34 35 /** 36 * Returns a function for evaluating the natural logarithm of the probability mass function (PMF) for a hypergeometric distribution with population size `N`, subpopulation size `K` and number of draws `n`. 37 * 38 * @param {NonNegativeInteger} N - population size 39 * @param {NonNegativeInteger} K - subpopulation size 40 * @param {NonNegativeInteger} n - number of draws 41 * @returns {Function} logPMF 42 * 43 * @example 44 * var mylogpmf = factory( 30, 20, 5 ); 45 * var y = mylogpmf( 4.0 ); 46 * // returns ~-1.079 47 * 48 * y = mylogpmf( 1.0 ); 49 * // returns ~-3.524 50 */ 51 function factory( N, K, n ) { 52 var maxs; 53 var mins; 54 if ( 55 isnan( N ) || 56 isnan( K ) || 57 isnan( n ) || 58 !isNonNegativeInteger( N ) || 59 !isNonNegativeInteger( K ) || 60 !isNonNegativeInteger( n ) || 61 N === PINF || 62 K === PINF || 63 K > N || 64 n > N 65 ) { 66 return constantFunction( NaN ); 67 } 68 69 mins = max( 0, n + K - N ); 70 maxs = min( K, n ); 71 return logpmf; 72 73 /** 74 * Evaluates the natural logarithm of the probability mass function (PMF) for a hypergeometric distribution. 75 * 76 * @private 77 * @param {number} x - input value 78 * @returns {number} evaluated logPMF 79 */ 80 function logpmf( x ) { 81 var ldenom; 82 var lnum; 83 if ( isnan( x ) ) { 84 return NaN; 85 } 86 if ( 87 isNonNegativeInteger( x ) && 88 mins <= x && 89 x <= maxs 90 ) { 91 lnum = fln( n ) + fln( K ) + fln( N - n ) + fln( N - K ); 92 ldenom = fln( N ) + fln( x ) + fln( n - x ); 93 ldenom += fln( K - x ) + fln( N - K + x - n ); 94 return lnum - ldenom; 95 } 96 return NINF; 97 } 98 } 99 100 101 // EXPORTS // 102 103 module.exports = factory;