## This file is part of MLPY.
## Confidence Interval methods.
    
## This code is written by Davide Albanese, <albanese@fbk.eu>.
##(C) 2008 Fondazione Bruno Kessler - Via Santa Croce 77, 38100 Trento, ITALY.

## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.

## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.

## You should have received a copy of the GNU General Public License
## along with this program.  If not, see <http://www.gnu.org/licenses/>.

__all__ = ["percentile_ci_median"]

from numpy import *

def percentile_ci_median(x, nboot=1000, alpha=0.025, rseed=0):
    """
    Percentile confidence interval for the median of a
    sample x and unknown distribution.

    Input
    
      * *x*     - [1D numpy array] sample
      * *nboot* - [integer] (>1) number of resamples
      * *alpha* - [float] confidence level is 100*(1-2*alpha) (0.0<alpha<1.0)
      * *rseed* - [integer] random seed

    Output
    
      * *ci* - (cimin, cimax) confidence interval

    Example:

    >>> from numpy import *
    >>> from mlpy import *
    >>> x = array([1,2,4,3,2,2,1,1,2,3,4,3,2])
    >>> percentile_ci_median(x, nboot = 100)
    (1.8461538461538463, 2.8461538461538463)
    """

    if nboot <= 1:
        raise ValueError("nboot (number of resamples) must be > 1")
    if alpha <= 0.0 or alpha >= 1:
        raise ValueError("alpha must be in (0, 1)")
  
    random.seed(rseed)
    xlen = x.shape[0]
    bootmean = empty(nboot)
    low = int(nboot * alpha)
    high = int(nboot * (1-alpha))
    
    for i in range(nboot):
        ridx = random.random_integers(0, xlen-1,(xlen, ))
        rx = x[ridx]
        bootmean[i] = rx.mean()

    bootmean.sort()
    return (bootmean[low], bootmean[high])
