a
    BCCf%                    @  s^  d Z ddlmZ ddlZddlZddlZddlZddlZddlm	Z	m
Z
 ddlmZ ddlmZmZmZmZmZ ddlZerddlmZ ddlmZmZmZmZ ddlmZ ddlmZmZ dd	l m!Z! dd
l"m#Z#m$Z$ ddl%m&Z& ddl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z. ddl/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6 g dZ7edvdddddZ8edddddZ8dwddZ8dddddddddd Z9ddd!d"d#Z:dd$dd%ddd&d'd(d)d*d+Z;dxdd.d/d(d0d1d2Z<ddd3d(d4d5d6Z=dd7d7d7d(d8d9d:Z>d7dd;d<d=Z?d'd>d;d?d@Z@ddAd'dBddCdDdEZAdyddddddGd'd'd'ddHdBd'ddIdJdKZBG dLdM dMe	ZCG dNdO dOeCZDG dPdQ dQeCZEG dRdS dSeCZFG dTdU dUeCZGG dVdW dWZHG dXdY dYZIdZd[d\d]d^d_ZJdd7d7dd[dd`dadbZKdd(d!dcddZLdd(d/ddedfdgZMdhdiddjdd3d'dkd[ddldmdnZNdzd'd'dodpdqZOddd7drdsdtduZPdS ){z&Quasi-Monte Carlo engines and helpers.    )annotationsN)ABCabstractmethod)partial)CallableClassVarLiteraloverloadTYPE_CHECKING)DecimalNumberGeneratorType	IntNumberSeedType)rng_integers
_rng_spawn)minimum_spanning_tree)distanceVoronoi)gammainc   )_initialize_v
_cscramble_fill_p_cumulative_draw_fast_forward_categorize_MAXDIM) _cy_wrapper_centered_discrepancy#_cy_wrapper_wrap_around_discrepancy_cy_wrapper_mixture_discrepancy_cy_wrapper_l2_star_discrepancy_cy_wrapper_update_discrepancy_cy_van_der_corput_scrambled_cy_van_der_corput)scalediscrepancygeometric_discrepancyupdate_discrepancy	QMCEngineSobolHaltonLatinHypercubePoissonDiskMultinomialQMCMultivariateNormalQMC.IntNumber | Noneznp.random.Generator)seedreturnc                 C  s   d S N r0   r3   r3   L/var/www/html/django/DPS/env/lib/python3.9/site-packages/scipy/stats/_qmc.pycheck_random_state4   s    r6   r   c                 C  s   d S r2   r3   r4   r3   r3   r5   r6   9   s    c                 C  sR   | du st | tjtjfr&tj| S t | tjjtjjfr@| S t	| ddS )a!  Turn `seed` into a `numpy.random.Generator` instance.

    Parameters
    ----------
    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
        If `seed` is an int or None, a new `numpy.random.Generator` is
        created using ``np.random.default_rng(seed)``.
        If `seed` is already a ``Generator`` or ``RandomState`` instance, then
        the provided instance is used.

    Returns
    -------
    seed : {`numpy.random.Generator`, `numpy.random.RandomState`}
        Random number generator.

    Nz9 cannot be used to seed a numpy.random.Generator instance)

isinstancenumbersIntegralnpintegerrandomZdefault_rngZRandomState	Generator
ValueErrorr4   r3   r3   r5   r6   ?   s
    F)reversenpt.ArrayLikebool
np.ndarray)samplel_boundsu_boundsr?   r1   c                C  s   t | } | jdkstdt||| jd d\}}|sh|  dksP|  dk rXtd| ||  | S t | |krt | |kstd| | ||  S d	S )
a  Sample scaling from unit hypercube to different bounds.

    To convert a sample from :math:`[0, 1)` to :math:`[a, b), b>a`,
    with :math:`a` the lower bounds and :math:`b` the upper bounds.
    The following transformation is used:

    .. math::

        (b - a) \cdot \text{sample} + a

    Parameters
    ----------
    sample : array_like (n, d)
        Sample to scale.
    l_bounds, u_bounds : array_like (d,)
        Lower and upper bounds (resp. :math:`a`, :math:`b`) of transformed
        data. If `reverse` is True, range of the original data to transform
        to the unit hypercube.
    reverse : bool, optional
        Reverse the transformation from different bounds to the unit hypercube.
        Default is False.

    Returns
    -------
    sample : array_like (n, d)
        Scaled sample.

    Examples
    --------
    Transform 3 samples in the unit hypercube to bounds:

    >>> from scipy.stats import qmc
    >>> l_bounds = [-2, 0]
    >>> u_bounds = [6, 5]
    >>> sample = [[0.5 , 0.75],
    ...           [0.5 , 0.5],
    ...           [0.75, 0.25]]
    >>> sample_scaled = qmc.scale(sample, l_bounds, u_bounds)
    >>> sample_scaled
    array([[2.  , 3.75],
           [2.  , 2.5 ],
           [4.  , 1.25]])

    And convert back to the unit hypercube:

    >>> sample_ = qmc.scale(sample_scaled, l_bounds, u_bounds, reverse=True)
    >>> sample_
    array([[0.5 , 0.75],
           [0.5 , 0.5 ],
           [0.75, 0.25]])

       Sample is not a 2D arrayr   )rD   rE   d      ?        Sample is not in unit hypercubezSample is out of boundsN)	r:   asarrayndimr>   _validate_boundsshapemaxminall)rC   rD   rE   r?   lowerupperr3   r3   r5   r$   Y   s    ;


r$   rC   r1   c                 C  sH   t j| t jdd} | jdks$td|  dks<|  dk rDtd| S )a  Ensure that sample is a 2D array and is within a unit hypercube

    Parameters
    ----------
    sample : array_like (n, d)
        A 2D array of points.

    Returns
    -------
    np.ndarray
        The array interpretation of the input sample

    Raises
    ------
    ValueError
        If the input is not a 2D array or contains points outside of
        a unit hypercube.
    CdtypeorderrF   rG   rI   rJ   rK   )r:   rL   float64rM   r>   rP   rQ   rC   r3   r3   r5   _ensure_in_unit_hypercube   s    
