WeibullDistribution.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.math3.distribution;

  18. import org.apache.commons.math3.exception.NotStrictlyPositiveException;
  19. import org.apache.commons.math3.exception.OutOfRangeException;
  20. import org.apache.commons.math3.exception.util.LocalizedFormats;
  21. import org.apache.commons.math3.random.RandomGenerator;
  22. import org.apache.commons.math3.random.Well19937c;
  23. import org.apache.commons.math3.special.Gamma;
  24. import org.apache.commons.math3.util.FastMath;

  25. /**
  26.  * Implementation of the Weibull distribution. This implementation uses the
  27.  * two parameter form of the distribution defined by
  28.  * <a href="http://mathworld.wolfram.com/WeibullDistribution.html">
  29.  * Weibull Distribution</a>, equations (1) and (2).
  30.  *
  31.  * @see <a href="http://en.wikipedia.org/wiki/Weibull_distribution">Weibull distribution (Wikipedia)</a>
  32.  * @see <a href="http://mathworld.wolfram.com/WeibullDistribution.html">Weibull distribution (MathWorld)</a>
  33.  * @since 1.1 (changed to concrete class in 3.0)
  34.  */
  35. public class WeibullDistribution extends AbstractRealDistribution {
  36.     /**
  37.      * Default inverse cumulative probability accuracy.
  38.      * @since 2.1
  39.      */
  40.     public static final double DEFAULT_INVERSE_ABSOLUTE_ACCURACY = 1e-9;
  41.     /** Serializable version identifier. */
  42.     private static final long serialVersionUID = 8589540077390120676L;
  43.     /** The shape parameter. */
  44.     private final double shape;
  45.     /** The scale parameter. */
  46.     private final double scale;
  47.     /** Inverse cumulative probability accuracy. */
  48.     private final double solverAbsoluteAccuracy;
  49.     /** Cached numerical mean */
  50.     private double numericalMean = Double.NaN;
  51.     /** Whether or not the numerical mean has been calculated */
  52.     private boolean numericalMeanIsCalculated = false;
  53.     /** Cached numerical variance */
  54.     private double numericalVariance = Double.NaN;
  55.     /** Whether or not the numerical variance has been calculated */
  56.     private boolean numericalVarianceIsCalculated = false;

  57.     /**
  58.      * Create a Weibull distribution with the given shape and scale and a
  59.      * location equal to zero.
  60.      * <p>
  61.      * <b>Note:</b> this constructor will implicitly create an instance of
  62.      * {@link Well19937c} as random generator to be used for sampling only (see
  63.      * {@link #sample()} and {@link #sample(int)}). In case no sampling is
  64.      * needed for the created distribution, it is advised to pass {@code null}
  65.      * as random generator via the appropriate constructors to avoid the
  66.      * additional initialisation overhead.
  67.      *
  68.      * @param alpha Shape parameter.
  69.      * @param beta Scale parameter.
  70.      * @throws NotStrictlyPositiveException if {@code alpha <= 0} or
  71.      * {@code beta <= 0}.
  72.      */
  73.     public WeibullDistribution(double alpha, double beta)
  74.         throws NotStrictlyPositiveException {
  75.         this(alpha, beta, DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
  76.     }

  77.     /**
  78.      * Create a Weibull distribution with the given shape, scale and inverse
  79.      * cumulative probability accuracy and a location equal to zero.
  80.      * <p>
  81.      * <b>Note:</b> this constructor will implicitly create an instance of
  82.      * {@link Well19937c} as random generator to be used for sampling only (see
  83.      * {@link #sample()} and {@link #sample(int)}). In case no sampling is
  84.      * needed for the created distribution, it is advised to pass {@code null}
  85.      * as random generator via the appropriate constructors to avoid the
  86.      * additional initialisation overhead.
  87.      *
  88.      * @param alpha Shape parameter.
  89.      * @param beta Scale parameter.
  90.      * @param inverseCumAccuracy Maximum absolute error in inverse
  91.      * cumulative probability estimates
  92.      * (defaults to {@link #DEFAULT_INVERSE_ABSOLUTE_ACCURACY}).
  93.      * @throws NotStrictlyPositiveException if {@code alpha <= 0} or
  94.      * {@code beta <= 0}.
  95.      * @since 2.1
  96.      */
  97.     public WeibullDistribution(double alpha, double beta,
  98.                                double inverseCumAccuracy) {
  99.         this(new Well19937c(), alpha, beta, inverseCumAccuracy);
  100.     }

  101.     /**
  102.      * Creates a Weibull distribution.
  103.      *
  104.      * @param rng Random number generator.
  105.      * @param alpha Shape parameter.
  106.      * @param beta Scale parameter.
  107.      * @throws NotStrictlyPositiveException if {@code alpha <= 0} or {@code beta <= 0}.
  108.      * @since 3.3
  109.      */
  110.     public WeibullDistribution(RandomGenerator rng, double alpha, double beta)
  111.         throws NotStrictlyPositiveException {
  112.         this(rng, alpha, beta, DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
  113.     }

  114.     /**
  115.      * Creates a Weibull distribution.
  116.      *
  117.      * @param rng Random number generator.
  118.      * @param alpha Shape parameter.
  119.      * @param beta Scale parameter.
  120.      * @param inverseCumAccuracy Maximum absolute error in inverse
  121.      * cumulative probability estimates
  122.      * (defaults to {@link #DEFAULT_INVERSE_ABSOLUTE_ACCURACY}).
  123.      * @throws NotStrictlyPositiveException if {@code alpha <= 0} or {@code beta <= 0}.
  124.      * @since 3.1
  125.      */
  126.     public WeibullDistribution(RandomGenerator rng,
  127.                                double alpha,
  128.                                double beta,
  129.                                double inverseCumAccuracy)
  130.         throws NotStrictlyPositiveException {
  131.         super(rng);

  132.         if (alpha <= 0) {
  133.             throw new NotStrictlyPositiveException(LocalizedFormats.SHAPE,
  134.                                                    alpha);
  135.         }
  136.         if (beta <= 0) {
  137.             throw new NotStrictlyPositiveException(LocalizedFormats.SCALE,
  138.                                                    beta);
  139.         }
  140.         scale = beta;
  141.         shape = alpha;
  142.         solverAbsoluteAccuracy = inverseCumAccuracy;
  143.     }

  144.     /**
  145.      * Access the shape parameter, {@code alpha}.
  146.      *
  147.      * @return the shape parameter, {@code alpha}.
  148.      */
  149.     public double getShape() {
  150.         return shape;
  151.     }

  152.     /**
  153.      * Access the scale parameter, {@code beta}.
  154.      *
  155.      * @return the scale parameter, {@code beta}.
  156.      */
  157.     public double getScale() {
  158.         return scale;
  159.     }

  160.     /** {@inheritDoc} */
  161.     public double density(double x) {
  162.         if (x < 0) {
  163.             return 0;
  164.         }

  165.         final double xscale = x / scale;
  166.         final double xscalepow = FastMath.pow(xscale, shape - 1);

  167.         /*
  168.          * FastMath.pow(x / scale, shape) =
  169.          * FastMath.pow(xscale, shape) =
  170.          * FastMath.pow(xscale, shape - 1) * xscale
  171.          */
  172.         final double xscalepowshape = xscalepow * xscale;

  173.         return (shape / scale) * xscalepow * FastMath.exp(-xscalepowshape);
  174.     }

  175.     /** {@inheritDoc} */
  176.     @Override
  177.     public double logDensity(double x) {
  178.         if (x < 0) {
  179.             return Double.NEGATIVE_INFINITY;
  180.         }

  181.         final double xscale = x / scale;
  182.         final double logxscalepow = FastMath.log(xscale) * (shape - 1);

  183.         /*
  184.          * FastMath.pow(x / scale, shape) =
  185.          * FastMath.pow(xscale, shape) =
  186.          * FastMath.pow(xscale, shape - 1) * xscale
  187.          */
  188.         final double xscalepowshape = FastMath.exp(logxscalepow) * xscale;

  189.         return FastMath.log(shape / scale) + logxscalepow - xscalepowshape;
  190.     }

  191.     /** {@inheritDoc} */
  192.     public double cumulativeProbability(double x) {
  193.         double ret;
  194.         if (x <= 0.0) {
  195.             ret = 0.0;
  196.         } else {
  197.             ret = 1.0 - FastMath.exp(-FastMath.pow(x / scale, shape));
  198.         }
  199.         return ret;
  200.     }

  201.     /**
  202.      * {@inheritDoc}
  203.      *
  204.      * Returns {@code 0} when {@code p == 0} and
  205.      * {@code Double.POSITIVE_INFINITY} when {@code p == 1}.
  206.      */
  207.     @Override
  208.     public double inverseCumulativeProbability(double p) {
  209.         double ret;
  210.         if (p < 0.0 || p > 1.0) {
  211.             throw new OutOfRangeException(p, 0.0, 1.0);
  212.         } else if (p == 0) {
  213.             ret = 0.0;
  214.         } else  if (p == 1) {
  215.             ret = Double.POSITIVE_INFINITY;
  216.         } else {
  217.             ret = scale * FastMath.pow(-FastMath.log1p(-p), 1.0 / shape);
  218.         }
  219.         return ret;
  220.     }

  221.     /**
  222.      * Return the absolute accuracy setting of the solver used to estimate
  223.      * inverse cumulative probabilities.
  224.      *
  225.      * @return the solver absolute accuracy.
  226.      * @since 2.1
  227.      */
  228.     @Override
  229.     protected double getSolverAbsoluteAccuracy() {
  230.         return solverAbsoluteAccuracy;
  231.     }

  232.     /**
  233.      * {@inheritDoc}
  234.      *
  235.      * The mean is {@code scale * Gamma(1 + (1 / shape))}, where {@code Gamma()}
  236.      * is the Gamma-function.
  237.      */
  238.     public double getNumericalMean() {
  239.         if (!numericalMeanIsCalculated) {
  240.             numericalMean = calculateNumericalMean();
  241.             numericalMeanIsCalculated = true;
  242.         }
  243.         return numericalMean;
  244.     }

  245.     /**
  246.      * used by {@link #getNumericalMean()}
  247.      *
  248.      * @return the mean of this distribution
  249.      */
  250.     protected double calculateNumericalMean() {
  251.         final double sh = getShape();
  252.         final double sc = getScale();

  253.         return sc * FastMath.exp(Gamma.logGamma(1 + (1 / sh)));
  254.     }

  255.     /**
  256.      * {@inheritDoc}
  257.      *
  258.      * The variance is {@code scale^2 * Gamma(1 + (2 / shape)) - mean^2}
  259.      * where {@code Gamma()} is the Gamma-function.
  260.      */
  261.     public double getNumericalVariance() {
  262.         if (!numericalVarianceIsCalculated) {
  263.             numericalVariance = calculateNumericalVariance();
  264.             numericalVarianceIsCalculated = true;
  265.         }
  266.         return numericalVariance;
  267.     }

  268.     /**
  269.      * used by {@link #getNumericalVariance()}
  270.      *
  271.      * @return the variance of this distribution
  272.      */
  273.     protected double calculateNumericalVariance() {
  274.         final double sh = getShape();
  275.         final double sc = getScale();
  276.         final double mn = getNumericalMean();

  277.         return (sc * sc) * FastMath.exp(Gamma.logGamma(1 + (2 / sh))) -
  278.                (mn * mn);
  279.     }

  280.     /**
  281.      * {@inheritDoc}
  282.      *
  283.      * The lower bound of the support is always 0 no matter the parameters.
  284.      *
  285.      * @return lower bound of the support (always 0)
  286.      */
  287.     public double getSupportLowerBound() {
  288.         return 0;
  289.     }

  290.     /**
  291.      * {@inheritDoc}
  292.      *
  293.      * The upper bound of the support is always positive infinity
  294.      * no matter the parameters.
  295.      *
  296.      * @return upper bound of the support (always
  297.      * {@code Double.POSITIVE_INFINITY})
  298.      */
  299.     public double getSupportUpperBound() {
  300.         return Double.POSITIVE_INFINITY;
  301.     }

  302.     /** {@inheritDoc} */
  303.     public boolean isSupportLowerBoundInclusive() {
  304.         return true;
  305.     }

  306.     /** {@inheritDoc} */
  307.     public boolean isSupportUpperBoundInclusive() {
  308.         return false;
  309.     }

  310.     /**
  311.      * {@inheritDoc}
  312.      *
  313.      * The support of this distribution is connected.
  314.      *
  315.      * @return {@code true}
  316.      */
  317.     public boolean isSupportConnected() {
  318.         return true;
  319.     }
  320. }