001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.math3.stat.interval;
018
019import org.apache.commons.math3.exception.NotPositiveException;
020import org.apache.commons.math3.exception.NotStrictlyPositiveException;
021import org.apache.commons.math3.exception.NumberIsTooLargeException;
022import org.apache.commons.math3.exception.OutOfRangeException;
023import org.apache.commons.math3.exception.util.LocalizedFormats;
024
025/**
026 * Factory methods to generate confidence intervals for a binomial proportion.
027 * The supported methods are:
028 * <ul>
029 * <li>Agresti-Coull interval</li>
030 * <li>Clopper-Pearson method (exact method)</li>
031 * <li>Normal approximation (based on central limit theorem)</li>
032 * <li>Wilson score interval</li>
033 * </ul>
034 *
035 * @since 3.3
036 */
037public final class IntervalUtils {
038
039    /** Singleton Agresti-Coull instance. */
040    private static final BinomialConfidenceInterval AGRESTI_COULL = new AgrestiCoullInterval();
041
042    /** Singleton Clopper-Pearson instance. */
043    private static final BinomialConfidenceInterval CLOPPER_PEARSON = new ClopperPearsonInterval();
044
045    /** Singleton NormalApproximation instance. */
046    private static final BinomialConfidenceInterval NORMAL_APPROXIMATION = new NormalApproximationInterval();
047
048    /** Singleton Wilson score instance. */
049    private static final BinomialConfidenceInterval WILSON_SCORE = new WilsonScoreInterval();
050
051    /**
052     * Prevent instantiation.
053     */
054    private IntervalUtils() {
055    }
056
057    /**
058     * Create an Agresti-Coull binomial confidence interval for the true
059     * probability of success of an unknown binomial distribution with the given
060     * observed number of trials, successes and confidence level.
061     *
062     * @param numberOfTrials number of trials
063     * @param numberOfSuccesses number of successes
064     * @param confidenceLevel desired probability that the true probability of
065     *        success falls within the returned interval
066     * @return Confidence interval containing the probability of success with
067     *         probability {@code confidenceLevel}
068     * @throws NotStrictlyPositiveException if {@code numberOfTrials <= 0}.
069     * @throws NotPositiveException if {@code numberOfSuccesses < 0}.
070     * @throws NumberIsTooLargeException if {@code numberOfSuccesses > numberOfTrials}.
071     * @throws OutOfRangeException if {@code confidenceLevel} is not in the interval {@code (0, 1)}.
072     */
073    public static ConfidenceInterval getAgrestiCoullInterval(int numberOfTrials, int numberOfSuccesses,
074                                                             double confidenceLevel) {
075        return AGRESTI_COULL.createInterval(numberOfTrials, numberOfSuccesses, confidenceLevel);
076    }
077
078    /**
079     * Create a Clopper-Pearson binomial confidence interval for the true
080     * probability of success of an unknown binomial distribution with the given
081     * observed number of trials, successes and confidence level.
082     * <p>
083     * Preconditions:
084     * <ul>
085     * <li>{@code numberOfTrials} must be positive</li>
086     * <li>{@code numberOfSuccesses} may not exceed {@code numberOfTrials}</li>
087     * <li>{@code confidenceLevel} must be strictly between 0 and 1 (exclusive)</li>
088     * </ul>
089     * </p>
090     *
091     * @param numberOfTrials number of trials
092     * @param numberOfSuccesses number of successes
093     * @param confidenceLevel desired probability that the true probability of
094     *        success falls within the returned interval
095     * @return Confidence interval containing the probability of success with
096     *         probability {@code confidenceLevel}
097     * @throws NotStrictlyPositiveException if {@code numberOfTrials <= 0}.
098     * @throws NotPositiveException if {@code numberOfSuccesses < 0}.
099     * @throws NumberIsTooLargeException if {@code numberOfSuccesses > numberOfTrials}.
100     * @throws OutOfRangeException if {@code confidenceLevel} is not in the interval {@code (0, 1)}.
101     */
102    public static ConfidenceInterval getClopperPearsonInterval(int numberOfTrials, int numberOfSuccesses,
103                                                               double confidenceLevel) {
104        return CLOPPER_PEARSON.createInterval(numberOfTrials, numberOfSuccesses, confidenceLevel);
105    }
106
107    /**
108     * Create a binomial confidence interval for the true probability of success
109     * of an unknown binomial distribution with the given observed number of
110     * trials, successes and confidence level using the Normal approximation to
111     * the binomial distribution.
112     *
113     * @param numberOfTrials number of trials
114     * @param numberOfSuccesses number of successes
115     * @param confidenceLevel desired probability that the true probability of
116     *        success falls within the interval
117     * @return Confidence interval containing the probability of success with
118     *         probability {@code confidenceLevel}
119     */
120    public static ConfidenceInterval getNormalApproximationInterval(int numberOfTrials, int numberOfSuccesses,
121                                                                    double confidenceLevel) {
122        return NORMAL_APPROXIMATION.createInterval(numberOfTrials, numberOfSuccesses, confidenceLevel);
123    }
124
125    /**
126     * Create a Wilson score binomial confidence interval for the true
127     * probability of success of an unknown binomial distribution with the given
128     * observed number of trials, successes and confidence level.
129     *
130     * @param numberOfTrials number of trials
131     * @param numberOfSuccesses number of successes
132     * @param confidenceLevel desired probability that the true probability of
133     *        success falls within the returned interval
134     * @return Confidence interval containing the probability of success with
135     *         probability {@code confidenceLevel}
136     * @throws NotStrictlyPositiveException if {@code numberOfTrials <= 0}.
137     * @throws NotPositiveException if {@code numberOfSuccesses < 0}.
138     * @throws NumberIsTooLargeException if {@code numberOfSuccesses > numberOfTrials}.
139     * @throws OutOfRangeException if {@code confidenceLevel} is not in the interval {@code (0, 1)}.
140     */
141    public static ConfidenceInterval getWilsonScoreInterval(int numberOfTrials, int numberOfSuccesses,
142                                                            double confidenceLevel) {
143        return WILSON_SCORE.createInterval(numberOfTrials, numberOfSuccesses, confidenceLevel);
144    }
145
146    /**
147     * Verifies that parameters satisfy preconditions.
148     *
149     * @param numberOfTrials number of trials (must be positive)
150     * @param numberOfSuccesses number of successes (must not exceed numberOfTrials)
151     * @param confidenceLevel confidence level (must be strictly between 0 and 1)
152     * @throws NotStrictlyPositiveException if {@code numberOfTrials <= 0}.
153     * @throws NotPositiveException if {@code numberOfSuccesses < 0}.
154     * @throws NumberIsTooLargeException if {@code numberOfSuccesses > numberOfTrials}.
155     * @throws OutOfRangeException if {@code confidenceLevel} is not in the interval {@code (0, 1)}.
156     */
157    static void checkParameters(int numberOfTrials, int numberOfSuccesses, double confidenceLevel) {
158        if (numberOfTrials <= 0) {
159            throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_TRIALS, numberOfTrials);
160        }
161        if (numberOfSuccesses < 0) {
162            throw new NotPositiveException(LocalizedFormats.NEGATIVE_NUMBER_OF_SUCCESSES, numberOfSuccesses);
163        }
164        if (numberOfSuccesses > numberOfTrials) {
165            throw new NumberIsTooLargeException(LocalizedFormats.NUMBER_OF_SUCCESS_LARGER_THAN_POPULATION_SIZE,
166                                                numberOfSuccesses, numberOfTrials, true);
167        }
168        if (confidenceLevel <= 0 || confidenceLevel >= 1) {
169            throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUNDS_CONFIDENCE_LEVEL,
170                                          confidenceLevel, 0, 1);
171        }
172    }
173
174}