a
    BCCfOI                     @   s   d dl Zd dlmZmZ d dlmZmZmZ d dl	m
Z
 eZeZdd Zdd Zd	d
 ZdddZdddZdddZd ddZd!ddZdd ZdS )"    N)fftifft)gammaincinvndtrndtri)primes_from_2_toc                 C   sd   t  }ttt| d D ],}| | s<|| | | } q | dkr qJq| dkr\||  t|S )zLReturn a sorted list of the unique prime factors of a positive integer.
       )setr   intnpsqrtaddsorted)nfactorsp r   N/var/www/html/django/DPS/env/lib/python3.9/site-packages/scipy/stats/_qmvnt.py_factorize_int.   s    


r   c                 C   sp   | d }t |}t|}d}d}||k rl|||  }tt|t|t| }|dkrb|d7 }d}q |d7 }q |S )zCompute a primitive root of the prime number `p`.

    Used in the CBC lattice construction.

    References
    ----------
    .. [1] https://en.wikipedia.org/wiki/Primitive_root_modulo_n
    r      r   )r   lenpowr
   )r   pmr   r   rkdrdr   r   r   _primitive_root>   s    

r   c                 C   sj  t |d }|d }t| }tddt| d  g}d}d}td| d }|d d }t|}	tj|td}
t|d D ]}|	|
|  | |
|d < qt||
 |
}
|
| }|| | d }t	|}td| D ]}t|d	|d  d	d	d ||d | d	d	d g}|||d  ||d  |   }t
|t	| j }|
| ||< q|| }||fS )
a  Compute a QMC lattice generator using a Fast CBC construction.

    Parameters
    ----------
    n_dim : int > 0
        The number of dimensions for the lattice.
    n_qmc_samples : int > 0
        The desired number of QMC samples. This will be rounded down to the
        nearest prime to enable the CBC construction.

    Returns
    -------
    q : float array : shape=(n_dim,)
        The lattice generator vector. All values are in the open interval
        `(0, 1)`.
    actual_n_qmc_samples : int
        The prime number of QMC samples that must be used with this lattice,
        no more, no less.

    References
    ----------
    .. [1] Nuyens, D. and Cools, R. "Fast Component-by-Component Construction,
           a Reprise for Different Kernels", In H. Niederreiter and D. Talay,
           editors, Monte-Carlo and Quasi-Monte Carlo Methods 2004,
           Springer-Verlag, 2006, 371-385.
    r         ?g?r   r   ZdtypegUUUUUU?N)r   r   onesZhstackaranger   r
   rangeminimumr   r   realZargmin)Zn_dimn_qmc_samplesZprimesZbtZgmqwzmgpermjZpncZfcs	reorderedr   r   r   _cbc_latticeY   s4    
 r1   MbP?'  c                 K   s   t |}d}	|dkr*t|t| }
d}nt||d }d}
d}d}||kr|	|k rttd| }| ||||fd|i|\}}}|	|7 }	dd|| d   }|
|||
  7 }
t|| }qD|
||	fS )	a  Automatically rerun the integration to get the required error bound.

    Parameters
    ----------
    func : callable
        Either :func:`_qmvn` or :func:`_qmvt`.
    covar, low, high : array
        As specified in :func:`_qmvn` and :func:`_qmvt`.
    rng : Generator, optional
        default_rng(), yada, yada
    error : float > 0
        The desired error bound.
    limit : int > 0:
        The rough limit of the number of integration points to consider. The
        integration will stop looping once this limit has been *exceeded*.
    **kwds :
        Other keyword arguments to pass to `func`. When using :func:`_qmvt`, be
        sure to include ``nu=`` as one of these.

    Returns
    -------
    prob : float
        The estimated probability mass within the bounds.
    est_error : float
        3 times the standard error of the batch estimates.
    n_samples : int
        The number of integration points actually used.
    r   r   gV瞯<i          r   r   rng)r   phiminroundr   r   )funccovarlowhighr5   errorlimitkwdsr   	n_samplesprob	est_errormieipiniwtr   r   r   _qauto   s"     rH   cbc
   c                 C   s  t |||\}}}	|jd }
|d }t|d | }t|	d | }|}|| }d}d}t|
d t| | d\}}t|
d |f}t|d }t|D ]*}t	||}t	||}|
 }td|