r\   CD)	iterativemethodworkersz$Literal['CD', 'WD', 'MD', 'L2-star']r   float)rC   r^   r_   r`   r1   c                C  sR   t | } t|}ttttd}||v r8|| | ||dS t|dt|dS )a-  Discrepancy of a given sample.

    Parameters
    ----------
    sample : array_like (n, d)
        The sample to compute the discrepancy from.
    iterative : bool, optional
        Must be False if not using it for updating the discrepancy.
        Default is False. Refer to the notes for more details.
    method : str, optional
        Type of discrepancy, can be ``CD``, ``WD``, ``MD`` or ``L2-star``.
        Refer to the notes for more details. Default is ``CD``.
    workers : int, optional
        Number of workers to use for parallel processing. If -1 is given all
        CPU threads are used. Default is 1.

    Returns
    -------
    discrepancy : float
        Discrepancy.

    See Also
    --------
    geometric_discrepancy

    Notes
    -----
    The discrepancy is a uniformity criterion used to assess the space filling
    of a number of samples in a hypercube. A discrepancy quantifies the
    distance between the continuous uniform distribution on a hypercube and the
    discrete uniform distribution on :math:`n` distinct sample points.

    The lower the value is, the better the coverage of the parameter space is.

    For a collection of subsets of the hypercube, the discrepancy is the
    difference between the fraction of sample points in one of those
    subsets and the volume of that subset. There are different definitions of
    discrepancy corresponding to different collections of subsets. Some
    versions take a root mean square difference over subsets instead of
    a maximum.

    A measure of uniformity is reasonable if it satisfies the following
    criteria [1]_:

    1. It is invariant under permuting factors and/or runs.
    2. It is invariant under rotation of the coordinates.
    3. It can measure not only uniformity of the sample over the hypercube,
       but also the projection uniformity of the sample over non-empty
       subset of lower dimension hypercubes.
    4. There is some reasonable geometric meaning.
    5. It is easy to compute.
    6. It satisfies the Koksma-Hlawka-like inequality.
    7. It is consistent with other criteria in experimental design.

    Four methods are available:

    * ``CD``: Centered Discrepancy - subspace involves a corner of the
      hypercube
    * ``WD``: Wrap-around Discrepancy - subspace can wrap around bounds
    * ``MD``: Mixture Discrepancy - mix between CD/WD covering more criteria
    * ``L2-star``: L2-star discrepancy - like CD BUT variant to rotation

    See [2]_ for precise definitions of each method.

    Lastly, using ``iterative=True``, it is possible to compute the
    discrepancy as if we had :math:`n+1` samples. This is useful if we want
    to add a point to a sampling and check the candidate which would give the
    lowest discrepancy. Then you could just update the discrepancy with
    each candidate using `update_discrepancy`. This method is faster than
    computing the discrepancy for a large number of candidates.

    References
    ----------
    .. [1] Fang et al. "Design and modeling for computer experiments".
       Computer Science and Data Analysis Series, 2006.
    .. [2] Zhou Y.-D. et al. "Mixture discrepancy for quasi-random point sets."
       Journal of Complexity, 29 (3-4) , pp. 283-301, 2013.
    .. [3] T. T. Warnock. "Computational investigations of low discrepancy
       point sets." Applications of Number Theory to Numerical
       Analysis, Academic Press, pp. 319-343, 1972.

    Examples
    --------
    Calculate the quality of the sample using the discrepancy:

    >>> import numpy as np
    >>> from scipy.stats import qmc
    >>> space = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]])
    >>> l_bounds = [0.5, 0.5]
    >>> u_bounds = [6.5, 6.5]
    >>> space = qmc.scale(space, l_bounds, u_bounds, reverse=True)
    >>> space
    array([[0.08333333, 0.41666667],
           [0.25      , 0.91666667],
           [0.41666667, 0.25      ],
           [0.58333333, 0.75      ],
           [0.75      , 0.08333333],
           [0.91666667, 0.58333333]])
    >>> qmc.discrepancy(space)
    0.008142039609053464

    We can also compute iteratively the ``CD`` discrepancy by using
    ``iterative=True``.

    >>> disc_init = qmc.discrepancy(space[:-1], iterative=True)
    >>> disc_init
    0.04769081147119336
    >>> qmc.update_discrepancy(space[-1], space[:-1], disc_init)
    0.008142039609053513

    )r]   ZWDZMDzL2-starr`   z* is not a valid method. It must be one of N)r\   _validate_workersr   r   r   r    r>   set)rC   r^   r_   r`   methodsr3   r3   r5   r%      s    ur%   mindist	euclideanzLiteral['mindist', 'mst']str)rC   r_   metricr1   c                 C  s   t | } | jd dk rtdtj| |d}t|dkrHtjddd |dkrbt	||
  S |d	krt|}t|}||
  }t|S t|d
dS )am  Discrepancy of a given sample based on its geometric properties.

    Parameters
    ----------
    sample : array_like (n, d)
        The sample to compute the discrepancy from.
    method : {"mindist", "mst"}, optional
        The method to use. One of ``mindist`` for minimum distance (default)
        or ``mst`` for minimum spanning tree.
    metric : str or callable, optional
        The distance metric to use. See the documentation
        for `scipy.spatial.distance.pdist` for the available metrics and
        the default.

    Returns
    -------
    discrepancy : float
        Discrepancy (higher values correspond to greater sample uniformity).

    See Also
    --------
    discrepancy

    Notes
    -----
    The discrepancy can serve as a simple measure of quality of a random sample.
    This measure is based on the geometric properties of the distribution of points
    in the sample, such as the minimum distance between any pair of points, or
    the mean edge length in a minimum spanning tree.

    The higher the value is, the better the coverage of the parameter space is.
    Note that this is different from `scipy.stats.qmc.discrepancy`, where lower
    values correspond to higher quality of the sample.

    Also note that when comparing different sampling strategies using this function,
    the sample size must be kept constant.

    It is possible to calculate two metrics from the minimum spanning tree:
    the mean edge length and the standard deviation of edges lengths. Using
    both metrics offers a better picture of uniformity than either metric alone,
    with higher mean and lower standard deviation being preferable (see [1]_
    for a brief discussion). This function currently only calculates the mean
    edge length.

    References
    ----------
    .. [1] Franco J. et al. "Minimum Spanning Tree: A new approach to assess the quality
       of the design of computer experiments." Chemometrics and Intelligent Laboratory
       Systems, 97 (2), pp. 164-169, 2009.

    Examples
    --------
    Calculate the quality of the sample using the minimum euclidean distance
    (the defaults):

    >>> import numpy as np
    >>> from scipy.stats import qmc
    >>> rng = np.random.default_rng(191468432622931918890291693003068437394)
    >>> sample = qmc.LatinHypercube(d=2, seed=rng).random(50)
    >>> qmc.geometric_discrepancy(sample)
    0.03708161435687876

    Calculate the quality using the mean edge length in the minimum
    spanning tree:

    >>> qmc.geometric_discrepancy(sample, method='mst')
    0.1105149978798376

    Display the minimum spanning tree and the points with
    the smallest distance:

    >>> import matplotlib.pyplot as plt
    >>> from matplotlib.lines import Line2D
    >>> from scipy.sparse.csgraph import minimum_spanning_tree
    >>> from scipy.spatial.distance import pdist, squareform
    >>> dist = pdist(sample)
    >>> mst = minimum_spanning_tree(squareform(dist))
    >>> edges = np.where(mst.toarray() > 0)
    >>> edges = np.asarray(edges).T
    >>> min_dist = np.min(dist)
    >>> min_idx = np.argwhere(squareform(dist) == min_dist)[0]
    >>> fig, ax = plt.subplots(figsize=(10, 5))
    >>> _ = ax.set(aspect='equal', xlabel=r'$x_1$', ylabel=r'$x_2$',
    ...            xlim=[0, 1], ylim=[0, 1])
    >>> for edge in edges:
    ...     ax.plot(sample[edge, 0], sample[edge, 1], c='k')
    >>> ax.scatter(sample[:, 0], sample[:, 1])
    >>> ax.add_patch(plt.Circle(sample[min_idx[0]], min_dist, color='red', fill=False))
    >>> markers = [
    ...     Line2D([0], [0], marker='o', lw=0, label='Sample points'),
    ...     Line2D([0], [0], color='k', label='Minimum spanning tree'),
    ...     Line2D([0], [0], marker='o', lw=0, markerfacecolor='w', markeredgecolor='r',
    ...            label='Minimum point-to-point distance'),
    ... ]
    >>> ax.legend(handles=markers, loc='center left', bbox_to_anchor=(1, 0.5));
    >>> plt.show()

    r   rF   z'Sample must contain at least two points)ri   rJ   z!Sample contains duplicate points.
stacklevelrf   mstz< is not a valid method. It must be one of {'mindist', 'mst'}N)r\   rO   r>   r   pdistr:   anywarningswarnrQ   nonzeroZ
squareformr   mean)rC   r_   ri   Z	distancesZfully_connected_graphrl   r3   r3   r5   r&   Q  s    f

r&   r   )x_newrC   initial_discr1   c                 C  s   t j|t jdd}t j| t jdd} |jdks6td| dksN| dk rVtd| jdkshtd	t | d
krt | dkstd| jd
 |jd krtdt	| ||S )a  Update the centered discrepancy with a new sample.

    Parameters
    ----------
    x_new : array_like (1, d)
        The new sample to add in `sample`.
    sample : array_like (n, d)
        The initial sample.
    initial_disc : float
        Centered discrepancy of the `sample`.

    Returns
    -------
    discrepancy : float
        Centered discrepancy of the sample composed of `x_new` and `sample`.

    Examples
    --------
    We can also compute iteratively the discrepancy by using
    ``iterative=True``.

    >>> import numpy as np
    >>> from scipy.stats import qmc
    >>> space = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]])
    >>> l_bounds = [0.5, 0.5]
    >>> u_bounds = [6.5, 6.5]
    >>> space = qmc.scale(space, l_bounds, u_bounds, reverse=True)
    >>> disc_init = qmc.discrepancy(space[:-1], iterative=True)
    >>> disc_init
    0.04769081147119336
    >>> qmc.update_discrepancy(space[-1], space[:-1], disc_init)
    0.008142039609053513

    rV   rW   rF   rG   rI   rJ   rK   r   zx_new is not a 1D arrayr   zx_new is not in unit hypercubez&x_new and sample must be broadcastable)
r:   rL   rZ   rM   r>   rP   rQ   rR   rO   r!   )rs   rC   rt   r3   r3   r5   r'     s    &

r'   int)rC   i1i2kdiscc                 C  s  | j d }| d }d|d  tjddt||ddf  t| t||ddf |   dd }d|d  tjddt||ddf  t| t||ddf |   dd }d|d  tdt||ddf   d| tddt||ddf   d||ddf d     }	d|d  tdt||ddf   d| tddt||ddf   d||ddf d     }
dt|||f  t|dd|f  t|||f |dd|f   }dt|||f  t|dd|f  t|||f |dd|f   }|| }|| }|| }dt|||f  dt|||f   }dt|||f  dt|||f   }tdt||ddf  }tdt||ddf  }tddt||ddf   d||ddf d   }tddt||ddf   d||ddf d   }|| |d  d| | | |  }||d |  d| || |   }|| | | }tj|td	}d
|||g< t|| }|| |	 | |
 d|  }|S )a  Centered discrepancy after an elementary perturbation of a LHS.

    An elementary perturbation consists of an exchange of coordinates between
    two points: ``sample[i1, k] <-> sample[i2, k]``. By construction,
    this operation conserves the LHS properties.

    Parameters
    ----------
    sample : array_like (n, d)
        The sample (before permutation) to compute the discrepancy from.
    i1 : int
        The first line of the elementary permutation.
    i2 : int
        The second line of the elementary permutation.
    k : int
        The column of the elementary permutation.
    disc : float
        Centered discrepancy of the design before permutation.

    Returns
    -------
    discrepancy : float
        Centered discrepancy of the design after permutation.

    References
    ----------
    .. [1] Jin et al. "An efficient algorithm for constructing optimal design
       of computer experiments", Journal of Statistical Planning and
       Inference, 2005.

    r         ?rI   g       @Nr   ZaxisrF   rX   F)rO   r:   prodabsonesrA   sum)rC   rv   rw   rx   ry   nZz_ijZc_i1jZc_i2jZc_i1i1Zc_i2i2numZdenumgammaZc_p_i1jZc_p_i2jalphabetaZg_i1Zg_i2Zh_i1Zh_i2Zc_p_i1i1Zc_p_i2i2Zsum_maskZdisc_epr3   r3   r5   _perturb_discrepancy  sj    !


($($&&((::$$r   r   r1   c                 C  s   t j| d | d dk td}tdt| d d d D ]X}d| d dB }d||| d dd| < d|||d|d@   d	  d dd| < q8t jdddt |d
 dd  d dB f S )a  Prime numbers from 2 to *n*.

    Parameters
    ----------
    n : int
        Sup bound with ``n >= 6``.

    Returns
    -------
    primes : list(int)
        Primes in ``2 <= p < n``.

    Notes
    -----
    Taken from [1]_ by P.T. Roy, written consent given on 23.04.2021
    by the original author, Bruno Astrolino, for free use in SciPy under
    the 3-clause BSD.

    References
    ----------
    .. [1] `StackOverflow <https://stackoverflow.com/questions/2068372>`_.

          rF   r|   r   rz   FN   r   )r:   r   rA   rangeru   Zr_rq   )r   sieveirx   r3   r3   r5   primes_from_2_toe  s    ,r   z	list[int]c                 C  sL   g dd|  }t || k rHd}t|d|  }t || kr>qH|d7 }q |S )zList of the n-first prime numbers.

    Parameters
    ----------
    n : int
        Number of prime numbers wanted.

    Returns
    -------
    primes : list(int)
        List of primes.

    )rF   r                              %   )   +   /   5   ;   =   C   G   I   O   S   Y   a   e   g   k   m   q                                                                           i  i  i  i  i  i  i  i%  i3  i7  i9  i=  iK  iQ  i[  i]  ia  ig  io  iu  i{  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i	  i  i  i#  i-  i3  i9  i;  iA  iK  iQ  iW  iY  i_  ie  ii  ik  iw  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i  i)  i+  i5  i7  i;  i=  iG  iU  iY  i[  i_  im  iq  is  iw  i  i  i  i  i  i  i  i  i  i  i  i  i  i  Ni  i  )lenr   )r   primesZ
big_numberr3   r3   r5   n_primes  s    
r   )random_stater   )baser   r1   c                C  sR   t |}tdt|  d }tjt| d |dd}|D ]}|| q>|S )a  Permutations for scrambling a Van der Corput sequence.

    Parameters
    ----------
    base : int
        Base of the sequence.
    random_state : {None, int, `numpy.random.Generator`}, optional
        If `seed` is an int or None, a new `numpy.random.Generator` is
        created using ``np.random.default_rng(seed)``.
        If `seed` is already a ``Generator`` instance, then the provided
        instance is used.

    Returns
    -------
    permutations : array_like
        Permutation indices.

    Notes
    -----
    In Algorithm 1 of Owen 2017, a permutation of `np.arange(base)` is
    created for each positive integer `k` such that `1 - base**-k < 1`
    using floating-point arithmetic. For double precision floats, the
    condition `1 - base**-k < 1` can also be written as `base**-k >
    2**-54`, which makes it more apparent how many permutations we need
    to create.
    6   r   Nr   r{   )r6   mathceillog2r:   repeatarangeshuffle)r   r   rngcountpermutationspermr3   r3   r5   _van_der_corput_permutations  s    r   rF   )start_indexscrambler   r0   r`   npt.ArrayLike | None)r   r   r   r   r   r0   r`   r1   c                C  sb   |dk rt d|rP|du r*t||d}n
