time-to-botec

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

simulate.js (2108B)


      1 /**
      2 * @license Apache-2.0
      3 *
      4 * Copyright (c) 2020 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 incrspace = require( '@stdlib/array/incrspace' );
     24 var sample = require( '@stdlib/random/sample' );
     25 var Float64Array = require( '@stdlib/array/float64' );
     26 var dfill = require( '@stdlib/blas/ext/base/dfill' );
     27 var tabulate = require( './tabulate.js' );
     28 var testStatistic = require( './statistic.js' );
     29 
     30 
     31 // MAIN //
     32 
     33 /**
     34 * Performs a Monte-Carlo simulation.
     35 *
     36 * @private
     37 * @param {NonNegativeInteger} N - number of indexed elements
     38 * @param {Float64Array} expected - expected number of observations
     39 * @param {NumericArray} p - probabilities
     40 * @param {number} stat - test statistic
     41 * @param {NonNegativeInteger} nobs - total number of observations
     42 * @param {NonNegativeInteger} niter - number of iterations
     43 * @returns {number} p-value
     44 */
     45 function simulate( N, expected, p, stat, nobs, niter ) {
     46 	var pool;
     47 	var opts;
     48 	var freq;
     49 	var cnt;
     50 	var v;
     51 	var i;
     52 
     53 	pool = incrspace( 0, N, 1 ); // TODO: replace with strided interface
     54 	opts = {
     55 		'size': nobs,
     56 		'probs': p
     57 	};
     58 	freq = new Float64Array( N );
     59 	cnt = 1;
     60 	for ( i = 0; i < niter; i++ ) {
     61 		v = sample( pool, opts ); // TODO: use `sample.factory` method once sample pkg is updated
     62 		freq = tabulate( N, v, 1, freq, 1 );
     63 		if ( testStatistic( N, freq, 1, expected, 1 ) >= stat ) { // TODO: consider replacing with low-level double-precision strided interface
     64 			cnt += 1;
     65 		}
     66 		if ( i < niter-1 ) {
     67 			dfill( N, 0.0, freq, 1 );
     68 		}
     69 	}
     70 	return cnt / ( niter+1 );
     71 }
     72 
     73 
     74 // EXPORTS //
     75 
     76 module.exports = simulate;