/* (non-Javadoc)
@see moa.classifiers.rules.RuleActiveLearningNodeInterface#computeProbability(double, double, double)
174602
public double computeProbability(double mean, double sd, double value) {
        double probability = 0.0;
        
      /* double diff = value - mean;
        if (sd > 0.0) {
            double k = (Math.abs(value - mean) / sd);
            if (k > 1.0) {
                probability = 1.0 / (k * k); // Chebyshev's inequality
            } else {
                probability = Math.exp(-(diff * diff / (2.0 * sd * sd)));
            }
        }*/
        
        if (sd > 0.0) {
            double k = (Math.abs(value - mean) / sd); // One tailed variant of Chebyshev's inequality
        	probability= 1.0 / (1+k*k); //cantelli's (one-tailed)
        	double var=Math.pow(sd, 2);
        	probability= 2*var/(var+Math.pow(Math.abs(value - mean), 2));
        	//probability= 1.0 / (1+k*k);
            //probability= 1.0 / (k*k); //chebyshev
        	//normal distribution
        	//double diff = value - mean;
        	//probability = Math.exp(-(diff * diff / (2.0 * sd * sd)));
        }
        
        return probability;
    }
996157
public double[] getPrediction(Instance instance) {
        int predictionMode = this.getLearnerToUse(instance, this.predictionFunction);
        return getPrediction(instance, predictionMode);
    }
1151715
@Reference(title = "Fast and accurate computation of binomial probabilities", //
      authors = "C. Loader", booktitle = "", //
      url = "http://projects.scipy.org/scipy/raw-attachment/ticket/620/loader2000Fast.pdf", //
      bibkey = "web/Loader00")
  private static double stirlingError(int n) {
    // Try to use a table value:
    if(n < 16) {
      return STIRLING_EXACT_ERROR[n << 1];
    }
    final double nn = n * n;
    // Use the appropriate number of terms
    if(n > 500) {
      return (S0 - S1 / nn) / n;
    }
    if(n > 80) {
      return ((S0 - (S1 - S2 / nn)) / nn) / n;
    }
    if(n > 35) {
      return ((S0 - (S1 - (S2 - S3 / nn) / nn) / nn) / n);
    }
    return ((S0 - (S1 - (S2 - (S3 - S4 / nn) / nn) / nn) / nn) / n);
  }
1304155
public SortedClassProbability[] sortByDescendingClassProbability(BinomialModelPrediction p) {
    String[] domainValues = m.getDomainValues(m.getResponseIdx());
    double[] classProbabilities = p.classProbabilities;
    return sortByDescendingClassProbability(domainValues, classProbabilities);
  }
593423
public void compute() 
	{
		if (!computable) {
			throw new RuntimeException("can't re-'compute' experiment results after a 'restore'");
		}
		expt = new MatchExpt[blockers.size()][learners.size()][datasets.size()];
		for (int i=0; i<blockers.size(); i++) {
			Blocker blocker = (Blocker)blockers.get(i);
			for (int j=0; j<learners.size(); j++) {
				StringDistanceLearner distance = (StringDistanceLearner)learners.get(j);
				for (int k=0; k<datasets.size(); k++) {
					MatchData dataset = (MatchData)datasets.get(k);
					expt[i][j][k] = new MatchExpt(dataset,distance,blocker);
				}
			}
		}
	}
675891
public DoubleArray getProbability() {
    if (TopicDistribution_Type.featOkTst && ((TopicDistribution_Type)jcasType).casFeat_probability == null)
      jcasType.jcas.throwFeatMissing("probability", "ch.epfl.bbp.uima.types.TopicDistribution");
    return (DoubleArray)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((TopicDistribution_Type)jcasType).casFeatCode_probability)));}
1017538
private SortedClassProbability[] sortByDescendingClassProbability(String[] domainValues, double[] classProbabilities) {
    assert (classProbabilities.length == domainValues.length);
    SortedClassProbability[] arr = new SortedClassProbability[domainValues.length];
    for (int i = 0; i < domainValues.length; i++) {
      arr[i] = new SortedClassProbability();
      arr[i].name = domainValues[i];
      arr[i].probability = classProbabilities[i];
    }
    Arrays.sort(arr, Collections.reverseOrder());
    return arr;
  }
