import { AbstractSnapshot } from './AbstractSnapshot' ; import { WeightSample } from '../domain' ; import { binarySearch } from '../../util/binarySearch' ; /**
 * A statistical snapshot of a  WeightedSnapshot .
  export class WeightedSnapshot extends AbstractSnapshot { values = [ ] ; normWeights = [ ] ; quantiles = [ 0.0 ] ; constructor ( values ) { super ( ) ; let copy = values . sort ( ( a , b ) => { if ( a . value < b . value ) { return - 1 ; } if ( a . value > b . value ) { return 1 ; } return 0 ; } ) ; let sumWeight = 0 ; for ( let sample of copy ) { sumWeight += sample . weight ; } for ( let i = 0 ; i < copy . length ; i ++ ) { this . values [ i ] = copy [ i ] . value ; this . normWeights [ i ] = copy [ i ] . weight / sumWeight ; } for ( let i = 1 ; i < copy . length ; i ++ ) { this . quantiles [ i ] = this . quantiles [ i - 1 ] + this . normWeights [ i - 1 ] ; } } param quantile return getValue ( quantile ) { if ( quantile < 0.0 || quantile > 1.0 || isNaN ( quantile ) ) { throw new Error ( quantile + ' is not in [0..1]' ) ; } if ( this . values . length === 0 ) { return 0.0 ; } let posx = binarySearch ( this . quantiles , quantile ) ; if ( posx < 0 ) { posx = ( ( - posx ) - 1 ) - 1 ; } if ( posx < 1 ) { return this . values [ 0 ] ; } if ( posx >= this . values . length ) { return this . values [ this . values . length - 1 ] ; } return this . values [ posx ] ; } return getValues ( ) { return this . values ; } return size ( ) { return this . values . length ; } return getMax ( ) { if ( this . values . length === 0 ) { return 0 ; } return this . values [ this . values . length - 1 ] ; } return getMean ( ) { if ( this . values . length === 0 ) { return 0 ; } let sum = 0.0 ; for ( let i = 0 ; i < this . values . length ; i ++ ) { sum += this . values [ i ] * this . normWeights [ i ] ; } return sum ; } return getMin ( ) { if ( this . values . length === 0 ) { return 0 ; } return this . values [ 0 ] ; } return getStdDev ( ) { if ( this . values . length <= 1 ) { return 0 ; } let mean = this . getMean ( ) ; let variance = 0 ; for ( let i = 0 ; i < this . values . length ; i ++ ) { let diff = this . values [ i ] - mean ; variance += this . normWeights [ i ] * diff * diff ; } return Math . sqrt ( variance ) ; } }