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.math4.legacy.stat.interval;
018
019import org.apache.commons.math4.legacy.exception.NotPositiveException;
020import org.apache.commons.math4.legacy.exception.NotStrictlyPositiveException;
021import org.apache.commons.math4.legacy.exception.NumberIsTooLargeException;
022import org.apache.commons.math4.legacy.exception.OutOfRangeException;
023import org.apache.commons.math4.legacy.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     *
090     * @param numberOfTrials number of trials
091     * @param numberOfSuccesses number of successes
092     * @param confidenceLevel desired probability that the true probability of
093     *        success falls within the returned interval
094     * @return Confidence interval containing the probability of success with
095     *         probability {@code confidenceLevel}
096     * @throws NotStrictlyPositiveException if {@code numberOfTrials <= 0}.
097     * @throws NotPositiveException if {@code numberOfSuccesses < 0}.
098     * @throws NumberIsTooLargeException if {@code numberOfSuccesses > numberOfTrials}.
099     * @throws OutOfRangeException if {@code confidenceLevel} is not in the interval {@code (0, 1)}.
100     */
101    public static ConfidenceInterval getClopperPearsonInterval(int numberOfTrials, int numberOfSuccesses,
102                                                               double confidenceLevel) {
103        return CLOPPER_PEARSON.createInterval(numberOfTrials, numberOfSuccesses, confidenceLevel);
104    }
105
106    /**
107     * Create a binomial confidence interval for the true probability of success
108     * of an unknown binomial distribution with the given observed number of
109     * trials, successes and confidence level using the Normal approximation to
110     * the binomial distribution.
111     *
112     * @param numberOfTrials number of trials
113     * @param numberOfSuccesses number of successes
114     * @param confidenceLevel desired probability that the true probability of
115     *        success falls within the interval
116     * @return Confidence interval containing the probability of success with
117     *         probability {@code confidenceLevel}
118     */
119    public static ConfidenceInterval getNormalApproximationInterval(int numberOfTrials, int numberOfSuccesses,
120                                                                    double confidenceLevel) {
121        return NORMAL_APPROXIMATION.createInterval(numberOfTrials, numberOfSuccesses, confidenceLevel);
122    }
123
124    /**
125     * Create a Wilson score binomial confidence interval for the true
126     * probability of success of an unknown binomial distribution with the given
127     * observed number of trials, successes and confidence level.
128     *
129     * @param numberOfTrials number of trials
130     * @param numberOfSuccesses number of successes
131     * @param confidenceLevel desired probability that the true probability of
132     *        success falls within the returned interval
133     * @return Confidence interval containing the probability of success with
134     *         probability {@code confidenceLevel}
135     * @throws NotStrictlyPositiveException if {@code numberOfTrials <= 0}.
136     * @throws NotPositiveException if {@code numberOfSuccesses < 0}.
137     * @throws NumberIsTooLargeException if {@code numberOfSuccesses > numberOfTrials}.
138     * @throws OutOfRangeException if {@code confidenceLevel} is not in the interval {@code (0, 1)}.
139     */
140    public static ConfidenceInterval getWilsonScoreInterval(int numberOfTrials, int numberOfSuccesses,
141                                                            double confidenceLevel) {
142        return WILSON_SCORE.createInterval(numberOfTrials, numberOfSuccesses, confidenceLevel);
143    }
144
145    /**
146     * Verifies that parameters satisfy preconditions.
147     *
148     * @param numberOfTrials number of trials (must be positive)
149     * @param numberOfSuccesses number of successes (must not exceed numberOfTrials)
150     * @param confidenceLevel confidence level (must be strictly between 0 and 1)
151     * @throws NotStrictlyPositiveException if {@code numberOfTrials <= 0}.
152     * @throws NotPositiveException if {@code numberOfSuccesses < 0}.
153     * @throws NumberIsTooLargeException if {@code numberOfSuccesses > numberOfTrials}.
154     * @throws OutOfRangeException if {@code confidenceLevel} is not in the interval {@code (0, 1)}.
155     */
156    static void checkParameters(int numberOfTrials, int numberOfSuccesses, double confidenceLevel) {
157        if (numberOfTrials <= 0) {
158            throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_TRIALS, numberOfTrials);
159        }
160        if (numberOfSuccesses < 0) {
161            throw new NotPositiveException(LocalizedFormats.NEGATIVE_NUMBER_OF_SUCCESSES, numberOfSuccesses);
162        }
163        if (numberOfSuccesses > numberOfTrials) {
164            throw new NumberIsTooLargeException(LocalizedFormats.NUMBER_OF_SUCCESS_LARGER_THAN_POPULATION_SIZE,
165                                                numberOfSuccesses, numberOfTrials, true);
166        }
167        if (confidenceLevel <= 0 || confidenceLevel >= 1) {
168            throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUNDS_CONFIDENCE_LEVEL,
169                                          confidenceLevel, 0, 1);
170        }
171    }
172}