
    >hx~                        S r SSKJr  SSKrSSKJr  SSKJr  SSK	J
r
  SSKJr   SSKJrJrJr  S	rSSKrSSKJr  SSKJr  / SQr " S S5      rS rS rS r  SS jr  SS jr  SS jrSS jr g! \ a    SS
KJrJr  Sr NTf = f)zModule for functional boxplots.    )	NP_LT_123N)comb)_import_mpl)PCA)KDEMultivariate)brutedifferential_evolutionfminT)r   r
   F)Pool   )utils)
hdrboxplotfboxplotrainbowplot	banddepthc                   $    \ rS rSrSrS rS rSrg)
HdrResults   z#Wrap results and pretty print them.c                 :    U R                   R                  U5        g N)__dict__update)selfkwdss     rC:\Users\julio\OneDrive\Documentos\Trabajo\Ideas Frescas\venv\Lib\site-packages\statsmodels/graphics/functional.py__init__HdrResults.__init__   s    T"    c                     SR                  U R                  U R                  U R                  U R                  U R
                  U R                  5      nU$ )NzHDR boxplot summary:
-> median:
{}
-> 50% HDR (max, min):
{}
-> 90% HDR (max, min):
{}
-> Extra quantiles (max, min):
{}
-> Outliers:
{}
-> Outliers indices:
{}
)formatmedianhdr_50hdr_90extra_quantilesoutliersoutliers_idx)r   msgs     r   __repr__HdrResults.__repr__   sI    , T[[$++,,dmmT=N=NP 	 
r    N)__name__
__module____qualname____firstlineno____doc__r   r(   __static_attributes__r*   r   r   r   r      s    -#r   r   c                     U R                   nUR                  SUR                  S   5      U l         U R                  5       nX l         U$ )a  
Inverse transform on PCA.

Use PCA's `project` method by temporary replacing its factors with
`data`.

Parameters
----------
pca : statsmodels Principal Component Analysis instance
    The PCA object to use.
data : sequence of ndarrays or 2-D ndarray
    The vectors of functions to create a functional boxplot from.  If a
    sequence of 1-D arrays, these should all be the same size.
    The first axis is the function index, the second axis the one along
    which the function is defined.  So ``data[0, :]`` is the first
    functional curve.

Returns
-------
projection : ndarray
    nobs by nvar array of the projection onto ncomp factors
r   )factorsreshapeshapeproject)pcadatar3   
projections       r   _inverse_transformr:   -   s>    . kkG,,r7==#34CKJKr   c                     U R                  SS5      n UR                  U 5      nUS   Us=:  a	  US   :  a  O  OU[        X@5      S   U   -  nU$ SnU$ )aN  Find out if the curve is within the band.

The curve value at :attr:`idx` for a given PDF is only returned if
within bounds defined by the band. Otherwise, 1E6 is returned.

Parameters
----------
x : float
    Curve in reduced space.
idx : int
    Index value of the components to compute.
sign : int
    Return positive or negative value.
band : list of float
    PDF values `[min_pdf, max_pdf]` to be within.
pca : statsmodels Principal Component Analysis instance
    The PCA object to use.
ks_gaussian : KDEMultivariate instance

Returns
-------
value : float
    Curve value at `idx`.
r   r2   r       .A)r4   pdfr:   )xidxsignbandr7   ks_gaussianr=   values           r   _curve_constrainedrD   K   sd    2 	
		!RA
//!
CAwtAw)#1!4S99 L Lr   c           
      ^   U u  nu  p#pEpg[         (       aF  U(       d?  [        [        UUSX#U4SUS9R                  n[        [        UUSX#U4SUS9R                  n	O0[	        [        U[
        USX#U4S9n[	        [        U[
        USX#U4S9n	[        X85      S   U   [        X95      S   U   4nU$ )a  
Min and max values at `idx`.

Global optimization to find the extrema per component.

Parameters
----------
args: list
    It is a list of an idx and other arguments as a tuple:
        idx : int
            Index value of the components to compute
    The tuple contains:
        band : list of float
            PDF values `[min_pdf, max_pdf]` to be within.
        pca : statsmodels Principal Component Analysis instance
            The PCA object to use.
        bounds : sequence
            ``(min, max)`` pair for each components
        ks_gaussian : KDEMultivariate instance

Returns
-------
band : tuple of float
    ``(max, min)`` curve values at `idx`