D ]}||d  | |  }||t8 }td| d }t|||  ||d ddf< ||d|f |d|ddf  }|||f }t|| | | }t|	| | | }|| }|| }q| | |d  }||7 }|d | |d  ||  }qdt| }|| }|||fS )a  Multivariate normal integration over box bounds.

    Parameters
    ----------
    m : int > n_batches
        The number of points to sample. This number will be divided into
        `n_batches` batches that apply random offsets of the sampling lattice
        for each batch in order to estimate the error.
    covar : (n, n) float array
        Possibly singular, positive semidefinite symmetric covariance matrix.
    low, high : (n,) float array
        The low and high integration bounds.
    rng : Generator, optional
        default_rng(), yada, yada
    lattice : 'cbc' or callable
        The type of lattice rule to use to construct the integration points.
    n_batches : int > 0, optional
        The number of QMC batches to apply.

    Returns
    -------
    prob : float
        The estimated probability mass within the bounds.
    est_error : float
        3 times the standard error of the batch estimates.
    r   r   r   r4   r   r   N   )_permuted_choleskyshaper6   r1   maxr   zerosr"   r#   fullcopyrandomastyper
   absphinvmeanr   )r*   r:   r;   r<   r5   lattice	n_batchescholohir   ctr.   r   cidcirA   	error_varr'   r&   y	i_samplesr-   dcpvir)   xr/   rB   r@   r   r   r   _qmvn   sB    
 $
rg   Fc                    sz   t | ||\  jd d  d }td | }td | }||  fdd}|fS )a~  Transform the multivariate normal integration into a QMC integrand over
    a unit hypercube.

    The dimensionality of the resulting hypercube integration domain is one
    less than the dimensionality of the original integrand. Note that this
    transformation subsumes the integration bounds in order to account for
    infinite bounds. The QMC integration one does with the returned integrand
    should be on the unit hypercube.

    Parameters
    ----------
    covar : (n, n) float array
        Possibly singular, positive semidefinite symmetric covariance matrix.
    low, high : (n,) float array
        The low and high integration bounds.
    use_tent : bool, optional
        If True, then use tent periodization. Only helpful for lattice rules.

    Returns
    -------
    integrand : Callable[[NDArray], NDArray]
        The QMC-integrable integrand. It takes an
        ``(n_qmc_samples, ndim_integrand)`` array of QMC samples in the unit
        hypercube and returns the ``(n_qmc_samples,)`` evaluations of at these
        QMC points.
    ndim_integrand : int
        The dimensionality of the integrand. Equal to ``n-1``.
    r   r   rK   c                     s  t | }t t| d }|ks&J t||f}t|}t|}| }tdD ]}rtd| |d   d }n| |d  }t|||  ||d d d f<  |d |f |d |d d f  }	 ||f }
t	| |	 |
 }t	| |	 |
 }|| }|| }q^|S )Nr   r   r   )
