time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

factory.js (7317B)


      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 setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
     24 var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
     25 var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' );
     26 var isPositive = require( '@stdlib/assert/is-positive-number' ).isPrimitive;
     27 var isObject = require( '@stdlib/assert/is-plain-object' );
     28 var isFunction = require( '@stdlib/assert/is-function' );
     29 var hasOwnProp = require( '@stdlib/assert/has-own-property' );
     30 var constantFunction = require( '@stdlib/utils/constant-function' );
     31 var noop = require( '@stdlib/utils/noop' );
     32 var randu = require( './../../../base/mt19937' ).factory;
     33 var isnan = require( '@stdlib/math/base/assert/is-nan' );
     34 var typedarray2json = require( '@stdlib/array/to-json' );
     35 var exponential0 = require( './exponential.js' );
     36 
     37 
     38 // MAIN //
     39 
     40 /**
     41 * Returns a pseudorandom number generator for generating exponentially distributed random numbers.
     42 *
     43 * @param {PositiveNumber} [lambda] - rate parameter
     44 * @param {Options} [options] - function options
     45 * @param {PRNG} [options.prng] - pseudorandom number generator which generates uniformly distributed pseudorandom numbers
     46 * @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed
     47 * @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state
     48 * @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
     49 * @throws {TypeError} `lambda` must be a positive number
     50 * @throws {TypeError} options argument must be an object
     51 * @throws {TypeError} must provide valid options
     52 * @throws {Error} must provide a valid state
     53 * @returns {PRNG} pseudorandom number generator
     54 *
     55 * @example
     56 * var exponential = factory( 0.5 );
     57 * var v = exponential();
     58 * // returns <number>
     59 *
     60 * @example
     61 * var exponential = factory( 0.8, {
     62 *     'seed': 297
     63 * });
     64 * var v = exponential();
     65 * // returns ~3.735
     66 *
     67 * @example
     68 * var exponential = factory();
     69 * var v = exponential( 0.5 );
     70 * // returns <number>
     71 */
     72 function factory() {
     73 	var lambda;
     74 	var opts;
     75 	var rand;
     76 	var prng;
     77 
     78 	if ( arguments.length === 0 ) {
     79 		rand = randu();
     80 	} else if (
     81 		arguments.length === 1 &&
     82 		isObject( arguments[ 0 ] )
     83 	) {
     84 		opts = arguments[ 0 ];
     85 		if ( hasOwnProp( opts, 'prng' ) ) {
     86 			if ( !isFunction( opts.prng ) ) {
     87 				throw new TypeError( 'invalid option. `prng` option must be a pseudorandom number generator function. Option: `' + opts.prng + '`.' );
     88 			}
     89 			rand = opts.prng;
     90 		} else {
     91 			rand = randu( opts );
     92 		}
     93 	} else {
     94 		lambda = arguments[ 0 ];
     95 		if ( !isPositive( lambda ) ) {
     96 			throw new TypeError( 'invalid argument. First argument must be a positive number. Value: `' + lambda + '`.' );
     97 		}
     98 		if ( arguments.length > 1 ) {
     99 			opts = arguments[ 1 ];
    100 			if ( !isObject( opts ) ) {
    101 				throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + opts + '`.' );
    102 			}
    103 			if ( hasOwnProp( opts, 'prng' ) ) {
    104 				if ( !isFunction( opts.prng ) ) {
    105 					throw new TypeError( 'invalid option. `prng` option must be a pseudorandom number generator function. Option: `' + opts.prng + '`.' );
    106 				}
    107 				rand = opts.prng;
    108 			} else {
    109 				rand = randu( opts );
    110 			}
    111 		} else {
    112 			rand = randu();
    113 		}
    114 	}
    115 	if ( lambda === void 0 ) {
    116 		prng = exponential2;
    117 	} else {
    118 		prng = exponential1;
    119 	}
    120 	setReadOnly( prng, 'NAME', 'exponential' );
    121 
    122 	// If we are provided an "external" PRNG, we don't support getting or setting PRNG state, as we'd need to check for compatible state value types, etc, entailing considerable complexity.
    123 	if ( opts && opts.prng ) {
    124 		setReadOnly( prng, 'seed', null );
    125 		setReadOnly( prng, 'seedLength', null );
    126 		setReadWriteAccessor( prng, 'state', constantFunction( null ), noop );
    127 		setReadOnly( prng, 'stateLength', null );
    128 		setReadOnly( prng, 'byteLength', null );
    129 		setReadOnly( prng, 'toJSON', constantFunction( null ) );
    130 		setReadOnly( prng, 'PRNG', rand );
    131 	} else {
    132 		setReadOnlyAccessor( prng, 'seed', getSeed );
    133 		setReadOnlyAccessor( prng, 'seedLength', getSeedLength );
    134 		setReadWriteAccessor( prng, 'state', getState, setState );
    135 		setReadOnlyAccessor( prng, 'stateLength', getStateLength );
    136 		setReadOnlyAccessor( prng, 'byteLength', getStateSize );
    137 		setReadOnly( prng, 'toJSON', toJSON );
    138 		setReadOnly( prng, 'PRNG', rand );
    139 		rand = rand.normalized;
    140 	}
    141 	return prng;
    142 
    143 	/**
    144 	* Returns the PRNG seed.
    145 	*
    146 	* @private
    147 	* @returns {PRNGSeedMT19937} seed
    148 	*/
    149 	function getSeed() {
    150 		return rand.seed;
    151 	}
    152 
    153 	/**
    154 	* Returns the PRNG seed length.
    155 	*
    156 	* @private
    157 	* @returns {PositiveInteger} seed length
    158 	*/
    159 	function getSeedLength() {
    160 		return rand.seedLength;
    161 	}
    162 
    163 	/**
    164 	* Returns the PRNG state length.
    165 	*
    166 	* @private
    167 	* @returns {PositiveInteger} state length
    168 	*/
    169 	function getStateLength() {
    170 		return rand.stateLength;
    171 	}
    172 
    173 	/**
    174 	* Returns the PRNG state size (in bytes).
    175 	*
    176 	* @private
    177 	* @returns {PositiveInteger} state size (in bytes)
    178 	*/
    179 	function getStateSize() {
    180 		return rand.byteLength;
    181 	}
    182 
    183 	/**
    184 	* Returns the current pseudorandom number generator state.
    185 	*
    186 	* @private
    187 	* @returns {PRNGStateMT19937} current state
    188 	*/
    189 	function getState() {
    190 		return rand.state;
    191 	}
    192 
    193 	/**
    194 	* Sets the pseudorandom number generator state.
    195 	*
    196 	* @private
    197 	* @param {PRNGStateMT19937} s - generator state
    198 	* @throws {Error} must provide a valid state
    199 	*/
    200 	function setState( s ) {
    201 		rand.state = s;
    202 	}
    203 
    204 	/**
    205 	* Serializes the pseudorandom number generator as a JSON object.
    206 	*
    207 	* ## Notes
    208 	*
    209 	* -   `JSON.stringify()` implicitly calls this method when stringifying a PRNG.
    210 	*
    211 	* @private
    212 	* @returns {Object} JSON representation
    213 	*/
    214 	function toJSON() {
    215 		var out = {};
    216 		out.type = 'PRNG';
    217 		out.name = prng.NAME;
    218 		out.state = typedarray2json( rand.state );
    219 		if ( lambda === void 0 ) {
    220 			out.params = [];
    221 		} else {
    222 			out.params = [ lambda ];
    223 		}
    224 		return out;
    225 	}
    226 
    227 	/**
    228 	* Returns a pseudorandom number drawn from an exponential distribution with bound parameter `lambda`.
    229 	*
    230 	* @private
    231 	* @returns {NonNegativeNumber} pseudorandom number
    232 	*
    233 	* @example
    234 	* var v = exponential1();
    235 	* // returns <number>
    236 	*/
    237 	function exponential1() {
    238 		return exponential0( rand, lambda );
    239 	}
    240 
    241 	/**
    242 	* Returns a pseudorandom number drawn from an exponential distribution with parameter `lambda`.
    243 	*
    244 	* @private
    245 	* @param {PositiveNumber} lambda - rate parameter
    246 	* @returns {NonNegativeNumber} pseudorandom number
    247 	*
    248 	* @example
    249 	* var v = exponential2( 4.8 );
    250 	* // returns <number>
    251 	*/
    252 	function exponential2( lambda ) {
    253 		if (
    254 			isnan( lambda ) ||
    255 			lambda <= 0.0
    256 		) {
    257 			return NaN;
    258 		}
    259 		return exponential0( rand, lambda );
    260 	}
    261 }
    262 
    263 
    264 // EXPORTS //
    265 
    266 module.exports = factory;