t|}|tj}t| ||||S t| |||S dS )aw  Van der Corput sequence.

    Pseudo-random number generator based on a b-adic expansion.

    Scrambling uses permutations of the remainders (see [1]_). Multiple
    permutations are applied to construct a point. The sequence of
    permutations has to be the same for all points of the sequence.

    Parameters
    ----------
    n : int
        Number of element of the sequence.
    base : int, optional
        Base of the sequence. Default is 2.
    start_index : int, optional
        Index to start the sequence from. Default is 0.
    scramble : bool, optional
        If True, use Owen scrambling. Otherwise no scrambling is done.
        Default is True.
    permutations : array_like, optional
        Permutations used for scrambling.
    seed : {None, int, `numpy.random.Generator`}, optional
        If `seed` is an int or None, a new `numpy.random.Generator` is
        created using ``np.random.default_rng(seed)``.
        If `seed` is already a ``Generator`` instance, then the provided
        instance is used.
    workers : int, optional
        Number of workers to use for parallel processing. If -1 is
        given all CPU threads are used. Default is 1.

    Returns
    -------
    sequence : list (n,)
        Sequence of Van der Corput.

    References
    ----------
    .. [1] A. B. Owen. "A randomized Halton algorithm in R",
       :arxiv:`1706.02808`, 2017.

    rF   z'base' must be at least 2Nr   r   )r>   r   r:   rL   astypeint64r"   r#   )r   r   r   r   r   r0   r`   r3   r3   r5   van_der_corput  s    2
r   c                   @  s   e Zd ZdZeddddddddd	d
Zed!ddddddddZd"ddddddddZddddddddddddddZd dddZ	dd ddd Z
dS )#r(   a  A generic Quasi-Monte Carlo sampler class meant for subclassing.

    QMCEngine is a base class to construct a specific Quasi-Monte Carlo
    sampler. It cannot be used directly as a sampler.

    Parameters
    ----------
    d : int
        Dimension of the parameter space.
    optimization : {None, "random-cd", "lloyd"}, optional
        Whether to use an optimization scheme to improve the quality after
        sampling. Note that this is a post-processing step that does not
        guarantee that all properties of the sample will be conserved.
        Default is None.

        * ``random-cd``: random permutations of coordinates to lower the
          centered discrepancy. The best sample based on the centered
          discrepancy is constantly updated. Centered discrepancy-based
          sampling shows better space-filling robustness toward 2D and 3D
          subprojections compared to using other discrepancy measures.
        * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm.
          The process converges to equally spaced samples.

        .. versionadded:: 1.10.0
    seed : {None, int, `numpy.random.Generator`}, optional
        If `seed` is an int or None, a new `numpy.random.Generator` is
        created using ``np.random.default_rng(seed)``.
        If `seed` is already a ``Generator`` instance, then the provided
        instance is used.

    Notes
    -----
    By convention samples are distributed over the half-open interval
    ``[0, 1)``. Instances of the class can access the attributes: ``d`` for
    the dimension; and ``rng`` for the random number generator (used for the
    ``seed``).

    **Subclassing**

    When subclassing `QMCEngine` to create a new sampler,  ``__init__`` and
    ``random`` must be redefined.

    * ``__init__(d, seed=None)``: at least fix the dimension. If the sampler
      does not take advantage of a ``seed`` (deterministic methods like
      Halton), this parameter can be omitted.
    * ``_random(n, *, workers=1)``: draw ``n`` from the engine. ``workers``
      is used for parallelism. See `Halton` for example.

    Optionally, two other methods can be overwritten by subclasses:

    * ``reset``: Reset the engine to its original state.
    * ``fast_forward``: If the sequence is deterministic (like Halton
      sequence), then ``fast_forward(n)`` is skipping the ``n`` first draw.

    Examples
    --------
    To create a random sampler based on ``np.random.random``, we would do the
    following:

    >>> from scipy.stats import qmc
    >>> class RandomEngine(qmc.QMCEngine):
    ...     def __init__(self, d, seed=None):
    ...         super().__init__(d=d, seed=seed)
    ...
    ...
    ...     def _random(self, n=1, *, workers=1):
    ...         return self.rng.random((n, self.d))
    ...
    ...
    ...     def reset(self):
    ...         super().__init__(d=self.d, seed=self.rng_seed)
    ...         return self
    ...
    ...
    ...     def fast_forward(self, n):
    ...         self.random(n)
    ...         return self

    After subclassing `QMCEngine` to define the sampling strategy we want to
    use, we can create an instance to sample from.

    >>> engine = RandomEngine(2)
    >>> engine.random(5)
    array([[0.22733602, 0.31675834],  # random
           [0.79736546, 0.67625467],
           [0.39110955, 0.33281393],
           [0.59830875, 0.18673419],
           [0.67275604, 0.94180287]])

    We can also reset the state of the generator and resample again.

    >>> _ = engine.reset()
    >>> engine.random(5)
    array([[0.22733602, 0.31675834],  # random
           [0.79736546, 0.67625467],
           [0.39110955, 0.33281393],
           [0.59830875, 0.18673419],
           [0.67275604, 0.94180287]])

    N)optimizationr0   r   $Literal['random-cd', 'lloyd'] | Noner   None)rH   r   r0   r1   c                C  s   t t|t jr|dk r"td|| _t|t jjrHt	|dd | _
n
t|| _
t| j
| _d| _dd| j
ddd d}t||| _d S )	Nr   z&d must be a non-negative integer valuer   d   i'  h㈵>
   )
n_nochangen_itersr   tolmaxiterqhull_options)r:   
issubdtypetyper;   r>   rH   r7   r<   r=   r   r   r6   copydeepcopyrng_seednum_generated_select_optimizeroptimization_method)selfrH   r   r0   configr3   r3   r5   __init__}  s     
zQMCEngine.__init__r   rb   rB   r   r`   r1   c                C  s   d S r2   r3   )r   r   r`   r3   r3   r5   _random  s    zQMCEngine._randomc                C  s4   | j ||d}| jdur"| |}|  j|7  _|S )aM  Draw `n` in the half-open interval ``[0, 1)``.

        Parameters
        ----------
        n : int, optional
            Number of samples to generate in the parameter space.
            Default is 1.
        workers : int, optional
            Only supported with `Halton`.
            Number of workers to use for parallel processing. If -1 is
            given all CPU threads are used. Default is 1. It becomes faster
            than one worker for `n` greater than :math:`10^3`.

        Returns
        -------
        sample : array_like (n, d)
            QMC sample.

        rb   N)r   r   r   r   r   r`   rC   r3   r3   r5   r<     s
    

zQMCEngine.randomF)rE   r   endpointr`   r@   r   rA   )rD   rE   r   r   r`   r1   c                C  s   |du r|}d}t |}t |}|r0|d }t |jt jrPt |jt js\d}t|t| trv| j||d}n| j|d}t	|||d}t 
|t j}|S )a?  
        Draw `n` integers from `l_bounds` (inclusive) to `u_bounds`
        (exclusive), or if endpoint=True, `l_bounds` (inclusive) to
        `u_bounds` (inclusive).

        Parameters
        ----------
        l_bounds : int or array-like of ints
            Lowest (signed) integers to be drawn (unless ``u_bounds=None``,
            in which case this parameter is 0 and this value is used for
            `u_bounds`).
        u_bounds : int or array-like of ints, optional
            If provided, one above the largest (signed) integer to be drawn
            (see above for behavior if ``u_bounds=None``).
            If array-like, must contain integer values.
        n : int, optional
            Number of samples to generate in the parameter space.
            Default is 1.
        endpoint : bool, optional
            If true, sample from the interval ``[l_bounds, u_bounds]`` instead
            of the default ``[l_bounds, u_bounds)``. Defaults is False.
        workers : int, optional
            Number of workers to use for parallel processing. If -1 is
            given all CPU threads are used. Only supported when using `Halton`
            Default is 1.

        Returns
        -------
        sample : array_like (n, d)
            QMC sample.

        Notes
        -----
        It is safe to just use the same ``[0, 1)`` to integer mapping
        with QMC that you would use with MC. You still get unbiasedness,
        a strong law of large numbers, an asymptotically infinite variance
        reduction and a finite sample variance bound.

        To convert a sample from :math:`[0, 1)` to :math:`[a, b), b>a`,
        with :math:`a` the lower bounds and :math:`b` the upper bounds,
        the following transformation is used:

        .. math::

            \text{floor}((b - a) \cdot \text{sample} + a)

        Nr   r   zD'u_bounds' and 'l_bounds' must be integers or array-like of integers)r   r`   r   )rD   rE   )r:   