r2      )boundsargsmaxiterseedr   )rangesfinishrH   r   )have_de_optimr	   rD   r>   r   r
   r:   )
rH   r?   rA   r7   rG   rB   	use_bruterJ   max_min_s
             r   _min_max_bandrQ   m   s    4 >B:C	:$V)}Y%&8,/T+L./d<<=A 	 &&8,/D{+K./d<<=A 	 'tD{;= 't4k:< s)!,S1s)!,S13DKr   c
           	      0  ^^%^&^'^(^) [         R                  " U5      u  pUc=  [        U S5      (       a  U R                  nO[        R
                  " [        U 5      5      n[        R                  " U 5      n Uc#  [        R
                  " U R                  S   5      nU R                  u  nm&[        XS9m(T(R                  n[        XSUR                  S   -  S9m'[        R                  " UR                  SS9UR                  SS9/5      R                  m%Tc  US	S
/mO(TR!                  US	S
/5        [#        [%        T5      5      mTR'                  SS9  [        T5      nT'R)                  U5      R+                  5       n[,        (       a:  [/        U5       Vs/ s H"  n[        R0                  " USTU   -
  S-  SS9PM$     snm)O9[/        U5       Vs/ s H"  n[        R0                  " USTU   -
  S-  SS9PM$     snm)[2        (       a"  U(       d  [5        U'4S jT%SU	S9R6                  nO[9        U'4S jT%[:        S9n[        R<                  " UT)TR                  U5         :  5      S   nU Vs/ s H  oU   PM	     nnU U   nX4UU%U&U'U(U)4S jjnT Vs/ s H  nS
U:w  d  M  S	U:w  d  M  X?:w  d  M  UPM     nn[        U5      S:  a,  / nU H#  nU" U/XS9 H  nUR?                  U5        M     M%     O/ n[A        T(U5      S   nU" S	S
/XS9nU" S
/XS9n[C        UUUUUUS.5      nURE                  [        R                  " U/U-  5      R                  U R                  SSSS9  URE                  UUSSS9  / nUR?                  URF                  " U/UQ7SS S!S".65        UR?                  URF                  " U/UQ7SS#S$S".65        [        U5      S:w  a]  URE                  [        R                  " U/[        U5      -  5      R                  [        R                  " U5      R                  S%S&S S'S(9  [        U5      S:w  a<  [I        U5       H-  u  nnUc  S)nO[K        UU   5      nURE                  UUS*S+US,9  M/     URM                  5       u  n n[O        5       n![Q        S!S$/U5       HK  u  nn"U!RS                  S-SSU"RU                  5       S   S.9n#U R?                  U#5        UR?                  U5        MM     [W        [Q        UU 5      5      n$[        U5      S:w  a3  U$RY                  S5        U$RY                  S!5        U$RY                  S$5        UR[                  U$R]                  5       U$R_                  5       S/S09  U
U4$ s  snf s  snf s  snf s  snf )1a  
High Density Region boxplot

Parameters
----------
data : sequence of ndarrays or 2-D ndarray
    The vectors of functions to create a functional boxplot from.  If a
    sequence of 1-D arrays, these should all be the same size.
    The first axis is the function index, the second axis the one along
    which the function is defined.  So ``data[0, :]`` is the first
    functional curve.
ncomp : int, optional
    Number of components to use.  If None, returns the as many as the
    smaller of the number of rows or columns in data.
alpha : list of floats between 0 and 1, optional
    Extra quantile values to compute. Default is None
threshold : float between 0 and 1, optional
    Percentile threshold value for outliers detection. High value means
    a lower sensitivity to outliers. Default is `0.95`.
bw : array_like or str, optional
    If an array, it is a fixed user-specified bandwidth. If `None`, set to
    `normal_reference`. If a string, should be one of:

        - normal_reference: normal reference rule of thumb (default)
        - cv_ml: cross validation maximum likelihood
        - cv_ls: cross validation least squares

xdata : ndarray, optional
    The independent variable for the data. If not given, it is assumed to
    be an array of integers 0..N-1 with N the length of the vectors in
    `data`.
labels : sequence of scalar or str, optional
    The labels or identifiers of the curves in `data`. If not given,
    outliers are labeled in the plot with array indices.
ax : AxesSubplot, optional
    If given, this subplot is used to plot in instead of a new figure being
    created.
use_brute : bool
    Use the brute force optimizer instead of the default differential
    evolution to find the curves. Default is False.
seed : {None, int, np.random.RandomState}
    Seed value to pass to scipy.optimize.differential_evolution. Can be an
    integer or RandomState instance. If None, then the default RandomState
    provided by np.random is used.

Returns
-------
fig : Figure
    If `ax` is None, the created figure.  Otherwise the figure to which
    `ax` is connected.
hdr_res : HdrResults instance
    An `HdrResults` instance with the following attributes:

     - 'median', array. Median curve.
     - 'hdr_50', array. 50% quantile band. [sup, inf] curves
     - 'hdr_90', list of array. 90% quantile band. [sup, inf]
        curves.
     - 'extra_quantiles', list of array. Extra quantile band.
        [sup, inf] curves.
     - 'outliers', ndarray. Outlier curves.

See Also
--------
banddepth, rainbowplot, fboxplot

Notes
-----
The median curve is the curve with the highest probability on the reduced
space of a Principal Component Analysis (PCA).

Outliers are defined as curves that fall outside the band corresponding
to the quantile given by `threshold`.

The non-outlying region is defined as the band made up of all the
non-outlying curves.

Behind the scene, the dataset is represented as a matrix. Each line
corresponding to a 1D curve. This matrix is then decomposed using Principal
Components Analysis (PCA). This allows to represent the data using a finite
number of modes, or components. This compression process allows to turn the
functional representation into a scalar representation of the matrix. In
other words, you can visualize each curve from its components. Each curve
is thus a point in this reduced space. With 2 components, this is called a
bivariate plot (2D plot).

In this plot, if some points are adjacent (similar components), it means
that back in the original space, the curves are similar. Then, finding the
median curve means finding the higher density region (HDR) in the reduced
space. Moreover, the more you get away from this HDR, the more the curve is
unlikely to be similar to the other curves.

Using a kernel smoothing technique, the probability density function (PDF)
of the multivariate space can be recovered. From this PDF, it is possible
to compute the density probability linked to the cluster of points and plot
its contours.

Finally, using these contours, the different quantiles can be extracted
along with the median curve and the outliers.

Steps to produce the HDR boxplot include:

1. Compute a multivariate kernel density estimation
2. Compute contour lines for quantiles 90%, 50% and `alpha` %
3. Plot the bivariate plot
4. Compute median curve along with quantiles and outliers curves.

References
----------
[1] R.J. Hyndman and H.L. Shang, "Rainbow Plots, Bagplots, and Boxplots for
    Functional Data", vol. 19, pp. 29-45, 2010.

Examples
--------
Load the El Nino dataset.  Consists of 60 years worth of Pacific Ocean sea
surface temperature data.

>>> import matplotlib.pyplot as plt
>>> import statsmodels.api as sm
>>> data = sm.datasets.elnino.load()

Create a functional boxplot.  We see that the years 1982-83 and 1997-98 are
outliers; these are the years where El Nino (a climate pattern
characterized by warming up of the sea surface and higher air pressures)
occurred with unusual intensity.

>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> res = sm.graphics.hdrboxplot(data.raw_data[:, 1:],
...                              labels=data.raw_data[:, 0].astype(int),
...                              ax=ax)

>>> ax.set_xlabel("Month of the year")
>>> ax.set_ylabel("Sea surface temperature (C)")
>>> ax.set_xticks(np.arange(13, step=3) - 1)
>>> ax.set_xticklabels(["", "Mar", "Jun", "Sep", "Dec"])
>>> ax.set_xlim([-0.2, 11.2])

>>> plt.show()

.. plot:: plots/graphics_functional_hdrboxplot.py
Nindexr   )ncompc)bwvar_typer   axisg?      ?T)reversed   linear)interpolationmidpointmethodc                 (   > TR                  U 5      * $ r   r=   r>   rB   s    r   <lambda>hdrboxplot.<locals>.<lambda>X  s    KOOA4F2Fr      )rG   rI   rJ   c                 (   > TR                  U 5      * $ r   rc   rd   s    r   re   rf   [  s    ;??1#5!5r   )rK   rL   c                   > TTR                  U S   5         n TTR                  U S   5         nX4/n [        5       n[        [	        T
5      [
        R                  " U TT	TX!45      5      nUR                  [        U5      nUR                  5         UR                  5         [        [        U6 5      nU$ ! [         a    Sn Nf = f)a  
Find extreme curves for a quantile band.

From the `band` of quantiles, the associated PDF extrema values
are computed. If `min_alpha` is not provided (single quantile value),
`max_pdf` is set to `1E6` in order not to constrain the problem on high
values.

An optimization is performed per component in order to find the min and
max curves. This is done by comparing the PDF value of a given curve
with the band PDF.

Parameters
----------
band : array_like
    alpha values ``(max_alpha, min_alpha)`` ex: ``[0.9, 0.5]``
use_brute : bool
    Use the brute force optimizer instead of the default differential
    evolution to find the curves. Default is False.
seed : {None, int, np.random.RandomState}
    Seed value to pass to scipy.optimize.differential_evolution. Can
    be an integer or RandomState instance. If None, then the default
    RandomState provided by np.random is used.


Returns
-------
band_quantiles : list of 1-D array
    ``(max_quantile, min_quantile)`` (2, n_features)
r   r   r<   )rS   
IndexErrorr   ziprange	itertoolsrepeatmaprQ   	terminatecloselist)rA   rN   rJ   min_pdfmax_pdfpoolr8   band_quantilesalpharG   dimrB   r7   pvaluess           r   _band_quantiles#hdrboxplot.<locals>._band_quantilesd  s    > %++d1g./	ekk$q'23G !v5:y//s17151B  C D -6

c>23  	G	s   B5 5CC)rN   rJ   )r!   r"   r#   r$   r%   r&   g?)rU   rw   labelkMedian)rU   r|   grayg?z50% HDR)colorrw   r|   g333333?z90% HDRyz-.zExtra quantiles)rU   lsrw   r|   Outliersz--gffffff?)r   rw   r|   )r   r   )fcbest)loc)0r   create_mpl_axhasattrrS   nparangelenasarrayr5   r   r3   r   arrayminmaxTextendrr   setsortr=   flattenr   rl   
percentilerM   r	   r>   r   r
   whereappendr:   r   plotfill_between	enumeratestrget_legend_handles_labelsr   rk   	Rectangleget_facecolordictpoplegendvalueskeys)*r8   rT   rw   	thresholdrV   xdatalabelsaxrN   rJ   fig	n_samplesdata_rn_quantilespdf_rir!   r&   labels_outlierr%   rz   extra_alphar$   r>   r   r#   r"   hdr_resfill_betweensiioutlierr|   handlespltr   pby_labelrG   rx   rB   r7   ry   s*     `                                  @@@@@r   r   r      s   ^ !!"%GC~4!!ZZFYYs4y)F::dD}		$**Q-(ZZNIs
