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