atleast_1dr   rX   r;   r>   r7   r*   r<   r$   floorr   r   )r   rD   rE   r   r   r`   messagerC   r3   r3   r5   integers  s$    8


zQMCEngine.integersr1   c                 C  s    t | j}t|| _d| _| S )zReset the engine to base state.

        Returns
        -------
        engine : QMCEngine
            Engine reset to its base state.

        r   )r   r   r   r6   r   r   )r   r0   r3   r3   r5   reset  s    	
zQMCEngine.resetr   c                 C  s   | j |d | S )a
  Fast-forward the sequence by `n` positions.

        Parameters
        ----------
        n : int
            Number of points to skip in the sequence.

        Returns
        -------
        engine : QMCEngine
            Engine reset to its base state.

        r   )r<   r   r   r3   r3   r5   fast_forward%  s    zQMCEngine.fast_forward)r   )r   )__name__
__module____qualname____doc__r   r   r   r<   r   r   r   r3   r3   r3   r5   r(     s*   e$  !Rr(   c                      s`   e Zd ZdZddddddddd	d
 fddZd	dddZdddddddddZ  ZS )r*   a  Halton sequence.

    Pseudo-random number generator that generalize the Van der Corput sequence
    for multiple dimensions. The Halton sequence uses the base-two Van der
    Corput sequence for the first dimension, base-three for its second and
    base-:math:`n` for its n-dimension.

    Parameters
    ----------
    d : int
        Dimension of the parameter space.
    scramble : bool, optional
        If True, use Owen scrambling. Otherwise no scrambling is done.
        Default is True.
    optimization : {None, "random-cd", "lloyd"}, optional
        Whether to use an optimization scheme to improve the quality after
        sampling. Note that this is a post-processing step that does not
        guarantee that all properties of the sample will be conserved.
        Default is None.

        * ``random-cd``: random permutations of coordinates to lower the
          centered discrepancy. The best sample based on the centered
          discrepancy is constantly updated. Centered discrepancy-based
          sampling shows better space-filling robustness toward 2D and 3D
          subprojections compared to using other discrepancy measures.
        * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm.
          The process converges to equally spaced samples.

        .. versionadded:: 1.10.0
    seed : {None, int, `numpy.random.Generator`}, optional
        If `seed` is an int or None, a new `numpy.random.Generator` is
        created using ``np.random.default_rng(seed)``.
        If `seed` is already a ``Generator`` instance, then the provided
        instance is used.

    Notes
    -----
    The Halton sequence has severe striping artifacts for even modestly
    large dimensions. These can be ameliorated by scrambling. Scrambling
    also supports replication-based error estimates and extends
    applicabiltiy to unbounded integrands.

    References
    ----------
    .. [1] Halton, "On the efficiency of certain quasi-random sequences of
       points in evaluating multi-dimensional integrals", Numerische
       Mathematik, 1960.
    .. [2] A. B. Owen. "A randomized Halton algorithm in R",
       :arxiv:`1706.02808`, 2017.

    Examples
    --------
    Generate samples from a low discrepancy sequence of Halton.

    >>> from scipy.stats import qmc
    >>> sampler = qmc.Halton(d=2, scramble=False)
    >>> sample = sampler.random(n=5)
    >>> sample
    array([[0.        , 0.        ],
           [0.5       , 0.33333333],
           [0.25      , 0.66666667],
           [0.75      , 0.11111111],
           [0.125     , 0.44444444]])

    Compute the quality of the sample using the discrepancy criterion.

    >>> qmc.discrepancy(sample)
    0.088893711419753

    If some wants to continue an existing design, extra points can be obtained
    by calling again `random`. Alternatively, you can skip some points like:

    >>> _ = sampler.fast_forward(5)
    >>> sample_continued = sampler.random(n=5)
    >>> sample_continued
    array([[0.3125    , 0.37037037],
           [0.8125    , 0.7037037 ],
           [0.1875    , 0.14814815],
           [0.6875    , 0.48148148],
           [0.4375    , 0.81481481]])

    Finally, samples can be scaled to bounds.

    >>> l_bounds = [0, 2]
    >>> u_bounds = [10, 5]
    >>> qmc.scale(sample_continued, l_bounds, u_bounds)
    array([[3.125     , 3.11111111],
           [8.125     , 4.11111111],
           [1.875     , 2.44444444],
           [6.875     , 3.44444444],
           [4.375     , 4.44444444]])

    TN)r   r   r0   r   rA   r   r   r   )rH   r   r   r0   r1   c                  sL   |d|d| _ t j|||d || _dd t|D | _|| _|   d S )NT)rH   r   r   rH   r   r0   c                 S  s   g | ]}t |qS r3   )ru   ).0bdimr3   r3   r5   
<listcomp>      z#Halton.__init__.<locals>.<listcomp>)
_init_quadsuperr   r0   r   r   r   _initialize_permutations)r   rH   r   r   r0   	__class__r3   r5   r     s    zHalton.__init__r   c                 C  sH   dgt | j | _| jrDt| jD ] \}}t|| jd}|| j|< q"dS )zxInitialize permutations for all Van der Corput sequences.

        Permutations are only needed for scrambling.
        Nr   )r   r   _permutationsr   	enumerater   r   )r   r   r  r   r3   r3   r5   r
    s    zHalton._initialize_permutationsr   rb   rB   r   c                  s:   t  fddtjD }t|j jS )a  Draw `n` in the half-open interval ``[0, 1)``.

        Parameters
        ----------
        n : int, optional
            Number of samples to generate in the parameter space. Default is 1.
        workers : int, optional
            Number of workers to use for parallel processing. If -1 is
            given all CPU threads are used. Default is 1. It becomes faster
            than one worker for `n` greater than :math:`10^3`.

        Returns
        -------
        sample : array_like (n, d)
            QMC sample.

        c              
     s.   g | ]&\}}t  |jjj| d qS ))r   r   r   r`   )r   r   r   r  )r  r   r  r   r   r`   r3   r5   r    s   
z"Halton._random.<locals>.<listcomp>)rc   r  r   r:   arrayTreshaperH   r   r3   r  r5   r     s
    zHalton._random)r   )r   r   r  r  r   r
  r   __classcell__r3   r3   r  r5   r*   7  s   _ r*   c                      sz   e Zd ZdZddddddddd	d
dd fddZdddddddddZddddddZddddddZ  ZS )r+   aU   Latin hypercube sampling (LHS).

    A Latin hypercube sample [1]_ generates :math:`n` points in
    :math:`[0,1)^{d}`. Each univariate marginal distribution is stratified,
    placing exactly one point in :math:`[j/n, (j+1)/n)` for
    :math:`j=0,1,...,n-1`. They are still applicable when :math:`n << d`.

    Parameters
    ----------
    d : int
        Dimension of the parameter space.
    scramble : bool, optional
        When False, center samples within cells of a multi-dimensional grid.
        Otherwise, samples are randomly placed within cells of the grid.

        .. note::
            Setting ``scramble=False`` does not ensure deterministic output.
            For that, use the `seed` parameter.

        Default is True.

        .. versionadded:: 1.10.0

    optimization : {None, "random-cd", "lloyd"}, optional
        Whether to use an optimization scheme to improve the quality after
        sampling. Note that this is a post-processing step that does not
        guarantee that all properties of the sample will be conserved.
        Default is None.

        * ``random-cd``: random permutations of coordinates to lower the
          centered discrepancy. The best sample based on the centered
          discrepancy is constantly updated. Centered discrepancy-based
          sampling shows better space-filling robustness toward 2D and 3D
          subprojections compared to using other discrepancy measures.
        * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm.
          The process converges to equally spaced samples.

        .. versionadded:: 1.8.0
        .. versionchanged:: 1.10.0
            Add ``lloyd``.

    strength : {1, 2}, optional
        Strength of the LHS. ``strength=1`` produces a plain LHS while
        ``strength=2`` produces an orthogonal array based LHS of strength 2
        [7]_, [8]_. In that case, only ``n=p**2`` points can be sampled,
        with ``p`` a prime number. It also constrains ``d <= p + 1``.
        Default is 1.

        .. versionadded:: 1.8.0

    seed : {None, int, `numpy.random.Generator`}, optional
        If `seed` is an int or None, a new `numpy.random.Generator` is
        created using ``np.random.default_rng(seed)``.
        If `seed` is already a ``Generator`` instance, then the provided
        instance is used.

    Notes
    -----

    When LHS is used for integrating a function :math:`f` over :math:`n`,
    LHS is extremely effective on integrands that are nearly additive [2]_.
    With a LHS of :math:`n` points, the variance of the integral is always
    lower than plain MC on :math:`n-1` points [3]_. There is a central limit
    theorem for LHS on the mean and variance of the integral [4]_, but not
    necessarily for optimized LHS due to the randomization.

    :math:`A` is called an orthogonal array of strength :math:`t` if in each
    n-row-by-t-column submatrix of :math:`A`: all :math:`p^t` possible
    distinct rows occur the same number of times. The elements of :math:`A`
    are in the set :math:`\{0, 1, ..., p-1\}`, also called symbols.
    The constraint that :math:`p` must be a prime number is to allow modular
    arithmetic. Increasing strength adds some symmetry to the sub-projections
    of a sample. With strength 2, samples are symmetric along the diagonals of
    2D sub-projections. This may be undesirable, but on the other hand, the
    sample dispersion is improved.

    Strength 1 (plain LHS) brings an advantage over strength 0 (MC) and
    strength 2 is a useful increment over strength 1. Going to strength 3 is
    a smaller increment and scrambled QMC like Sobol', Halton are more
    performant [7]_.

    To create a LHS of strength 2, the orthogonal array :math:`A` is
    randomized by applying a random, bijective map of the set of symbols onto
    itself. For example, in column 0, all 0s might become 2; in column 1,
    all 0s might become 1, etc.
    Then, for each column :math:`i` and symbol :math:`j`, we add a plain,
    one-dimensional LHS of size :math:`p` to the subarray where
    :math:`A^i = j`. The resulting matrix is finally divided by :math:`p`.

    References
    ----------
    .. [1] Mckay et al., "A Comparison of Three Methods for Selecting Values
       of Input Variables in the Analysis of Output from a Computer Code."
       Technometrics, 1979.
    .. [2] M. Stein, "Large sample properties of simulations using Latin
       hypercube sampling." Technometrics 29, no. 2: 143-151, 1987.
    .. [3] A. B. Owen, "Monte Carlo variance of scrambled net quadrature."
       SIAM Journal on Numerical Analysis 34, no. 5: 1884-1910, 1997
    .. [4]  Loh, W.-L. "On Latin hypercube sampling." The annals of statistics
       24, no. 5: 2058-2080, 1996.
    .. [5] Fang et al. "Design and modeling for computer experiments".
       Computer Science and Data Analysis Series, 2006.
    .. [6] Damblin et al., "Numerical studies of space filling designs:
       optimization of Latin Hypercube Samples and subprojection properties."
       Journal of Simulation, 2013.
    .. [7] A. B. Owen , "Orthogonal arrays for computer experiments,
       integration and visualization." Statistica Sinica, 1992.
    .. [8] B. Tang, "Orthogonal Array-Based Latin Hypercubes."
       Journal of the American Statistical Association, 1993.
    .. [9] Susan K. Seaholm et al. "Latin hypercube sampling and the
       sensitivity analysis of a Monte Carlo epidemic model".
       Int J Biomed Comput, 23(1-2), 97-112,
       :doi:`10.1016/0020-7101(88)90067-0`, 1988.

    Examples
    --------
    In [9]_, a Latin Hypercube sampling strategy was used to sample a
    parameter space to study the importance of each parameter of an epidemic
    model. Such analysis is also called a sensitivity analysis.

    Since the dimensionality of the problem is high (6), it is computationally
    expensive to cover the space. When numerical experiments are costly,
    QMC enables analysis that may not be possible if using a grid.

    The six parameters of the model represented the probability of illness,
    the probability of withdrawal, and four contact probabilities,
    The authors assumed uniform distributions for all parameters and generated
    50 samples.

    Using `scipy.stats.qmc.LatinHypercube` to replicate the protocol, the
    first step is to create a sample in the unit hypercube:

    >>> from scipy.stats import qmc
    >>> sampler = qmc.LatinHypercube(d=6)
    >>> sample = sampler.random(n=50)

    Then the sample can be scaled to the appropriate bounds:

    >>> l_bounds = [0.000125, 0.01, 0.0025, 0.05, 0.47, 0.7]
    >>> u_bounds = [0.000375, 0.03, 0.0075, 0.15, 0.87, 0.9]
    >>> sample_scaled = qmc.scale(sample, l_bounds, u_bounds)

    Such a sample was used to run the model 50 times, and a polynomial
    response surface was constructed. This allowed the authors to study the
    relative importance of each parameter across the range of
    possibilities of every other parameter.
    In this computer experiment, they showed a 14-fold reduction in the number
    of samples required to maintain an error below 2% on their response surface
    when compared to a grid sampling.

    Below are other examples showing alternative ways to construct LHS
    with even better coverage of the space.

    Using a base LHS as a baseline.

    >>> sampler = qmc.LatinHypercube(d=2)
    >>> sample = sampler.random(n=5)
    >>> qmc.discrepancy(sample)
    0.0196...  # random

    Use the `optimization` keyword argument to produce a LHS with
    lower discrepancy at higher computational cost.

    >>> sampler = qmc.LatinHypercube(d=2, optimization="random-cd")
    >>> sample = sampler.random(n=5)
    >>> qmc.discrepancy(sample)
    0.0176...  # random

    Use the `strength` keyword argument to produce an orthogonal array based
    LHS of strength 2. In this case, the number of sample points must be the
    square of a prime number.

    >>> sampler = qmc.LatinHypercube(d=2, strength=2)
    >>> sample = sampler.random(n=9)
    >>> qmc.discrepancy(sample)
    0.00526...  # random

    Options could be combined to produce an optimized centered
    orthogonal array based LHS. After optimization, the result would not
    be guaranteed to be of strength 2.

    Tr   N)r   strengthr   r0   r   rA   ru   r   r   r   )rH   r   r  r   r0   r1   c          	   
     s   |d||d| _ t j|||d || _| j| jd}z|| | _W n@ ty } z(|dt|}t	||W Y d }~n