r   r   Z
atleast_1drP   rQ   rR   r#   rU   rV   r6   )ZzsZndim_qmcr&   ra   r.   rc   rd   re   rf   r/   r]   r   rZ   r^   r_   r\   r[   r   Zndim_integranduse_tentr   r   	integrand8  s&     $
z%_mvn_qmc_integrand.<locals>.integrand)rM   rN   r6   )r:   r;   r<   ri   r]   r.   r   rj   r   rh   r   _mvn_qmc_integrand  s    
rk   c           $   
   C   s  t dt|}tj|tjd}tj|tjd}t||| || \}	}
}|	jd }d}d}t|t | | d\}}t|d }t	|D ]}t
|}t||f}t	|D ]}|| | |  }||t8 }td| d }|dkr"|dkrtdt|d | }n
t|}n|t|||  }tjddN ||d	d	d	f  |	|d	|d f d	d	tjf | 7  < W d	   n1 s0    Y  ||d	d	f }t
|}t
|}tjdd0 |
| | | }|| | | }W d	   n1 s0    Y  d||d
k < d||d
k < t|dk } t|dk }!t||  || < t||! ||!< || }||9 }q| | |d  }||7 }|d | |d  ||  }qdt| }"|| }#||"|#fS )a5  Multivariate t integration over box bounds.

    Parameters
    ----------
    m : int > n_batches
        The number of points to sample. This number will be divided into
        `n_batches` batches that apply random offsets of the sampling lattice
        for each batch in order to estimate the error.
    nu : float >= 0
        The shape parameter of the multivariate t distribution.
    covar : (n, n) float array
        Possibly singular, positive semidefinite symmetric covariance matrix.
    low, high : (n,) float array
        The low and high integration bounds.
    rng : Generator, optional
        default_rng(), yada, yada
    lattice : 'cbc' or callable
        The type of lattice rule to use to construct the integration points.
    n_batches : int > 0, optional
        The number of QMC batches to apply.

    Returns
    -------
    prob : float
        The estimated probability mass within the bounds.
    est_error : float
        3 times the standard error of the batch estimates.
    n_samples : int
        The number of samples actually used.
    r   r    r   r4   r   r   ignore)invalidNi	   rL   )rO   r   r   Zasarrayfloat64rM   rN   r1   r"   r#   r!   rP   rS   rT   r
   rU   r   Z	ones_likerV   Zerrstatenewaxisr6   rW   )$r*   nur:   r;   r<   r5   rX   rY   ZsnrZ   r[   r\   r   rA   r`   r'   r&   rb   r-   rd   r/   re   r)   rf   r   r.   rc   ra   sir   ZloisZhiisZlo_maskZhi_maskrB   r@   r   r   r   _qmvtR  sV    



^

0
rs   绽|=c              
   C   s  t j| t jd}t j|t jd}t j|t jd}|jd }|j||fkrPtd|j|fksh|j|fkrptdt t t |d}d||dk< || }|| }|| }||ddt jf  }t 	|}	t dt j
 }
t|D ]}|d	 | }|}d}d}d}d}d}t||D ]}|||f |krt |||f }|dkrf||d|f |	d|  }|| | | }|| | | }t|t| }||kr|}|}|}|}|}q||krv|||f |||f< t|t j|d|f t j|d|f  t|t j|d	 d|f t j|d	 d|f  t|t j|d	 ||f t j||d	 |f  t||| t||| ||kr||||f< d|||d	 df< t|d	 |D ]Z}|||f  |  < |||d	 |d	 f  |||f ||d	 |d	 |f  8  < qt||krNt | | d t | | d  |
|  |	|< n6|| d |	|< |d
k rr||	|< n|dkr||	|< ||d|d	 f  |  < ||  |  < ||  |  < qd||d|f< || ||  d |	|< q|||fS )a{  Compute a scaled, permuted Cholesky factor, with integration bounds.

    The scaling and permuting of the dimensions accomplishes part of the
    transformation of the original integration problem into a more numerically
    tractable form. The lower-triangular Cholesky factor will then be used in
    the subsequent integration. The integration bounds will be scaled and
    permuted as well.

    Parameters
    ----------
    covar : (n, n) float array
        Possibly singular, positive semidefinite symmetric covariance matrix.
    low, high : (n,) float array
        The low and high integration bounds.
    tol : float, optional
        The singularity tolerance.

    Returns
    -------
    cho : (n, n) float array
        Lower Cholesky factor, scaled and permuted.
    new_low, new_high : (n,) float array
        The scaled and permuted low and high integration bounds.
    r    r   z!expected a square symmetric arrayzLexpected integration boundaries the same dimensions as the covariance matrixr4   r   Nr   r   irJ   )r   arrayro   rN   
ValueErrorr   maximumZdiagrp   rP   rE   r#   r6   _swap_slicesZs_rU   exp)r:   r;   r<   ZtolrZ   Znew_loZnew_hir   rc   ra   Zsqtpr   ZepkZimZckZdemr/   Zlo_mZhi_mre   r^   Zlo_iZhi_ider   r   r   rM     s    




(00
D&



rM   c                 C   s(   | |   }| |   | |< || |< d S )N)rR   )rf   Zslc1Zslc2tr   r   r   rx     s    rx   )r2   r3   )rI   rJ   )F)rI   rJ   )rt   )numpyr   Z	scipy.fftr   r   Zscipy.specialr   r   r   Zscipy.stats._qmcr   r6   rV   r   r   r1   rH   rg   rk   rs   rM   rx   r   r   r   r   <module>#   s   >
5
F
@
Z
f