# AUTHOR : André GILLIBERT (August 2017)
# LICENSE : Creative Commons CC0
# DESCRIPTION : Provides the Clopper-Pearson mid-P confidence interval of a binomial proportion
# This procedure is described in DOI: 10.2307/2348891
# EXAMPLE : cpmidp(3,100,conf=0.90)
# SYNTAX : cpmidp(successes,trials,conf=confidence level)

from scipy.stats.distributions import binom
from scipy.optimize import brentq

def cpmidp(x,n,conf=0.95):
	def midpvalue(p,level):
		return binom.cdf(x,n,p) - 0.5*binom.pmf(x,n,p) - level
	if x>0:
		lcl = brentq(midpvalue, 0, 1, args=0.5+conf/2,xtol=1e-8/n)
	else:
		lcl=0
	if x<n:
		ucl = brentq(midpvalue, 0, 1, args=0.5-conf/2,xtol=1e-8/n)
	else:
		ucl=1
	return (lcl,ucl)