d }~0 0 d S )NT)rH   r   r  r   )rH   r0   r   )r   rF   z, is not a valid strength. It must be one of )
r  r	  r   r   _random_lhs_random_oa_lhs
lhs_methodKeyErrorrd   r>   )	r   rH   r   r  r   r0   Zlhs_method_strengthexcr   r  r3   r5   r     s    zLatinHypercube.__init__rb   rB   r   c                C  s   |  |}|S r2   )r  )r   r   r`   lhsr3   r3   r5   r     s    
zLatinHypercube._randomr   c                 C  s|   | j sd}n| jj|| jfd}ttd|d | jdf}t| jD ]}| j||ddf  qH|j	}|| | }|S )zBase LHS algorithm.rz   sizer   N)
r   r   uniformrH   r:   tiler   r   r   r  )r   r   samplespermsr   r3   r3   r5   r    s    zLatinHypercube._random_lhsr   c                 C  s  t |t}|d }|d }t|d }||vs<||krVtd|dd d  | j|d krltdt j||ftd}t t 	|d}t j
t j| d	d
d	d|ddddf< td|D ]D}t |dddf ||dddf   ||ddd| d f< qt j||ftd}	t|D ]2}
| j|}||dd|
f  |	dd|
f< q&t j||fd}td| jd| jd}t|D ]h}
t|D ]X}|dd|
f |k}|| }||dd|
f |  |dd|
f |< | }qq|| }|ddd| jf S )z)Orthogonal array based LHS of strength 2.rF   r   z8n is not the square of a prime number. Close values are Nz*n is too small for d. Must be n > (d-1)**2)rO   rX   )rF   r   r{   r   )rO   )rH   r   r  r0   )r:   sqrtr   ru   r   r>   rH   zerosr  r   stackZmeshgridr  r   modemptyr   Zpermutationr+   r   r<   flattenr   )r   r   pZn_rowZn_colr   Z	oa_sampleZarraysZp_Z
oa_sample_jr   Zoa_lhs_sampleZ
lhs_enginerx   idxr  r3   r3   r5   r    sR    $
(zLatinHypercube._random_oa_lhs)r   )r   )r   )	r   r   r  r  r   r   r  r  r  r3   r3   r  r5   r+     s    :  r+   c                      s   e Zd ZU dZeZded< dddddddd	d
ddd fddZddddZd!ddddddddZ	dddddZ
d d fddZdd ddd Z  ZS )"r)   a  Engine for generating (scrambled) Sobol' sequences.

    Sobol' sequences are low-discrepancy, quasi-random numbers. Points
    can be drawn using two methods:

    * `random_base2`: safely draw :math:`n=2^m` points. This method
      guarantees the balance properties of the sequence.
    * `random`: draw an arbitrary number of points from the
      sequence. See warning below.

    Parameters
    ----------
    d : int
        Dimensionality of the sequence. Max dimensionality is 21201.
    scramble : bool, optional
        If True, use LMS+shift scrambling. Otherwise, no scrambling is done.
        Default is True.
    bits : int, optional
        Number of bits of the generator. Control the maximum number of points
        that can be generated, which is ``2**bits``. Maximal value is 64.
        It does not correspond to the return type, which is always
        ``np.float64`` to prevent points from repeating themselves.
        Default is None, which for backward compatibility, corresponds to 30.

        .. versionadded:: 1.9.0
    optimization : {None, "random-cd", "lloyd"}, optional
        Whether to use an optimization scheme to improve the quality after
        sampling. Note that this is a post-processing step that does not
        guarantee that all properties of the sample will be conserved.
        Default is None.

        * ``random-cd``: random permutations of coordinates to lower the
          centered discrepancy. The best sample based on the centered
          discrepancy is constantly updated. Centered discrepancy-based
          sampling shows better space-filling robustness toward 2D and 3D
          subprojections compared to using other discrepancy measures.
        * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm.
          The process converges to equally spaced samples.

        .. versionadded:: 1.10.0
    seed : {None, int, `numpy.random.Generator`}, optional
        If `seed` is an int or None, a new `numpy.random.Generator` is
        created using ``np.random.default_rng(seed)``.
        If `seed` is already a ``Generator`` instance, then the provided
        instance is used.

    Notes
    -----
    Sobol' sequences [1]_ provide :math:`n=2^m` low discrepancy points in
    :math:`[0,1)^{d}`. Scrambling them [3]_ makes them suitable for singular
    integrands, provides a means of error estimation, and can improve their
    rate of convergence. The scrambling strategy which is implemented is a
    (left) linear matrix scramble (LMS) followed by a digital random shift
    (LMS+shift) [2]_.

    There are many versions of Sobol' sequences depending on their
    'direction numbers'. This code uses direction numbers from [4]_. Hence,
    the maximum number of dimension is 21201. The direction numbers have been
    precomputed with search criterion 6 and can be retrieved at
    https://web.maths.unsw.edu.au/~fkuo/sobol/.

    .. warning::

       Sobol' sequences are a quadrature rule and they lose their balance
       properties if one uses a sample size that is not a power of 2, or skips
       the first point, or thins the sequence [5]_.

       If :math:`n=2^m` points are not enough then one should take :math:`2^M`
       points for :math:`M>m`. When scrambling, the number R of independent
       replicates does not have to be a power of 2.

       Sobol' sequences are generated to some number :math:`B` of bits.
       After :math:`2^B` points have been generated, the sequence would
       repeat. Hence, an error is raised.
       The number of bits can be controlled with the parameter `bits`.

    References
    ----------
    .. [1] I. M. Sobol', "The distribution of points in a cube and the accurate
       evaluation of integrals." Zh. Vychisl. Mat. i Mat. Phys., 7:784-802,
       1967.
    .. [2] J. Matousek, "On the L2-discrepancy for anchored boxes."
       J. of Complexity 14, 527-556, 1998.
    .. [3] Art B. Owen, "Scrambling Sobol and Niederreiter-Xing points."
       Journal of Complexity, 14(4):466-489, December 1998.
    .. [4] S. Joe and F. Y. Kuo, "Constructing sobol sequences with better
       two-dimensional projections." SIAM Journal on Scientific Computing,
       30(5):2635-2654, 2008.
    .. [5] Art B. Owen, "On dropping the first Sobol' point."
       :arxiv:`2008.08051`, 2020.

    Examples
    --------
    Generate samples from a low discrepancy sequence of Sobol'.

    >>> from scipy.stats import qmc
    >>> sampler = qmc.Sobol(d=2, scramble=False)
    >>> sample = sampler.random_base2(m=3)
    >>> sample
    array([[0.   , 0.   ],
           [0.5  , 0.5  ],
           [0.75 , 0.25 ],
           [0.25 , 0.75 ],
           [0.375, 0.375],
           [0.875, 0.875],
           [0.625, 0.125],
           [0.125, 0.625]])

    Compute the quality of the sample using the discrepancy criterion.

    >>> qmc.discrepancy(sample)
    0.013882107204860938

    To continue an existing design, extra points can be obtained
    by calling again `random_base2`. Alternatively, you can skip some
    points like:

    >>> _ = sampler.reset()
    >>> _ = sampler.fast_forward(4)
    >>> sample_continued = sampler.random_base2(m=2)
    >>> sample_continued
    array([[0.375, 0.375],
           [0.875, 0.875],
           [0.625, 0.125],
           [0.125, 0.625]])

    Finally, samples can be scaled to bounds.

    >>> l_bounds = [0, 2]
    >>> u_bounds = [10, 5]
    >>> qmc.scale(sample_continued, l_bounds, u_bounds)
    array([[3.75 , 3.125],
           [8.75 , 4.625],
           [6.25 , 2.375],
           [1.25 , 3.875]])

    zClassVar[int]MAXDIMTN)r   bitsr0   r   r   rA   r/   r   r   r   )rH   r   r-  r0   r   r1   c                  s4  |d||d| _ t j|||d || jkr>td| j d|| _|  | jd u rXd| _| jdkrltj| _n,d| j  k rdkrn n
tj	| _ntd	d
| j | _
tj|| jf| jd| _t| j|| jd |stj|| jd| _n|   | j | _dd
| j  | _| j| j dd| _| jtj| _d S )NT)rH   r   r-  r   r  z$Maximum supported dimensionality is .       @   zMaximum supported 'bits' is 64rF   r|   )dimr-  rI   r   r"  )r  r	  r   r,  r>   r-  r:   Zuint32dtype_iZuint64maxnr$  _svr   _shift	_scrambler   _quasi_scaler  _first_pointr   rZ   )r   rH   r   r-  r0   r   r  r3   r5   r   x  s6    




zSobol.__init__r   c                 C  sx   t t| jd| j| jf| jddt j| j| jd | _t 	t| jd| j| j| jf| jd}t
| j| j|| jd dS )z&Scramble the sequence using LMS+shift.rF   )r  rX   r|   )r2  r-  ltmsvN)r:   dotr   r   rH   r-  r3  r   r6  Ztrilr   r5  )r   r;  r3   r3   r5   r7    s    zSobol._scrambler   rb   rB   r   c                C  s   t j|| jft jd}|dkr"|S | j| }|| jkrd| j d| j d| j d| j d| d| d}| jd	krz|d
7 }t|| jdkr||d @ dkstj	ddd |dkr| j
}n<t|d | j| j| j| j| j|d t | j
|gd| }n$t|| jd | j| j| j| j|d |S )a$  Draw next point(s) in the Sobol' sequence.

        Parameters
        ----------
        n : int, optional
            Number of samples to generate in the parameter space. Default is 1.

        Returns
        -------
        sample : array_like (n, d)
            Sobol' sample.

        r|   r   zAt most 2**=z# distinct points can be generated. z0 points have been previously generated, then: n=+z. r1  zConsider increasing `bits`.r   zEThe balance properties of Sobol' points require n to be a power of 2.rF   rj   )r   num_genr2  r$   r<  quasirC   N)r:   r'  rH   rZ   r   r4  r-  r>   ro   rp   r:  r   r9  r5  r8  Zconcatenate)r   r   r`   rC   total_nmsgr3   r3   r5   r     sR    



