
    >h<                         S r SSKrSSKrSSKJrJr   " S S5      rS rSS jr	SS jr
SS	 jrS
 rSS jrSS jrSS jrS rS rSS jrg)zM
Created on Thu Feb 11 09:19:30 2021

Author: Josef Perktold
License: BSD-3

    N)interpolatestatsc                   "    \ rS rSrSrSS jrSrg)_Grid   a.  Create Grid values and indices, grid in [0, 1]^d

This class creates a regular grid in a d dimensional hyper cube.

Intended for internal use, implementation might change without warning.


Parameters
----------
k_grid : tuple or array_like
    number of elements for axes, this defines k_grid - 1 equal sized
    intervals of [0, 1] for each axis.
eps : float
    If eps is not zero, then x values will be clipped to [eps, 1 - eps],
    i.e. to the interior of the unit interval or hyper cube.


Attributes
----------
k_grid : list of number of grid points
x_marginal: list of 1-dimensional marginal values
idx_flat: integer array with indices
x_flat: flattened grid values,
    rows are grid points, columns represent variables or axis.
    ``x_flat`` is currently also 2-dim in the univariate 1-dim grid case.

c           	      &   Xl         U Vs/ s H  n[        R                  " U5      US-
  -  PM!     nn[        R                  " [        R                  " [        R                  " [        R
                  " U5      5      U5      5      R                  [        5      nXUR                  S5      -  nUS:w  aD  U Vs/ s H  n[        R                  " XrSU-
  5      PM     nn[        R                  " XbSU-
  5      nX@l
        XPl        X`l        g s  snf s  snf )N   r   )k_gridnparangecolumn_stackunravel_indexprodastypefloatmaxclip
x_marginalidx_flatx_flat)selfr
   epskir   r   r   xis           rC:\Users\julio\OneDrive\Documentos\Trabajo\Ideas Frescas\venv\Lib\site-packages\statsmodels/distributions/tools.py__init___Grid.__init__,   s    9?@2biimrAv.
@??  2776?!;VD&- 	 LLO+!8>HIj"''"1s73jJIWWV!c'2F$  A Js   &D	6$D)r   r
   r   r   Nr   )__name__
__module____qualname____firstlineno____doc__r   __static_attributes__     r   r   r      s    8r&   r   c                     [         R                  " U 5      R                  5       nUR                  n[	        U5       H  nUR                  US9nM     U$ )zCumulative probabilities from cell provabilites on a grid

Parameters
----------
probs : array_like
    Rectangular grid of cell probabilities.

Returns
-------
cdf : ndarray
    Grid of cumulative probabilities with same shape as probs.
axis)r   asarraycopyndimrangecumsum)probscdfkis       r   prob2cdf_gridr3   >   sI     **U

 
 
"CA1Xjjaj   Jr&   c                     Uc  [         R                  n[         R                  " U 5      R                  5       nUR                  n[        U5       H  n[         R                  " X!US9nM     U$ )zCell probabilities from cumulative probabilities on a grid.

Parameters
----------
cdf : array_like
    Grid of cumulative probabilities with same shape as probs.

Returns
-------
probs : ndarray
    Rectangular grid of cell probabilities.

)prependr)   )r   _NoValuer*   r+   r,   r-   diff)r0   r5   probr1   r2   s        r   cdf2prob_gridr9   S   sV     ++::c?!D		A1Xwwt15  Kr&   c                 F   U R                   nUS:X  a  U R                  5       n[        U5       He  n[        SSS5      /U-  n[        SSS5      /U-  n[        SSS5      Xe'   [        SSS5      Xu'   [	        U5      n[	        U5      nXF   XG   -   S-  nMg     O;US:X  a5  SSKJn  UR                  U S	U-  [        R                  " S/U-  5      -  S
S9nUbK  [        R                  " S5      n	[        U5       H!  nU	S   [        R                  " X   5      -  n	M#     WU	-  nW$ )a  Compute average for each cell in grid using endpoints

Parameters
----------
values : array_like
    Values on a grid that will average over corner points of each cell.
coords : None or list of array_like
    Grid coordinates for each axis use to compute volumne of cell.
    If None, then averaged values are not rescaled.
_method : {"slicing", "convolve"}
    Grid averaging is implemented using numpy "slicing" or using
    scipy.signal "convolve".

Returns
-------
Grid with averaged cell values.
slicingNr	      convolver   )signalg      ?valid)mode.N)r,   r+   r-   slicetuplescipyr?   r>   r   onesarrayr7   )
valuescoords_methodk_dimpdsl1sl2r?   dxs
             r   average_gridrQ   k   s)   $ KKE)KKMuAtT*+e3CtT*+e3C4T*CF1dD)CF*C*C!&A%A  
J	 OOFCJ!u1E$E!(  * XXa[uAI!33B  FHr&   c           	         [         R                  " U 5      nSn[        U5       GH(  nUR                  5       n[        UR                  5       HK  n[        [        UR                  5       Vs/ s H  oU:X  a  M
  UPM     sn5      n	XcR                  U	SS9-  nMM     UnX3R                  5       -  n/ n
[        UR                  5       Hn  n[        [        UR                  5       Vs/ s H  oU:X  a  M
  UPM     sn5      n	UR                  U	SS9nU
R                  [         R                  " U5      5        Mp     [        U
5      U:  d  GM'  Sn  O   U(       d  SSK
Jn  [        R                  " SU5        U$ s  snf s  snf )a<  nearest matrix with uniform margins

Parameters
----------
mat : array_like, 2-D
    Matrix that will be converted to have uniform margins.
    Currently, `mat` has to be two dimensional.
maxiter : in
    Maximum number of iterations.
tol : float
    Tolerance for convergence, defined for difference between largest and
    smallest margin in each dimension.

Returns
-------
ndarray, nearest matrix with uniform margins.

Notes
-----
This function is intended for internal use and will be generalized in
future. API will change.

changed in 0.14 to support k_dim > 2.


FT)r)   keepdimsr   )ConvergenceWarningz,Iterations did not converge, maxiter reached)r   r*   r-   r+   r,   rD   sumappendptpr   statsmodels.tools.sm_exceptionsrT   warningswarn)matmaxitertolpc	converged_pc0axr2   axsmptpsmargrT   s                r   nearest_matrix_marginsrf      s4   6 
CBI7^ggi.BE"''NBNqr'NBCC66sT622C ! 
ffh .BE"''NBNqr'NBCC66sU63DLL& ! u:I! $ FD(	*I' C Cs   ,	E79E7&	E<3E<c                     U R                   u  p[        R                  " X45      n[        R                  " U SS9n[        R                  " SUS-   5      SS2S4   X4[        R                  " U5      4'   U$ )zrankdata without ties for 2-d array

This is a simplified version for ranking data if there are no ties.
Works vectorized across columns.

See Also
--------
scipy.stats.rankdata

r   r(   r	   N)shaper   rF   argsortr   )xnobsk_varsrankssidxs        r   _rankdata_no_tiesro      sb     77LDGGTN#E::aa D%'YYq$(%;AtG%DE		&!
!"Lr&   c                     [         R                  " U 5      n U R                  S   nUS-   n[        U/U-  SS9nU(       a  [	        U 5      U R                  S   S-   -  n [         R
                  " XR                  S9u  pgU$ )a  count of observations in bins (histogram)

currently only for bivariate data

Parameters
----------
data : array_like
    Bivariate data with observations in rows and two columns. Binning is
    in unit rectangle [0, 1]^2. If use_rank is False, then data should be
    in unit interval.
k_bins : int
    Number of bins along each dimension in the histogram
use_ranks : bool
    If use_rank is True, then data will be converted to ranks without
    tie handling.

Returns
-------
bin counts : ndarray
    Frequencies are the number of observations in a given bin.
    Bin counts are a 2-dim array with k_bins rows and k_bins columns.

Notes
-----
This function is intended for internal use and will be generalized in
future. API will change.
r<   r	   r   r   )bins)r   r*   rh   r   ro   histogramddr   )datak_bins	use_ranksrK   r1   g2freqrr`   s           r   frequencies_fromdatary      st    8 ::dDJJrNE
A	sU{	"B &$**Q-!*;<
 ~~d7HELr&   c                    U R                   nUS-   n[        U/U-  5      nU(       aw  [        U/U-  SU-  S9nU R                  UR                  5      R
                  " U6 nUSXT-  -  -  n[        U5      n	U(       a  [        U	SSS9n
U
$ XR                  5       -  n
 U
$ [        U/U-  SS9nU R                  UR                  5      R
                  " U6 n[        USS	9n
XR                  5       -  n
U
$ )
a  Histogram probabilities as approximation to a copula density.

Parameters
----------
copula : instance
    Instance of a copula class. Only the ``pdf`` method is used.
k_bins : int
    Number of bins along each dimension in the approximating histogram.
force_uniform : bool
    If true, then the pdf grid will be adjusted to have uniform margins
    using `nearest_matrix_margin`.
    If false, then no adjustment is done and the margins may not be exactly
    uniform.
use_pdf : bool
    If false, then the grid cell probabilities will be computed from the
    copula cdf.
    If true, then the density, ``pdf``, is used and cell probabilities
    are approximated by averaging the pdf of the cell corners. This is
    only useful if the cdf is not available.

Returns
-------
bin probabilites : ndarray
    Probability that random variable falls in given bin. This corresponds
    to a discrete distribution, and is not scaled to bin size to form a
    piecewise uniform, histogram density.
    Bin probabilities are a k-dim array with k_bins segments in each
    dimensionrows.

Notes
-----
This function is intended for internal use and will be generalized in
future. API will change.
r	   g?rq   d   :0yE>)r\   r]   gư>N)r5   )rK   rD   r   pdfr   reshaperQ   rf   rU   r0   r9   )copularu   force_uniformuse_pdfrK   r1   ksgpdfgagpdf_gridcdfgs               r   approx_copula_pdfr     s    F LLE
A	sU{	B1#+3<0zz!((#++R0AH$-b#4HH O FFH}H O 1#+4(zz!((#++R0 t4 	LLN"Or&   c                    UR                   S   n[        R                  " U 5      n[        R                  " U5      R	                  [
        5      nUS-
  nUR                  5       S:X  ar  [        R                  " 5          [        R                  " S[        5        [        R                  R                  XVUS   5      nSSS5        UW-  R                  S5      nU$ UR                  5       S:X  a*  [        R                   " USS2S4   SS	/5      n	U	" U 5      nU$ UR                  5       S
:X  a  [        R                  " 5          [        R                  " S[        5        [        R"                  R%                  US   US	-   Xe-
  S	-   5      US	-   -  nSSS5        UW-  R                  S5      nU$ ['        S5      e! , (       d  f       GN= f! , (       d  f       NA= f)a  Evaluate 1-dimensional bernstein polynomial given grid of values.

experimental, comparing methods

Parameters
----------
x : array_like
    Values at which to evaluate the Bernstein polynomial.
fvals : ndarray
    Grid values of coefficients for Bernstein polynomial basis in the
    weighted sum.
method: "binom", "beta" or "bpoly"
    Method to construct Bernstein polynomial basis, used for comparison
    of parameterizations.

    - "binom" uses pmf of Binomial distribution
    - "beta" uses pdf of Beta distribution
    - "bpoly" uses one interval in scipy.interpolate.BPoly

Returns
-------
Bernstein polynomial at evaluation points, weighted sum of Bernstein
polynomial basis.
r<   g      ?binomignorerB   Nbpolyg        r	   betazmethod not recogized)rh   r   r*   r   r   r   lowerrY   catch_warningssimplefilterRuntimeWarningr   r   pmfrU   r   BPolyr   r}   
ValueError)
rj   fvalsmethodk_termsxxr1   n	poly_base	bp_valuesbpbs
             r   _eval_bernstein_1dr   M  s   2 kk"oG	AB
		'!!%(A"A||~ $$&!!(N;bm<I ' Y&++B/	  
7	"agQ8F	  
6	!$$&!!(N;

r)}a!eQUQYG1q5QI ' Y&++B/	  /00 '& '&s   =?F8AG
8
G

Gc           	         UR                   nUR                  nUS:w  a  [        S5      e[        R                  " U 5      nUR                   S   S:w  a  [        S5      eUR
                  u  pVUS   S-
  US   S-
  p[        R                  " US   5      R                  [        5      n	[        R                  " US   5      R                  [        5      n
[        R                  R                  U	SSS2S4   XuSS2SS4   5      [        R                  R                  U
SSSS24   XSS2SS4   5      -  nX-  R                  S5      R                  S5      nU$ )a  Evaluate 2-dimensional bernstein polynomial given grid of values

experimental

Parameters
----------
x : array_like
    Values at which to evaluate the Bernstein polynomial.
fvals : ndarray
    Grid values of coefficients for Bernstein polynomial basis in the
    weighted sum.

Returns
-------
Bernstein polynomial at evaluation points, weighted sum of Bernstein
polynomial basis.
r=   z `fval` needs to be 2-dimensionalr	   z*x needs to be bivariate and have 2 columnsr   Nr<   )rh   r,   r   r   
atleast_2dTr   r   r   r   r   r   rU   )rj   r   r   rK   r   x1x2n1n2k1k2r   r   s                r   _eval_bernstein_2dr     s-   $ kkGJJEz;<<	q	B	xx{aEFFTTFBQZ!^WQZ!^	71:		%	%e	,B	71:		%	%e	,B D!TM!2B1dD=8IJD$M!2B1dD=8IJKI"''+//3Ir&   c                 X   UR                   nUR                  n[        R                  " U 5      n[        R                  " U R                   S   5      n[        U5       H~  n[        R                  " X&   5      R                  [        5      n[        US-   5       H  nUS   nM
     X&   S-
  n	USS2U4   n
US   [        R                  R                  XyU
5      -   nM     [        R                  " U5      nUR                  S   U-  n[        U5       H  nUR                  S5      nM     U$ )a  Evaluate d-dimensional bernstein polynomial given grid of valuesv

experimental

Parameters
----------
x : array_like
    Values at which to evaluate the Bernstein polynomial.
fvals : ndarray
    Grid values of coefficients for Bernstein polynomial basis in the
    weighted sum.

Returns
-------
Bernstein polynomial at evaluation points, weighted sum of Bernstein
polynomial basis.
r   r	   rB   N)N.)rh   r,   r   r   zerosr-   r   r   r   r   r   _logpmfexpr   rU   )rj   r   r   rK   r   r   r2   r   r`   nir   r   s               r   _eval_bernstein_ddr     s    $ kkGJJE	q	B $I5\YYwz"))%0qsAIB Z!^1Xi(5;;+>+>rr+JJ	  y!I	"Y.I5\MM!$	  r&   c                    [         R                  " U 5      nUR                  S   nU(       a  [        U5      U-  nUS:X  aU  [	        U5       Vs/ s H&  oSX5   :*  R                  S5      R                  5       PM(     nn[         R                  " U5      nXc4$ UR                  S5      (       a  [         R                  " USS2S4   5      nX7   nUSS2SS24   n	[	        U5       Vs/ s H,  oYSU X   :*  R                  S5      R                  5       S-   PM.     n
n[         R                  " UR                  S   5      nXU'   Xc4$ [        S5      es  snf s  snf )aZ  
Multivariate empiricial distribution function, empirical copula


Notes
-----
Method "seq" is faster than method "brute", but supports mainly bivariate
case. Speed advantage of "seq" is increasing in number of observations
and decreasing in number of variables.
(see Segers ...)

Warning: This does not handle ties. The ecdf is based on univariate ranks
without ties. The assignment of ranks to ties depends on the sorting
algorithm and the initial ordering of the data.

When the original data is used instead of ranks, then method "brute"
computes the correct ecdf counts even in the case of ties.

r   bruter	   seqNzmethod not available)r   r*   rh   ro   r-   allrU   
startswithri   emptyr   )rt   r   rv   rj   r   r2   count	sort_idx0x_s0r   count_smallers              r   _ecdf_mvr     s8   ( 	

4A	
Aa 1$5:1X>X9//!$))+X>

5! 8O 
		5	!	!JJqAw'	|!QR%[EJ1XNXRa&BE/..q1557!;XN$(i 8O /00 ? Os   -E%3Er   )Nr;   )r{   r|   )T)
   TF)r   )r   T)r#   rY   numpyr   rE   r   r   r   r3   r9   rQ   rf   ro   ry   r   r   r   r   r   r%   r&   r   <module>r      s^      $, ,^*0-`4n$'T:~0f$N)X%r&   