225817
@Override
    public double inverseCumulativeProbability(final double p) throws OutOfRangeException {
        /*
         * IMPLEMENTATION NOTES
         * --------------------
         * Where applicable, use is made of the one-sided Chebyshev inequality
         * to bracket the root. This inequality states that
         * P(X - mu >= k * sig) <= 1 / (1 + k^2),
         * mu: mean, sig: standard deviation. Equivalently
         * 1 - P(X < mu + k * sig) <= 1 / (1 + k^2),
         * F(mu + k * sig) >= k^2 / (1 + k^2).
         *
         * For k = sqrt(p / (1 - p)), we find
         * F(mu + k * sig) >= p,
         * and (mu + k * sig) is an upper-bound for the root.
         *
         * Then, introducing Y = -X, mean(Y) = -mu, sd(Y) = sig, and
         * P(Y >= -mu + k * sig) <= 1 / (1 + k^2),
         * P(-X >= -mu + k * sig) <= 1 / (1 + k^2),
         * P(X <= mu - k * sig) <= 1 / (1 + k^2),
         * F(mu - k * sig) <= 1 / (1 + k^2).
         *
         * For k = sqrt((1 - p) / p), we find
         * F(mu - k * sig) <= p,
         * and (mu - k * sig) is a lower-bound for the root.
         *
         * In cases where the Chebyshev inequality does not apply, geometric
         * progressions 1, 2, 4, ... and -1, -2, -4, ... are used to bracket
         * the root.
         */
        if (p < 0.0 || p > 1.0) {
            throw new OutOfRangeException(p, 0, 1);
        }

        double lowerBound = getSupportLowerBound();
        if (p == 0.0) {
            return lowerBound;
        }

        double upperBound = getSupportUpperBound();
        if (p == 1.0) {
            return upperBound;
        }

        final double mu = getNumericalMean();
        final double sig = FastMath.sqrt(getNumericalVariance());
        final boolean chebyshevApplies;
        chebyshevApplies = !(Double.isInfinite(mu) || Double.isNaN(mu) || Double.isInfinite(sig) || Double.isNaN(sig));

        if (lowerBound == Double.NEGATIVE_INFINITY) {
            if (chebyshevApplies) {
                lowerBound = mu - sig * FastMath.sqrt((1. - p) / p);
            } else {
                lowerBound = -1.0;
                while (cumulativeProbability(lowerBound) >= p) {
                    lowerBound *= 2.0;
                }
            }
        }

        if (upperBound == Double.POSITIVE_INFINITY) {
            if (chebyshevApplies) {
                upperBound = mu + sig * FastMath.sqrt(p / (1. - p));
            } else {
                upperBound = 1.0;
                while (cumulativeProbability(upperBound) < p) {
                    upperBound *= 2.0;
                }
            }
        }

        final UnivariateFunction toSolve = new UnivariateFunction() {

            public double value(final double x) {
                return cumulativeProbability(x) - p;
            }
        };

        double x = UnivariateSolverUtils.solve(toSolve, lowerBound, upperBound, getSolverAbsoluteAccuracy());

        if (!isSupportConnected()) {
            /* Test for plateau. */
            final double dx = getSolverAbsoluteAccuracy();
            if (x - dx >= getSupportLowerBound()) {
                double px = cumulativeProbability(x);
                if (cumulativeProbability(x - dx) == px) {
                    upperBound = x;
                    while (upperBound - lowerBound > dx) {
                        final double midPoint = 0.5 * (lowerBound + upperBound);
                        if (cumulativeProbability(midPoint) < px) {
                            lowerBound = midPoint;
                        } else {
                            upperBound = midPoint;
                        }
                    }
                    return upperBound;
                }
            }
        }
        return x;
    }
665878
@Override
	public double getVariance() {
		if(isDeterministic()) {
			return 0.0;
		}
		if(size() == 0) {
			return Double.NaN;
		}

		double sum			= 0.0;
		double sumOfSquared = 0.0;
		for (double realization : getRealizations()) {
			sum += realization;
			sumOfSquared += realization * realization;
		}
		return sumOfSquared/size() - sum/size() * sum/size();
	}