zSobol._random)mr1   c                 C  s@   d| }| j | }||d @ dks6td| j ||| |S )a  Draw point(s) from the Sobol' sequence.

        This function draws :math:`n=2^m` points in the parameter space
        ensuring the balance properties of the sequence.

        Parameters
        ----------
        m : int
            Logarithm in base 2 of the number of samples; i.e., n = 2^m.

        Returns
        -------
        sample : array_like (n, d)
            Sobol' sample.

        rF   r   r   zThe balance properties of Sobol' points require n to be a power of 2. {0} points have been previously generated, then: n={0}+2**{1}={2}. If you still want to do this, the function 'Sobol.random()' can be used.)r   r>   formatr<   )r   rD  r   rB  r3   r3   r5   random_base2  s    
zSobol.random_base2c                   s   t    | j | _| S )zReset the engine to base state.

        Returns
        -------
        engine : Sobol
            Engine reset to its base state.

        )r	  r   r6  r   r8  r   r  r3   r5   r     s    	
zSobol.resetr   c                 C  sZ   | j dkr*t|d | j | j| j| jd nt|| j d | j| j| jd |  j |7  _ | S )a  Fast-forward the sequence by `n` positions.

        Parameters
        ----------
        n : int
            Number of points to skip in the sequence.

        Returns
        -------
        engine : Sobol
            The fast-forwarded engine.

        r   r   )r   r@  r2  r<  rA  )r   r   rH   r5  r8  r   r3   r3   r5   r      s    
zSobol.fast_forward)r   )r   r   r  r  r   r,  __annotations__r   r7  r   rF  r   r   r  r3   r3   r  r5   r)     s   
  2 :r)   c                	      s   e Zd ZdZddddddddd	dd
ddd fddZdd Zd"ddddddddZddddZd d fddZd#dddddddZ	d$dddddd d!Z
  ZS )%r,   a  Poisson disk sampling.

    Parameters
    ----------
    d : int
        Dimension of the parameter space.
    radius : float
        Minimal distance to keep between points when sampling new candidates.
    hypersphere : {"volume", "surface"}, optional
        Sampling strategy to generate potential candidates to be added in the
        final sample. Default is "volume".

        * ``volume``: original Bridson algorithm as described in [1]_.
          New candidates are sampled *within* the hypersphere.
        * ``surface``: only sample the surface of the hypersphere.
    ncandidates : int
        Number of candidates to sample per iteration. More candidates result
        in a denser sampling as more candidates can be accepted per iteration.
    optimization : {None, "random-cd", "lloyd"}, optional
        Whether to use an optimization scheme to improve the quality after
        sampling. Note that this is a post-processing step that does not
        guarantee that all properties of the sample will be conserved.
        Default is None.

        * ``random-cd``: random permutations of coordinates to lower the
          centered discrepancy. The best sample based on the centered
          discrepancy is constantly updated. Centered discrepancy-based
          sampling shows better space-filling robustness toward 2D and 3D
          subprojections compared to using other discrepancy measures.
        * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm.
          The process converges to equally spaced samples.

        .. versionadded:: 1.10.0
    seed : {None, int, `numpy.random.Generator`}, optional
        If `seed` is an int or None, a new `numpy.random.Generator` is
        created using ``np.random.default_rng(seed)``.
        If `seed` is already a ``Generator`` instance, then the provided
        instance is used.

    Notes
    -----
    Poisson disk sampling is an iterative sampling strategy. Starting from
    a seed sample, `ncandidates` are sampled in the hypersphere
    surrounding the seed. Candidates below a certain `radius` or outside the
    domain are rejected. New samples are added in a pool of sample seed. The
    process stops when the pool is empty or when the number of required
    samples is reached.

    The maximum number of point that a sample can contain is directly linked
    to the `radius`. As the dimension of the space increases, a higher radius
    spreads the points further and help overcome the curse of dimensionality.
    See the :ref:`quasi monte carlo tutorial <quasi-monte-carlo>` for more
    details.

    .. warning::

       The algorithm is more suitable for low dimensions and sampling size
       due to its iterative nature and memory requirements.
       Selecting a small radius with a high dimension would
       mean that the space could contain more samples than using lower
       dimension or a bigger radius.

    Some code taken from [2]_, written consent given on 31.03.2021
    by the original author, Shamis, for free use in SciPy under
    the 3-clause BSD.

    References
    ----------
    .. [1] Robert Bridson, "Fast Poisson Disk Sampling in Arbitrary
       Dimensions." SIGGRAPH, 2007.
    .. [2] `StackOverflow <https://stackoverflow.com/questions/66047540>`__.

    Examples
    --------
    Generate a 2D sample using a `radius` of 0.2.

    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from matplotlib.collections import PatchCollection
    >>> from scipy.stats import qmc
    >>>
    >>> rng = np.random.default_rng()
    >>> radius = 0.2
    >>> engine = qmc.PoissonDisk(d=2, radius=radius, seed=rng)
    >>> sample = engine.random(20)

    Visualizing the 2D sample and showing that no points are closer than
    `radius`. ``radius/2`` is used to visualize non-intersecting circles.
    If two samples are exactly at `radius` from each other, then their circle
    of radius ``radius/2`` will touch.

    >>> fig, ax = plt.subplots()
    >>> _ = ax.scatter(sample[:, 0], sample[:, 1])
    >>> circles = [plt.Circle((xi, yi), radius=radius/2, fill=False)
    ...            for xi, yi in sample]
    >>> collection = PatchCollection(circles, match_original=True)
    >>> ax.add_collection(collection)
    >>> _ = ax.set(aspect='equal', xlabel=r'$x_1$', ylabel=r'$x_2$',
    ...            xlim=[0, 1], ylim=[0, 1])
    >>> plt.show()

    Such visualization can be seen as circle packing: how many circle can
    we put in the space. It is a np-hard problem. The method `fill_space`
    can be used to add samples until no more samples can be added. This is
    a hard problem and parameters may need to be adjusted manually. Beware of
    the dimension: as the dimensionality increases, the number of samples
    required to fill the space increases exponentially
    (curse-of-dimensionality).

    g?volumer/  N)radiushyperspherencandidatesr   r0   r   r   zLiteral['volume', 'surface']r   r   r   )rH   rJ  rK  rL  r   r0   r1   c          
   
     s  |||||d| _ t j|||d | j| jd}z|| | _W n@ ty } z(|dt|}	t|	|W Y d }~n
d }~0 0 |dkrdnd| _	|| _
| j
d | _|| _tjdd	D | j
t| j | _tt| j| j t| _W d    n1 s0    Y  |   d S )
N)rH   rJ  rK  rL  r   r  )rI  Zsurfacez? is not a valid hypersphere sampling method. It must be one of rI  rF   gjt?ignore)divide)r  r	  r   _hypersphere_volume_sample_hypersphere_surface_samplehypersphere_methodr  rd   r>   radius_factorrJ  radius_squaredrL  r:   errstater#  rH   	cell_sizer   r   r   ru   	grid_size_initialize_grid_pool)
r   rH   rJ  rK  rL  r   r0   Zhypersphere_sampler  r   r  r3   r5   r     s8     &zPoissonDisk.__init__c                 C  s6   g | _ tjt| j| jtjd| _| jtj	 dS )zSampling pool and sample grid.r|   N)
sample_poolr:   r'  appendrV  rH   Zfloat32sample_gridfillnanrG  r3   r3   r5   rW    s    z!PoissonDisk._initialize_grid_poolr   rb   rB   r   c                  s0  |dksj dkr"t|j fS ddddd}ddddd	fd
d}ddd fdd}g  tjdkr|jj  d}nd}tjr||k rtjtj}j| }j|= |j	j
 j}	|	D ]0}
