main.js (9665B)
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 Readable = require( 'readable-stream' ).Readable; 24 var isPositiveNumber = require( '@stdlib/assert/is-positive-number' ).isPrimitive; 25 var isError = require( '@stdlib/assert/is-error' ); 26 var copy = require( '@stdlib/utils/copy' ); 27 var inherit = require( '@stdlib/utils/inherit' ); 28 var setNonEnumerable = require( '@stdlib/utils/define-nonenumerable-property' ); 29 var setNonEnumerableReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); 30 var setReadOnlyAccessor = require( '@stdlib/utils/define-read-only-accessor' ); 31 var setReadWriteAccessor = require( '@stdlib/utils/define-read-write-accessor' ); 32 var rgamma = require( './../../../base/gamma' ).factory; 33 var string2buffer = require( '@stdlib/buffer/from-string' ); 34 var nextTick = require( '@stdlib/utils/next-tick' ); 35 var DEFAULTS = require( './defaults.json' ); 36 var validate = require( './validate.js' ); 37 var debug = require( './debug.js' ); 38 39 40 // FUNCTIONS // 41 42 /** 43 * Returns the PRNG seed. 44 * 45 * @private 46 * @returns {(PRNGSeedMT19937|null)} seed 47 */ 48 function getSeed() { 49 return this._prng.seed; // eslint-disable-line no-invalid-this 50 } 51 52 /** 53 * Returns the PRNG seed length. 54 * 55 * @private 56 * @returns {(PositiveInteger|null)} seed length 57 */ 58 function getSeedLength() { 59 return this._prng.seedLength; // eslint-disable-line no-invalid-this 60 } 61 62 /** 63 * Returns the PRNG state length. 64 * 65 * @private 66 * @returns {(PositiveInteger|null)} state length 67 */ 68 function getStateLength() { 69 return this._prng.stateLength; // eslint-disable-line no-invalid-this 70 } 71 72 /** 73 * Returns the PRNG state size (in bytes). 74 * 75 * @private 76 * @returns {(PositiveInteger|null)} state size (in bytes) 77 */ 78 function getStateSize() { 79 return this._prng.byteLength; // eslint-disable-line no-invalid-this 80 } 81 82 /** 83 * Returns the current PRNG state. 84 * 85 * @private 86 * @returns {(PRNGStateMT19937|null)} current state 87 */ 88 function getState() { 89 return this._prng.state; // eslint-disable-line no-invalid-this 90 } 91 92 /** 93 * Sets the PRNG state. 94 * 95 * @private 96 * @param {PRNGStateMT19937} s - generator state 97 * @throws {Error} must provide a valid state 98 */ 99 function setState( s ) { 100 this._prng.state = s; // eslint-disable-line no-invalid-this 101 } 102 103 /** 104 * Implements the `_read` method. 105 * 106 * @private 107 * @param {number} size - number (of bytes) to read 108 * @returns {void} 109 */ 110 function read() { 111 /* eslint-disable no-invalid-this */ 112 var FLG; 113 var r; 114 115 if ( this._destroyed ) { 116 return; 117 } 118 FLG = true; 119 while ( FLG ) { 120 this._i += 1; 121 if ( this._i > this._iter ) { 122 debug( 'Finished generating pseudorandom numbers.' ); 123 return this.push( null ); 124 } 125 r = this._prng(); 126 127 debug( 'Generated a new pseudorandom number. Value: %d. Iter: %d.', r, this._i ); 128 129 if ( this._objectMode === false ) { 130 r = r.toString(); 131 if ( this._i === 1 ) { 132 r = string2buffer( r ); 133 } else { 134 r = string2buffer( this._sep+r ); 135 } 136 } 137 FLG = this.push( r ); 138 if ( this._i%this._siter === 0 ) { 139 this.emit( 'state', this.state ); 140 } 141 } 142 143 /* eslint-enable no-invalid-this */ 144 } 145 146 /** 147 * Gracefully destroys a stream, providing backward compatibility. 148 * 149 * @private 150 * @param {(string|Object|Error)} [error] - error 151 * @returns {RandomStream} Stream instance 152 */ 153 function destroy( error ) { 154 /* eslint-disable no-invalid-this */ 155 var self; 156 if ( this._destroyed ) { 157 debug( 'Attempted to destroy an already destroyed stream.' ); 158 return this; 159 } 160 self = this; 161 this._destroyed = true; 162 163 nextTick( close ); 164 165 return this; 166 167 /** 168 * Closes a stream. 169 * 170 * @private 171 */ 172 function close() { 173 if ( error ) { 174 debug( 'Stream was destroyed due to an error. Error: %s.', ( isError( error ) ) ? error.message : JSON.stringify( error ) ); 175 self.emit( 'error', error ); 176 } 177 debug( 'Closing the stream...' ); 178 self.emit( 'close' ); 179 } 180 181 /* eslint-enable no-invalid-this */ 182 } 183 184 185 // MAIN // 186 187 /** 188 * Stream constructor for generating a stream of pseudorandom numbers drawn from a gamma distribution. 189 * 190 * @constructor 191 * @param {PositiveNumber} alpha - shape parameter 192 * @param {PositiveNumber} beta - rate parameter 193 * @param {Options} [options] - stream options 194 * @param {boolean} [options.objectMode=false] - specifies whether the stream should operate in object mode 195 * @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to strings 196 * @param {NonNegativeNumber} [options.highWaterMark] - specifies the maximum number of bytes to store in an internal buffer before ceasing to generate additional pseudorandom numbers 197 * @param {string} [options.sep='\n'] - separator used to join streamed data 198 * @param {NonNegativeInteger} [options.iter] - number of iterations 199 * @param {PRNG} [options.prng] - pseudorandom number generator which generates uniformly distributed pseudorandom numbers 200 * @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed 201 * @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state 202 * @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state 203 * @param {PositiveInteger} [options.siter] - number of iterations after which to emit the PRNG state 204 * @throws {TypeError} `alpha` must be a positive number 205 * @throws {TypeError} `beta` must be a positive number 206 * @throws {TypeError} options argument must be an object 207 * @throws {TypeError} must provide valid options 208 * @throws {Error} must provide a valid state 209 * @returns {RandomStream} Stream instance 210 * 211 * @example 212 * var inspectStream = require( '@stdlib/streams/node/inspect-sink' ); 213 * 214 * function log( chunk ) { 215 * console.log( chunk.toString() ); 216 * } 217 * 218 * var opts = { 219 * 'iter': 10 220 * }; 221 * 222 * var stream = new RandomStream( 2.0, 5.0, opts ); 223 * 224 * stream.pipe( inspectStream( log ) ); 225 */ 226 function RandomStream( alpha, beta, options ) { 227 var opts; 228 var err; 229 if ( !( this instanceof RandomStream ) ) { 230 if ( arguments.length > 2 ) { 231 return new RandomStream( alpha, beta, options ); 232 } 233 return new RandomStream( alpha, beta ); 234 } 235 if ( !isPositiveNumber( alpha ) ) { 236 throw new TypeError( 'invalid argument. First argument must be a positive number. Value: `'+alpha+'`.' ); 237 } 238 if ( !isPositiveNumber( beta ) ) { 239 throw new TypeError( 'invalid argument. Second argument must be a positive number. Value: `'+beta+'`.' ); 240 } 241 opts = copy( DEFAULTS ); 242 if ( arguments.length > 2 ) { 243 err = validate( opts, options ); 244 if ( err ) { 245 throw err; 246 } 247 } 248 // Make the stream a readable stream: 249 debug( 'Creating a readable stream configured with the following options: %s.', JSON.stringify( opts ) ); 250 Readable.call( this, opts ); 251 252 // Destruction state: 253 setNonEnumerable( this, '_destroyed', false ); 254 255 // Cache whether the stream is operating in object mode: 256 setNonEnumerableReadOnly( this, '_objectMode', opts.objectMode ); 257 258 // Cache the separator: 259 setNonEnumerableReadOnly( this, '_sep', opts.sep ); 260 261 // Cache the total number of iterations: 262 setNonEnumerableReadOnly( this, '_iter', opts.iter ); 263 264 // Cache the number of iterations after which to emit the underlying PRNG state: 265 setNonEnumerableReadOnly( this, '_siter', opts.siter ); 266 267 // Initialize an iteration counter: 268 setNonEnumerable( this, '_i', 0 ); 269 270 // Create the underlying PRNG: 271 setNonEnumerableReadOnly( this, '_prng', rgamma( alpha, beta, opts ) ); 272 setNonEnumerableReadOnly( this, 'PRNG', this._prng.PRNG ); 273 274 return this; 275 } 276 277 /* 278 * Inherit from the `Readable` prototype. 279 */ 280 inherit( RandomStream, Readable ); 281 282 /** 283 * PRNG seed. 284 * 285 * @name seed 286 * @memberof RandomStream.prototype 287 * @type {(PRNGSeedMT19937|null)} 288 */ 289 setReadOnlyAccessor( RandomStream.prototype, 'seed', getSeed ); 290 291 /** 292 * PRNG seed length. 293 * 294 * @name seedLength 295 * @memberof RandomStream.prototype 296 * @type {(PositiveInteger|null)} 297 */ 298 setReadOnlyAccessor( RandomStream.prototype, 'seedLength', getSeedLength ); 299 300 /** 301 * PRNG state getter/setter. 302 * 303 * @name state 304 * @memberof RandomStream.prototype 305 * @type {(PRNGStateMT19937|null)} 306 * @throws {Error} must provide a valid state 307 */ 308 setReadWriteAccessor( RandomStream.prototype, 'state', getState, setState ); 309 310 /** 311 * PRNG state length. 312 * 313 * @name stateLength 314 * @memberof RandomStream.prototype 315 * @type {(PositiveInteger|null)} 316 */ 317 setReadOnlyAccessor( RandomStream.prototype, 'stateLength', getStateLength ); 318 319 /** 320 * PRNG state size (in bytes). 321 * 322 * @name byteLength 323 * @memberof RandomStream.prototype 324 * @type {(PositiveInteger|null)} 325 */ 326 setReadOnlyAccessor( RandomStream.prototype, 'byteLength', getStateSize ); 327 328 /** 329 * Implements the `_read` method. 330 * 331 * @private 332 * @name _read 333 * @memberof RandomStream.prototype 334 * @type {Function} 335 * @param {number} size - number (of bytes) to read 336 * @returns {void} 337 */ 338 setNonEnumerableReadOnly( RandomStream.prototype, '_read', read ); 339 340 /** 341 * Gracefully destroys a stream, providing backward compatibility. 342 * 343 * @name destroy 344 * @memberof RandomStream.prototype 345 * @type {Function} 346 * @param {(string|Object|Error)} [error] - error 347 * @returns {RandomStream} Stream instance 348 */ 349 setNonEnumerableReadOnly( RandomStream.prototype, 'destroy', destroy ); 350 351 352 // EXPORTS // 353 354 module.exports = RandomStream;