1341814
double sparseProbabilisticAlgorithmCardinality() {
        final int m = this.m/*for performance*/;

        // compute the "indicator function" -- sum(2^(-M[j])) where M[j] is the
        // 'j'th register value
        double sum = 0;
        int numberOfZeroes = 0/*"V" in the paper*/;
        for(int j=0; j<m; j++) {
            final long register = sparseProbabilisticStorage.get(j);

            sum += 1.0 / (1L << register);
            if(register == 0L) numberOfZeroes++;
        }

        // apply the estimate and correction to the indicator function
        final double estimator = alphaMSquared / sum;
        if((numberOfZeroes != 0) && (estimator < smallEstimatorCutoff)) {
            return HLLUtil.smallEstimator(m, numberOfZeroes);
        } else if(estimator <= largeEstimatorCutoff) {
            return estimator;
        } else {
            return HLLUtil.largeEstimator(log2m, regwidth, estimator);
        }
    }
894049
double fullProbabilisticAlgorithmCardinality() {
        final int m = this.m/*for performance*/;

        // compute the "indicator function" -- sum(2^(-M[j])) where M[j] is the
        // 'j'th register value
        double sum = 0;
        int numberOfZeroes = 0/*"V" in the paper*/;
        final LongIterator iterator = probabilisticStorage.registerIterator();
        while(iterator.hasNext()) {
            final long register = iterator.next();

            sum += 1.0 / (1L << register);
            if(register == 0L) numberOfZeroes++;
        }

        // apply the estimate and correction to the indicator function
        final double estimator = alphaMSquared / sum;
        if((numberOfZeroes != 0) && (estimator < smallEstimatorCutoff)) {
            return HLLUtil.smallEstimator(m, numberOfZeroes);
        } else if(estimator <= largeEstimatorCutoff) {
            return estimator;
        } else {
            return HLLUtil.largeEstimator(log2m, regwidth, estimator);
        }
    }
316918
@Override
	public double getQuantile(double quantile, RandomVariableInterface probabilities) {
		if(isDeterministic()) {
			return valueIfNonStochastic;
		}
		if(size() == 0) {
			return Double.NaN;
		}

		throw new RuntimeException("Method not implemented.");
	}
811096
public double computeProbability(double mean, double sd, double value) {
		sd = sd + 0.00001;
		double probability = 0.0;
		double diff = value - mean;
		if (sd > 0.0) {
			 	double k = (Math.abs(value - mean)/sd);
			 	if (k > 1.0) {
			 		probability = 1.0/(k*k);
			 	}
			 	else {
			 		probability=  Math.exp(-(diff * diff / (2.0 * sd * sd)));
			 	}
		 }
		return probability;
	}
850965
public double computeConfidence( ImageRectangle r ) {
		return computeConfidence(r.x0,r.y0,r.x1,r.y1);
	}
1141095
public boolean isAnomaly(Instance instance,
			double uniVariateAnomalyProbabilityThreshold,
			double multiVariateAnomalyProbabilityThreshold,
			int numberOfInstanceesForAnomaly) {
		return this.getLearningNode().isAnomaly(instance, uniVariateAnomalyProbabilityThreshold,
				multiVariateAnomalyProbabilityThreshold,
				numberOfInstanceesForAnomaly);
	}
48540
@Override
	public double getInclusionProbability(Instance instance) {
		for (int i = 0 ; i < this.dimensions ; i++)
		{
			if ((int) instance.value(i) != this.coordinates[i])
				return 0.0;
		}
		
		return 1.0;
	}
932198
private static int selectWithProb(double probs[]) {
	double cutoff = Math.random();
	double curProbSum = 0.0;

	for (int i = 0; i < probs.length; i++) {
            curProbSum += probs[i];
            // NOTE: the assert is slightly larger than 1 to allow for marginal
            // accumulation due to double round-off errors
            assert curProbSum <= 1.0001
                : "sum of probabilities > 1: " + curProbSum;
            if (curProbSum >= cutoff)
                return i;
        }
        throw new IllegalStateException("Probablilities do not sum to 1");
    }