||
r||
s||
 |d7 }||kr qqq j|7  _t S )a  Draw `n` in the interval ``[0, 1]``.

        Note that it can return fewer samples if the space is full.
        See the note section of the class.

        Parameters
        ----------
        n : int, optional
            Number of samples to generate in the parameter space. Default is 1.

        Returns
        -------
        sample : array_like (n, d)
            QMC sample.

        r   rB   rA   rU   c                 S  s   |   dko|  dkS )NrI   rJ   )rP   rQ   r[   r3   r3   r5   	in_limits  s    z&PoissonDisk._random.<locals>.in_limitsrF   ru   )	candidater   r1   c              
     s   | j  t}t|| tjjtdt|| d j t	j
t| d s^dS  fddtjD }tjddP ttjt| j
t|  jd	jk rW d
   dS W d
   n1 s0    Y  dS )zz
            Check if there are samples closer than ``radius_squared`` to the
            `candidate` sample.
            r|   r   r   Tc                   s   g | ]}t |  | qS r3   )slicer  r   Zind_maxZind_minr3   r5   r    r  z@PoissonDisk._random.<locals>.in_neighborhood.<locals>.<listcomp>rM  )invalidr{   NF)rU  r   ru   r:   maximumr$  rH   minimumrV  isnanrZ  tupler   rT  rn   r   ZsquarerS  )r^  r   indicesarG  ra  r5   in_neighborhood  s"    .z,PoissonDisk._random.<locals>.in_neighborhoodr   )r^  r1   c                   s8   j |  | j t}| jt|<  |  d S r2   )rX  rY  rU  r   ru   rZ  rf  )r^  rg  Zcurr_sampler   r3   r5   
add_sample  s    z'PoissonDisk._random.<locals>.add_sampler   )rF   )rH   r:   r'  r   rX  r   r<   r   rQ  rJ  rR  rL  r   r  )r   r   r`   r]  ri  rk  Z	num_drawnZ
idx_centercenter
candidatesr^  r3   rj  r5   r     s2    
zPoissonDisk._randomr   c                 C  s   |  tjS )a  Draw ``n`` samples in the interval ``[0, 1]``.

        Unlike `random`, this method will try to add points until
        the space is full. Depending on ``candidates`` (and to a lesser extent
        other parameters), some empty areas can still be present in the sample.

        .. warning::

           This can be extremely slow in high dimensions or if the
           ``radius`` is very small-with respect to the dimensionality.

        Returns
        -------
        sample : array_like (n, d)
            QMC sample.

        )r<   r:   infrG  r3   r3   r5   
fill_spaceE  s    zPoissonDisk.fill_spacec                   s   t    |   | S )zReset the engine to base state.

        Returns
        -------
        engine : PoissonDisk
            Engine reset to its base state.

        )r	  r   rW  rG  r  r3   r5   r   Y  s    	
zPoissonDisk.reset)rl  rJ  rm  r1   c           	      C  s   | j j|| jfd}tj|d dd}|t| jd |d d| j   t| }t|ddd| jf}|t	|| }|S )z$Uniform sampling within hypersphere.r  rF   r   r{   r"  )
r   standard_normalrH   r:   r   r   r#  r  r  multiply)	r   rl  rJ  rm  xZssqfrZfr_tiledr)  r3   r3   r5   rO  f  s    ,z&PoissonDisk._hypersphere_volume_samplec                 C  sH   | j j|| jfd}|tjj|dddddf  }|t|| }|S )z.Uniform sampling on the hypersphere's surface.r  r   r{   N)r   rp  rH   r:   linalgnormrq  )r   rl  rJ  rm  Zvecr)  r3   r3   r5   rP  u  s     z'PoissonDisk._hypersphere_surface_sample)r   )r   )r   )r   r   r  r  r   rW  r   ro  r   rO  rP  r  r3   r3   r  r5   r,   <  s$   s"1 \  r,   c                
   @  sl   e Zd ZdZdddddddddddd	d
dddZddddddZdddddZddddddZdS )r.   aj  QMC sampling from a multivariate Normal :math:`N(\mu, \Sigma)`.

    Parameters
    ----------
    mean : array_like (d,)
        The mean vector. Where ``d`` is the dimension.
    cov : array_like (d, d), optional
        The covariance matrix. If omitted, use `cov_root` instead.
        If both `cov` and `cov_root` are omitted, use the identity matrix.
    cov_root : array_like (d, d'), optional
        A root decomposition of the covariance matrix, where ``d'`` may be less
        than ``d`` if the covariance is not full rank. If omitted, use `cov`.
    inv_transform : bool, optional
        If True, use inverse transform instead of Box-Muller. Default is True.
    engine : QMCEngine, optional
        Quasi-Monte Carlo engine sampler. If None, `Sobol` is used.
    seed : {None, int, `numpy.random.Generator`}, optional
        Used only if `engine` is None.
        If `seed` is an int or None, a new `numpy.random.Generator` is
        created using ``np.random.default_rng(seed)``.
        If `seed` is already a ``Generator`` instance, then the provided
        instance is used.

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> from scipy.stats import qmc
    >>> dist = qmc.MultivariateNormalQMC(mean=[0, 5], cov=[[1, 0], [0, 1]])
    >>> sample = dist.random(512)
    >>> _ = plt.scatter(sample[:, 0], sample[:, 1])
    >>> plt.show()

    NT)cov_rootinv_transformenginer0   r@   r   rA   QMCEngine | Noner   r   )rr   covrv  rw  rx  r0   r1   c                C  s  t t |}|jd }|d urt t |}|jd |jd ksNtdt || sftdzt j	| }W n\ t jj
y   t j|\}}	t |dkstdt |dd }|	t |  }Y n0 n8|d urt |}|jd |jd kstdnd }|| _|s2dt|d  }
n|}
|d u rTt|
dd	|d
| _n0t|tr||j|
krttd|| _ntd|| _|| _|| _d S )Nr   z/Dimension mismatch between mean and covariance.z#Covariance matrix is not symmetric.g:0yEzCovariance matrix not PSD.rJ   rF   Tr/  rH   r   r-  r0   zDimension of `engine` must be consistent with dimensions of mean and covariance. If `inv_transform` is False, it must be an even number.F`engine` must be an instance of `scipy.stats.qmc.QMCEngine` or `None`.)r:   rL   r   rO   Z
atleast_2dr>   ZallcloseZ	transposert  ZcholeskyZLinAlgErrorZeighrR   Zclipr#  _inv_transformr   r   r)   rx  r7   r(   rH   _mean_corr_matrix_d)r   rr   rz  rv  rw  rx  r0   rH   ZeigvalZeigvecZ
engine_dimr3   r3   r5   r     sJ    





zMultivariateNormalQMC.__init__r   r   rB   r   c                 C  s   |  |}| |S )a%  Draw `n` QMC samples from the multivariate Normal.

        Parameters
        ----------
        n : int, optional
            Number of samples to generate in the parameter space. Default is 1.

        Returns
        -------
        sample : array_like (n, d)
            Sample.

        )_standard_normal_samples
_correlate)r   r   base_samplesr3   r3   r5   r<     s    
zMultivariateNormalQMC.random)r  r1   c                 C  s(   | j d ur|| j  | j S || j S d S r2   )r  r~  )r   r  r3   r3   r5   r    s    
z MultivariateNormalQMC._correlatec           	      C  s   | j |}| jr*tjdd|d   S td|jd d}t	dt
|dd|f  }dtj |ddd| f  }t|}t|}t|| || gd|d}|ddd| jf S dS )	a3  Draw `n` QMC samples from the standard Normal :math:`N(0, I_d)`.

        Parameters
        ----------
        n : int, optional
            Number of samples to generate in the parameter space. Default is 1.

        Returns
        -------
        sample : array_like (n, d)
            Sample.

        rz   gA?r   r"  rF   r!  Nr   )rx  r<   r}  statsru  Zppfr:   r   rO   r#  logr   picossinr%  r  r  )	r   r   r  ZevenZRsZthetasr  r  Ztransf_samplesr3   r3   r5   r    s     

z.MultivariateNormalQMC._standard_normal_samples)N)r   )r   )r   r   r  r  r   r<   r  r  r3   r3   r3   r5   r.     s   # Ar.   c                   @  s@   e Zd ZdZddddddddd	d
dZddddddZdS )r-   a9  QMC sampling from a multinomial distribution.

    Parameters
    ----------
    pvals : array_like (k,)
        Vector of probabilities of size ``k``, where ``k`` is the number
        of categories. Elements must be non-negative and sum to 1.
    n_trials : int
        Number of trials.
    engine : QMCEngine, optional
        Quasi-Monte Carlo engine sampler. If None, `Sobol` is used.
    seed : {None, int, `numpy.random.Generator`}, optional
        Used only if `engine` is None.
        If `seed` is an int or None, a new `numpy.random.Generator` is
        created using ``np.random.default_rng(seed)``.
        If `seed` is already a ``Generator`` instance, then the provided
        instance is used.

    Examples
    --------
    Let's define 3 categories and for a given sample, the sum of the trials
    of each category is 8. The number of trials per category is determined
    by the `pvals` associated to each category.
    Then, we sample this distribution 64 times.

    >>> import matplotlib.pyplot as plt
    >>> from scipy.stats import qmc
    >>> dist = qmc.MultinomialQMC(
    ...     pvals=[0.2, 0.4, 0.4], n_trials=10, engine=qmc.Halton(d=1)
    ... )
    >>> sample = dist.random(64)

    We can plot the sample and verify that the median of number of trials
    for each category is following the `pvals`. That would be
    ``pvals * n_trials = [2, 4, 4]``.

    >>> fig, ax = plt.subplots()
    >>> ax.yaxis.get_major_locator().set_params(integer=True)
    >>> _ = ax.boxplot(sample)
    >>> ax.set(xlabel="Categories", ylabel="Trials")
    >>> plt.show()

    N)rx  r0   r@   r   ry  r   r   )pvalsn_trialsrx  r0   r1   c                C  s   t t || _t |dk r(tdt t |dsBtd|| _|d u rdt	ddd|d| _
n,t|tr|jdkrtd|| _
ntd	d S )
Nr   z'Elements of pvals must be non-negative.r   z Elements of pvals must sum to 1.Tr/  r{  z Dimension of `engine` must be 1.r|  )r:   r   rL   r  rQ   r>   iscloser   r  r)   rx  r7   r(   rH   )r   r  r  rx  r0   r3   r3   r5   r   J	  s    


zMultinomialQMC.__init__r   rB   r   c                 C  s   t |t| jf}t|D ]b}| j| j }t j	| jt
d}tt j| jt
d| t j| jt jd}t||| |||< q|S )a/  Draw `n` QMC samples from the multinomial distribution.

        Parameters
        ----------
        n : int, optional
            Number of samples to generate in the parameter space. Default is 1.

        Returns
        -------
        samples : array_like (n, pvals)
            Sample.

        r|   )r:   r'  r   r  r   rx  r<   r  Zravel
empty_likera   r   r  Z
zeros_likeZintpr   )r   r   rC   r   Z
base_drawsZp_cumulativeZsample_r3   r3   r5   r<   a	  s    
zMultinomialQMC.random)r   )r   r   r  r  r   r<   r3   r3   r3   r5   r-   	  s
   .r-   r   dictzCallable | None)r   r   r1   c              
   C  s   t td}| durzz|  } ||  }W n@ tyf } z(| dt|}t||W Y d}~n
d}~0 0 t|fi |}nd}|S )z#A factory for optimization methods.)z	random-cdZlloydNz7 is not a valid optimization method. It must be one of )
_random_cd&_lloyd_centroidal_voronoi_tessellationrS   r  rd   r>   r   )r   r   r   Z
optimizer_r  r   Z	optimizerr3   r3   r5   r   z	  s     r   )best_sampler   r   r   kwargsr1   c                 K  s6  ~| j \}}|dks|dkr*t||fS |dks:|dkr>| S t| }d|d gd|d gd|d gf}d}	d}
|	|k r2|
|k r2|
d7 }
t|g|d R ddi}t|g|d R ddi}t|g|d R ddi}t| ||||}||k r(| ||f | ||f  | ||f< | ||f< |}d}	qp|	d7 }	qp| S )a  Optimal LHS on CD.

    Create a base LHS and do random permutations of coordinates to
    lower the centered discrepancy.
    Because it starts with a normal LHS, it also works with the
    `scramble` keyword argument.

    Two stopping criterion are used to stop the algorithm: at most,
    `n_iters` iterations are performed; or if there is no improvement
    for `n_nochange` consecutive iterations.
    r   r   r   TrF   )rO   r:   r'  r%   r   r   )r  r   r   r   r  r   rH   Z	best_discZboundsZn_nochange_Zn_iters_colZrow_1Zrow_2ry   r3   r3   r5   r  	  s:    





r  c                 C  s   t | d S )NZ	cityblock)r   rm   rQ   r[   r3   r3   r5   _l1_norm	  s    r  )rC   decayr   r1   c                 C  s   t | }t| |d}t|jD ]P\}}dd |j| D }|j| }t j|dd}	| | |	| |  |  ||< q t jt 	|dk|dkdd}
||
 | |
< | S )uf  Lloyd-Max algorithm iteration.

    Based on the implementation of Stéfan van der Walt:

    https://github.com/stefanv/lloyd

    which is:

        Copyright (c) 2021-04-21 Stéfan van der Walt
        https://github.com/stefanv/lloyd
        MIT License

    Parameters
    ----------
    sample : array_like (n, d)
        The sample to iterate on.
    decay : float
        Relaxation decay. A positive value would move the samples toward
        their centroid, and negative value would move them away.
        1 would move the samples to their centroid.
    qhull_options : str
        Additional options to pass to Qhull. See Qhull manual
        for details. (Default: "Qbb Qc Qz Qj Qx" for ndim > 4 and
        "Qbb Qc Qz Qj" otherwise.)

    Returns
    -------
    sample : array_like (n, d)
        The sample after an iteration of Lloyd's algorithm.

    )r   c                 S  s   g | ]}|d kr|qS )r"  r3   r`  r3   r3   r5   r  	  r  z$_lloyd_iteration.<locals>.<listcomp>r   r{   r   )