d
 C[[F "&+.a+@BK XXvzzqz)6::1:+=>?AAF }C%ic*+SZ 	JJtJe*KOOF#++-Ey "+.0.q ==U1X(</79.0 "+.0.q ==U1X(<(24.0
 }Y'(F/5qtMMNQ 	 5$T3 88EGEKK	,B$CCDQGL)56AQiN6L!H )2 0 0d $ @eQh #&!8 09 eK @
;!A$aSII&&q) J    V,Q/Fc3Z9HFcUiCF&,&,&,/>(0,8 G GGBHHeWy()++TVV4  )GGE6SG1M E Ev/1)E F D Dv/1D E ?q 
%3#778::)++$b0A 	 	C 8}$X.KB%"N2./GGE7t3eGD / 224OGV -C"Iy#9=I|MM&!Q)779!<  >qe	  J C()H
8}XYYIIhoofI=<U00 7n@s*   )V)V	/V
V$V,V3Vc                    [         R                  " U5      u  pUc  0 OUnUR                  S5      c
  SSKJn	  XS'   [
        R                  " U 5      n Uc#  [
        R                  " U R                  S   5      nUc  US;  a  [        S5      e[        XS9nO(UR                  U R                  S   :w  a  [        S	5      e[
        R                  " U5      SSS
2   n
X
S   SS24   nU R                  S   S-  nX
SU SS24   R                  SS9nX
SU SS24   R                  SS9n[
        R                  " X
SU SS24   SS9nXU-
  U-  -
  nXU-
  U-  -   n/ n/ n[!        U R                  S   5       Hq  n[
        R"                  " U USS24   U:  5      (       d%  [
        R"                  " U USS24   U:  5      (       a  UR%                  U5        M`  UR%                  U5        Ms     [
        R                  " U5      nU USS24   R                  SS9nU USS24   R                  SS9nUR'                  UUUUR                  SS5      S9  UR'                  XUUR                  SS5      S9  UR)                  XUR                  SS5      UR                  SS5      S9  UR                  S5      n[+        U5       H`  u  nnUb  [-        UU   5      OSnUR)                  XUSS24   U" [/        U5      [1        U5      S-
  -  5      UUR                  SS5      S9  Mb     UR                  SS5      (       a!  U H  nUR)                  XUSS24   SSS9  M     Ub  UR3                  5         XU
U4$ )a  
Plot functional boxplot.

A functional boxplot is the analog of a boxplot for functional data.
Functional data is any type of data that varies over a continuum, i.e.
curves, probability distributions, seasonal data, etc.

The data is first ordered, the order statistic used here is `banddepth`.
Plotted are then the median curve, the envelope of the 50% central region,
the maximum non-outlying envelope and the outlier curves.

Parameters
----------
data : sequence of ndarrays or 2-D ndarray
    The vectors of functions to create a functional boxplot from.  If a
    sequence of 1-D arrays, these should all be the same size.
    The first axis is the function index, the second axis the one along
    which the function is defined.  So ``data[0, :]`` is the first
    functional curve.
xdata : ndarray, optional
    The independent variable for the data.  If not given, it is assumed to
    be an array of integers 0..N-1 with N the length of the vectors in
    `data`.
labels : sequence of scalar or str, optional
    The labels or identifiers of the curves in `data`.  If given, outliers
    are labeled in the plot.
depth : ndarray, optional
    A 1-D array of band depths for `data`, or equivalent order statistic.
    If not given, it will be calculated through `banddepth`.
method : {'MBD', 'BD2'}, optional
    The method to use to calculate the band depth.  Default is 'MBD'.
wfactor : float, optional
    Factor by which the central 50% region is multiplied to find the outer
    region (analog of "whiskers" of a classical boxplot).
ax : AxesSubplot, optional
    If given, this subplot is used to plot in instead of a new figure being
    created.
plot_opts : dict, optional
    A dictionary with plotting options.  Any of the following can be
    provided, if not present in `plot_opts` the defaults will be used::

      - 'cmap_outliers', a Matplotlib LinearSegmentedColormap instance.
      - 'c_inner', valid MPL color. Color of the central 50% region
      - 'c_outer', valid MPL color. Color of the non-outlying region
      - 'c_median', valid MPL color. Color of the median.
      - 'lw_outliers', scalar.  Linewidth for drawing outlier curves.
      - 'lw_median', scalar.  Linewidth for drawing the median curve.
      - 'draw_nonout', bool.  If True, also draw non-outlying curves.

Returns
-------
fig : Figure
    If `ax` is None, the created figure.  Otherwise the figure to which
    `ax` is connected.
depth : ndarray
    A 1-D array containing the calculated band depths of the curves.
ix_depth : ndarray
    A 1-D array of indices needed to order curves (or `depth`) from most to
    least central curve.
ix_outliers : ndarray
    A 1-D array of indices of outlying curves in `data`.

See Also
--------
banddepth, rainbowplot

Notes
-----
The median curve is the curve with the highest band depth.

Outliers are defined as curves that fall outside the band created by
multiplying the central region by `wfactor`.  Note that the range over
which they fall outside this band does not matter, a single data point
outside the band is enough.  If the data is noisy, smoothing may therefore
be required.

The non-outlying region is defined as the band made up of all the
non-outlying curves.

References
----------
[1] Y. Sun and M.G. Genton, "Functional Boxplots", Journal of Computational
    and Graphical Statistics, vol. 20, pp. 1-19, 2011.
[2] R.J. Hyndman and H.L. Shang, "Rainbow Plots, Bagplots, and Boxplots for
    Functional Data", vol. 19, pp. 29-45, 2010.

Examples
--------
Load the El Nino dataset.  Consists of 60 years worth of Pacific Ocean sea
surface temperature data.

>>> import matplotlib.pyplot as plt
>>> import statsmodels.api as sm
>>> data = sm.datasets.elnino.load()

Create a functional boxplot.  We see that the years 1982-83 and 1997-98 are
outliers; these are the years where El Nino (a climate pattern
characterized by warming up of the sea surface and higher air pressures)
occurred with unusual intensity.

>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> res = sm.graphics.fboxplot(data.raw_data[:, 1:], wfactor=2.58,
...                            labels=data.raw_data[:, 0].astype(int),
...                            ax=ax)

>>> ax.set_xlabel("Month of the year")
>>> ax.set_ylabel("Sea surface temperature (C)")
>>> ax.set_xticks(np.arange(13, step=3) - 1)
>>> ax.set_xticklabels(["", "Mar", "Jun", "Sep", "Dec"])
>>> ax.set_xlim([-0.2, 11.2])

>>> plt.show()

.. plot:: plots/graphics_functional_fboxplot.py
Ncmap_outliersr   	rainbow_rr   MBDBD2%Unknown value for parameter `method`.r`   .Provided `depth` array is not of correct size.r2      rX   c_outer)      ?r   r   )r   c_inner)rZ   rZ   rZ   c_medianr}   	lw_median)r   lwlw_outliers)r   r|   r   draw_nonoutFk-rZ   r   )r   r   getmatplotlib.cmr   r   r   r   r5   
ValueErrorr   sizeargsortr   r   r!   rl   anyr   r   r   r   r   floatr   r   )r8   r   r   depthra   wfactorr   	plot_optsr   r   ix_depthmedian_curveix_IQRlowerupperinner_medianlower_fenceupper_fenceix_outliers	ix_nonoutr   lower_nonoutupper_nonoutcmapixr|   s                             r   r   r     s   l !!"%GC'YI}}_%-+%./"::dD}		$**Q-( }'DEE$.::A&MNN zz% 2&HQ'LZZ]aF!F#Q&'+++3E!F#Q&'+++3E 99T1V"4a"78qAL"6'!AAK,"6'!AAK KIDJJqM"FF4A;,--tBE{[011r"R  # **[)K 	1%))q)1L	1%))q)1LOOE<#--	3EF  H OOE%#--	?C  E GGEy}}Z'E}}[!,  . ==)DK(B#)#5F2J4
BE{59K(8(:;<E==2 	 	4 ) }}]E**BGGEA;G5  
		x,,r   c           
      J   [         R                  " U5      u  pdUc  SSKJn  Un[        R
                  " U 5      n Uc#  [        R                  " U R                  S   5      nUc  US;  a  [        S5      e[        XS9nO(UR                  U R                  S   :w  a  [        S5      e[        R                  " U5      SSS	2   nU R                  S   n	[        U	5       H'  n
UR                  XX   SS24   U" XS
-
  -  5      S9  M)     XS   SS24   nUR                  XSSS9  U$ )a  
Create a rainbow plot for a set of curves.

A rainbow plot contains line plots of all curves in the dataset, colored in
order of functional depth.  The median curve is shown in black.

Parameters
----------
data : sequence of ndarrays or 2-D ndarray
    The vectors of functions to create a functional boxplot from.  If a
    sequence of 1-D arrays, these should all be the same size.
    The first axis is the function index, the second axis the one along
    which the function is defined.  So ``data[0, :]`` is the first
    functional curve.
xdata : ndarray, optional
    The independent variable for the data.  If not given, it is assumed to
    be an array of integers 0..N-1 with N the length of the vectors in
    `data`.
depth : ndarray, optional
    A 1-D array of band depths for `data`, or equivalent order statistic.
    If not given, it will be calculated through `banddepth`.
method : {'MBD', 'BD2'}, optional
    The method to use to calculate the band depth.  Default is 'MBD'.
ax : AxesSubplot, optional
    If given, this subplot is used to plot in instead of a new figure being
    created.
cmap : Matplotlib LinearSegmentedColormap instance, optional
    The colormap used to color curves with.  Default is a rainbow colormap,
    with red used for the most central and purple for the least central
    curves.

Returns
-------
Figure
    If `ax` is None, the created figure.  Otherwise the figure to which
    `ax` is connected.

See Also
--------
banddepth, fboxplot

References
----------
[1] R.J. Hyndman and H.L. Shang, "Rainbow Plots, Bagplots, and Boxplots for
    Functional Data", vol. 19, pp. 29-25, 2010.

Examples
--------
Load the El Nino dataset.  Consists of 60 years worth of Pacific Ocean sea
surface temperature data.

>>> import matplotlib.pyplot as plt
>>> import statsmodels.api as sm
>>> data = sm.datasets.elnino.load()

Create a rainbow plot:

>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> res = sm.graphics.rainbowplot(data.raw_data[:, 1:], ax=ax)

>>> ax.set_xlabel("Month of the year")
>>> ax.set_ylabel("Sea surface temperature (C)")
>>> ax.set_xticks(np.arange(13, step=3) - 1)
>>> ax.set_xticklabels(["", "Mar", "Jun", "Sep", "Dec"])
>>> ax.set_xlim([-0.2, 11.2])
>>> plt.show()

.. plot:: plots/graphics_functional_rainbowplot.py
Nr   r   r   r   r   r`   r   r2   g      ?)rU   r   r   r   )r   r   r   r   r   r   r   r5   r   r   r   r   rl   r   )r8   r   r   ra   r   r   r   r   r   
num_curvesr   r   s               r   r   r     s   P !!"%GC|+::dD}		$**Q-( }'DEE$.::A&MNNzz% 2&H AJJ
HL!O,R?5K0LM   Q'LGGE!G,Jr   c                    ^^^ U R                   u  mm[        R                  " U SS9n[        R                  " USS9S-   mUU4S jnUUU4S jnUS:X  a	  U" 5       nU$ US:X  a	  U" 5       nU$ [        S5      e)	aM  
Calculate the band depth for a set of functional curves.

Band depth is an order statistic for functional data (see `fboxplot`), with
a higher band depth indicating larger "centrality".  In analog to scalar
data, the functional curve with highest band depth is called the median
curve, and the band made up from the first N/2 of N curves is the 50%
central region.

Parameters
----------
data : ndarray
    The vectors of functions to create a functional boxplot from.
    The first axis is the function index, the second axis the one along
    which the function is defined.  So ``data[0, :]`` is the first
    functional curve.
method : {'MBD', 'BD2'}, optional
    Whether to use the original band depth (with J=2) of [1]_ or the
    modified band depth.  See Notes for details.

Returns
-------
ndarray
    Depth values for functional curves.

Notes
-----
Functional band depth as an order statistic for functional data was
proposed in [1]_ and applied to functional boxplots and bagplots in [2]_.

The method 'BD2' checks for each curve whether it lies completely inside
bands constructed from two curves.  All permutations of two curves in the
set of curves are used, and the band depth is normalized to one.  Due to
the complete curve having to fall within the band, this method yields a lot
of ties.

The method 'MBD' is similar to 'BD2', but checks the fraction of the curve
falling within the bands.  It therefore generates very few ties.

The algorithm uses the efficient implementation proposed in [3]_.

References
----------
.. [1] S. Lopez-Pintado and J. Romo, "On the Concept of Depth for
       Functional Data", Journal of the American Statistical Association,
       vol.  104, pp. 718-734, 2009.
.. [2] Y. Sun and M.G. Genton, "Functional Boxplots", Journal of
       Computational and Graphical Statistics, vol. 20, pp. 1-19, 2011.
.. [3] Y. Sun, M. G. Gentonb and D. W. Nychkac, "Exact fast computation
       of band depth for large functional datasets: How quickly can one
       million curves be ranked?", Journal for the Rapid Dissemination
       of Statistics Research, vol. 1, pp. 68-74, 2012.
r   rX   r   c                     > [         R                  " TSS9S-
  n T[         R                  " TSS9-
  nX-  T-   S-
  [        TS5      -  $ Nr   rX   r   )r   r   r   r   )downupnrmats     r   _fbd2banddepth.<locals>._fbd2C  sI    vvd#a'1%%	A!T!QZ//r   c                  r   > TS-
  n TT-
  n[         R                  " X-  SS9T-  T-   S-
  [        TS5      -  $ r   )r   sumr   )r   r   r   r   r   s     r   _fmbdbanddepth.<locals>._fmbdI  sB    axX	*Q.!3a741:EEr   r   r   z+Unknown input value for parameter `method`.)r5   r   r   r   )	r8   ra   rvr   r   r   r   r   r   s	         @@@r   r   r     s    l ::DAq	Dq	!B::bq!A%D0F
  L 
5 L FGGr   )	r   Ngffffff?NNNNFN)NNNr   g      ?NN)NNr   NN)r   )!r/   statsmodels.compat.numpyr   numpyr   scipy.specialr   statsmodels.graphics.utilsr   statsmodels.multivariate.pcar   (statsmodels.nonparametric.kernel_densityr   scipy.optimizer   r	   r
   rM   ImportErrorrm   multiprocessingr    r   __all__r   r:   rD   rQ   r   r   r   r   r*   r   r   <module>r      s    % .   2 , DBBM    
@ (<D+\ >BGK}@
 @E-1@-F @DgTMu  *Ms   A4 4BB