r:   r  r   r  Zpoint_regionZregionsZverticesrr   rR   logical_and)rC   r  r   Z
new_sampleZvoronoiiir+  regionZvertsZcentroidZis_validr3   r3   r5   _lloyd_iteration	  s    $

r  r   r   )r   r   r   z
str | None)rC   r   r   r   r  r1   c          	        s   ~t |  } | jdks"td| jd dks8td|  dksP|  dk rXtd|du rzd	}| jd d
krz|d7 }| t d   fddt	|D }t
| d}t	|D ]:}t| || |d} t
| d}t|| |k r qq|}q| S )a  Approximate Centroidal Voronoi Tessellation.

    Perturb samples in N-dimensions using Lloyd-Max algorithm.

    Parameters
    ----------
    sample : array_like (n, d)
        The sample to iterate on. With ``n`` the number of samples and ``d``
        the dimension. Samples must be in :math:`[0, 1]^d`, with ``d>=2``.
    tol : float, optional
        Tolerance for termination. If the min of the L1-norm over the samples
        changes less than `tol`, it stops the algorithm. Default is 1e-5.
    maxiter : int, optional
        Maximum number of iterations. It will stop the algorithm even if
        `tol` is above the threshold.
        Too many iterations tend to cluster the samples as a hypersphere.
        Default is 10.
    qhull_options : str, optional
        Additional options to pass to Qhull. See Qhull manual
        for details. (Default: "Qbb Qc Qz Qj Qx" for ndim > 4 and
        "Qbb Qc Qz Qj" otherwise.)

    Returns
    -------
    sample : array_like (n, d)
        The sample after being processed by Lloyd-Max algorithm.

    Notes
    -----
    Lloyd-Max algorithm is an iterative process with the purpose of improving
    the dispersion of samples. For given sample: (i) compute a Voronoi
    Tessellation; (ii) find the centroid of each Voronoi cell; (iii) move the
    samples toward the centroid of their respective cell. See [1]_, [2]_.

    A relaxation factor is used to control how fast samples can move at each
    iteration. This factor is starting at 2 and ending at 1 after `maxiter`
    following an exponential decay.

    The process converges to equally spaced samples. It implies that measures
    like the discrepancy could suffer from too many iterations. On the other
    hand, L1 and L2 distances should improve. This is especially true with
    QMC methods which tend to favor the discrepancy over other criteria.

    .. note::

        The current implementation does not intersect the Voronoi Tessellation
        with the boundaries. This implies that for a low number of samples,
        empirically below 20, no Voronoi cell is touching the boundaries.
        Hence, samples cannot be moved close to the boundaries.

        Further improvements could consider the samples at infinity so that
        all boundaries are segments of some Voronoi cells. This would fix
        the computation of the centroid position.

    .. warning::

       The Voronoi Tessellation step is expensive and quickly becomes
       intractable with dimensions as low as 10 even for a sample
       of size as low as 1000.

    .. versionadded:: 1.9.0

    References
    ----------
    .. [1] Lloyd. "Least Squares Quantization in PCM".
       IEEE Transactions on Information Theory, 1982.
    .. [2] Max J. "Quantizing for minimum distortion".
       IEEE Transactions on Information Theory, 1960.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.spatial import distance
    >>> from scipy.stats._qmc import _lloyd_centroidal_voronoi_tessellation
    >>> rng = np.random.default_rng()
    >>> sample = rng.random((128, 2))

    .. note::

        The samples need to be in :math:`[0, 1]^d`. `scipy.stats.qmc.scale`
        can be used to scale the samples from their
        original bounds to :math:`[0, 1]^d`. And back to their original bounds.

    Compute the quality of the sample using the L1 criterion.

    >>> def l1_norm(sample):
    ...    return distance.pdist(sample, 'cityblock').min()

    >>> l1_norm(sample)
    0.00161...  # random

    Now process the sample using Lloyd's algorithm and check the improvement
    on the L1. The value should increase.

    >>> sample = _lloyd_centroidal_voronoi_tessellation(sample)
    >>> l1_norm(sample)
    0.0278...  # random

    rF   z`sample` is not a 2D arrayr   z`sample` dimension is not >= 2rI   rJ   z!`sample` is not in unit hypercubeNzQbb Qc Qz QJr   z Qxg?c                   s    g | ]}t |   d  qS )g?)r:   exp)r  rr  rootr3   r5   r  
  r  z:_lloyd_centroidal_voronoi_tessellation.<locals>.<listcomp>r[   )rC   r  r   )r:   rL   r   rM   r>   rO   rP   rQ   r  r   r  r  r~   )	rC   r   r   r   r  r  Zl1_oldr   Zl1_newr3   r  r5   r  
  s2    k


r  )r`   r1   c                 C  sF   t | } | dkr*t } | du rBtdn| dkrBtd|  d| S )a@  Validate `workers` based on platform and value.

    Parameters
    ----------
    workers : int, optional
        Number of workers to use for parallel processing. If -1 is
        given all CPU threads are used. Default is 1.

    Returns
    -------
    Workers : int
        Number of CPU used by the algorithm

    r"  NzaCannot determine the number of cpus using os.cpu_count(), cannot use -1 for the number of workersr   zInvalid number of workers: z, must be -1 or > 0)ru   os	cpu_countNotImplementedErrorr>   rb   r3   r3   r5   rc   
  s    rc   ztuple[np.ndarray, ...])rD   rE   rH   r1   c              
   C  sn   zt | |}t ||}W n2 tyN } zd}t||W Y d}~n
d}~0 0 t ||k sftd||fS )a  Bounds input validation.

    Parameters
    ----------
    l_bounds, u_bounds : array_like (d,)
        Lower and upper bounds.
    d : int
        Dimension to use for broadcasting.

    Returns
    -------
    l_bounds, u_bounds : array_like (d,)
        Lower and upper bounds.

    zP'l_bounds' and 'u_bounds' must be broadcastable and respect the sample dimensionNz1Bounds are not consistent 'l_bounds' < 'u_bounds')r:   Zbroadcast_tor>   rR   )rD   rE   rH   rS   rT   r  rC  r3   r3   r5   rN   
  s     rN   ).)N)rf   rg   )rF   )r   )Qr  
__future__r   r   r   r8   r  ro   abcr   r   	functoolsr   typingr   r   r   r	   r
   numpyr:   Znumpy.typingZnptZscipy._lib._utilr   r   r   r   Zscipy.statsr  r   r   Zscipy.sparse.csgraphr   Zscipy.spatialr   r   Zscipy.specialr   Z_sobolr   r   r   r   r   r   r   Z_qmc_cyr   r   r   r    r!   r"   r#   __all__r6   r$   r\   r%   r&   r'   r   r   r   r   r   r(   r*   r+   r)   r,   r.   r-   r   r  r  r  r  rc   rN   r3   r3   r3   r5   <module>   s   $$
S! 
  }=Z ((  E  "     S  F ]7C 