L i"dZddlZddlZddlZddlZddlZddlmZmZddl m Z ddl m Z m Z mZmZddlmZddlZddlmZmZmZmZerddlm ZddlmZddlmZmZmZdd l m!Z!dd l"m#Z#m$Z$dd l%m&Z&d d l'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.d dl/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6gdZ7edbdedzdejpjrfdZ:ededefdZ:dcdZ:ddddddddde;dejxf dZ=dddejxfdZ>ddd dddd e;d!e d"d#ede?f d$Z@ ddddd!e d%d&eAde?fd'ZBd(dddd)ede?fd*ZCdejxd+eDd,eDd-eDd.e?f d/ZEd0eDdejxfd1ZFd0edeGeDfd2ZHdd3d4ed5edejxfd6ZI deddddd d7d0ed4ed8ed9e;d:d;d5ed#edejxfd<ZJGd=d>eZKGd?d@eKZLGdAdBeKZMGdCdDeKZNGdEdFeKZOGdGdHZPGdIdJZQdKe dLdzdMeRdedzfdNZSdOejxdPeDdQeDd5edReRdejxf dSZTdejxde?fdTZUdejxdUe?dVeAdejxfdWZVdXdYddZddd[ed\edVeAdzdReRdejxf d]ZWdfd#edefd^ZXddddd_eDdd`fdaZYy)gz&Quasi-Monte Carlo engines and helpers.N)ABCabstractmethod)partial)ClassVarLiteraloverload TYPE_CHECKING)Callable) DecimalNumber GeneratorType IntNumberSeedType) rng_integers _rng_spawn_transition_to_rng)minimum_spanning_tree)distanceVoronoi)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 discrepancygeometric_discrepancyupdate_discrepancy QMCEngineSobolHaltonLatinHypercube PoissonDiskMultinomialQMCMultivariateNormalQMCseedreturncyNr0s V/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/stats/_qmc.pycheck_random_stater71cyr3r4r5s r6r7r76r8r9c8|+t|tjtjzrtj j |St|tj jtj jzr|St|d)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. z9 cannot be used to seed a numpy.random.Generator instance) isinstancenumbersIntegralnpintegerrandom default_rng RandomState Generator ValueErrorr5s r6r7r7>sy" |z$(8(82::(EFyy$$T** D"))//"))2E2EE F D8$<<= =r9F)reversesample npt.ArrayLikel_boundsu_boundsrFctj|}|jdk(s tdt |||j d\}}|s<|j dkDs|jdkr td|||z z|zStj||k\rtj||ks td||z ||z z S) aSample 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 arrayrrIrJd?Sample is not in unit hypercubezSample is out of bounds) r?asarrayndimrE_validate_boundsshapemaxminall)rGrIrJrFloweruppers r6r%r%XsvZZ F ;;! 344#H QLE5  JJL2 6::<"#4>? ?'%//v'BFF6U?,C67 755=11r9ctj|tjd}|jdk(s t d|j dkDs|j dkr t d|S)aEnsure 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. CdtypeorderrLrMrPrQrR)r?rSfloat64rTrErWrXrGs r6_ensure_in_unit_hypercubercs^&ZZbjj >> 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 rhrgz* is not a valid method. It must be one of )rc_validate_workersrrr r!rEset)rGrerfrgmethodss r6r&r&srp'v .F(G/1-2 Gwvvy'BBF:& \,./ /r9)mindistmstmetricct|}|jddkr tdtj||}t j |dk(rtjdd|dk(r&t j||jS|d k(rHtj|}t|}||j}t j|St|d ) alDiscrepancy 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, rng=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() rrLz'Sample must contain at least two points)rrrQz!Sample contains duplicate points. stacklevelrprqz< is not a valid method. It must be one of {'mindist', 'mst'})rcrVrErpdistr?anywarningswarnrXnonzero squareformrmean)rGrfrr distancesfully_connected_graphrqs r6r'r'SsL'v .F ||ABCCvf5I vvi3 9aH vvi 1 1 3455 5 ( 3 3I >#$9: & wwy!!F:&BCD Dr9x_new initial_disccHtj|tjd}tj|tjd}|jdk(s t d|j dkDs|j dkr t d|jdk(s t d tj|d k\rtj|dks t d |jd |jdk7r t d t|||S) aUpdate 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 r]r^rLrMrPrQrRrzx_new is not a 1D arrayrzx_new is not in unit hypercubez&x_new and sample must be broadcastable) r?rSrarTrErWrXrYrVr")rrGrs r6r(r(sLZZbjj 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?rPg@NraxisrLr_F)rVr?prodabsonesboolsum)rGrrrrnz_ijc_i1jc_i2jc_i1i1c_i2i2numdenumgammac_p_i1jc_p_i2jalphabetag_i1g_i2h_i1h_i2c_p_i1i1c_p_i2i2sum_maskdisc_eps r6_perturb_discrepancyr siB  QA C= 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 `_. rLrrrFNr)r?rrrangeintr_rz)rsieveirs r6primes_from_2_torgs0 GGAFa!eqj) 6E 1c!s(mq(1, -= EAIM#(a!eqj!a% 7<a1qAE{?Q&'1,3a!e34= 55ARZZ.q1!"559Q>? @@r9cgdd|}t||kr(d} t|d|}t||k(r |S|dz }%|S)zList of the n-first prime numbers. Parameters ---------- n : int Number of prime numbers wanted. Returns ------- primes : list(int) List of primes. )rLr %)+/5;=CGIOSYaegkmqiii iiiii%i3i7i9i=iKiQi[i]iaigioiui{iiiiiiiiiiiiiiiiiiiiiii i ii#i-i3i9i;iAiKiQiWiYi_ieiiikiwiiiiiiiiiiiiiiiiiiiiiiiii)i+i5i7i;i=iGiUiYi[i_imiqisiwiiiiiiiiiiiiiiNii)lenr)rprimes big_numbers r6n_primesrsi 124! 5F 6{Q !%j1"15F6{a M $ J " Mr9)rngbaserct|}tjdtj|z dz }t j t j |d|d}|D]}|j||S)aPermutations for scrambling a Van der Corput sequence. Parameters ---------- base : int Base of the sequence. rng : `numpy.random.Generator`, optional Pseudorandom number generator state. When `rng` is None, a new `numpy.random.Generator` is created using entropy from the operating system. Types other than `numpy.random.Generator` are passed to `numpy.random.default_rng` to instantiate a ``Generator``. .. versionchanged:: 1.15.0 As part of the `SPEC-007 `_ transition from use of `numpy.random.RandomState` to `numpy.random.Generator`, this keyword was changed from `seed` to `rng`. During the transition, the behavior documented above is not accurate; see `check_random_state` for actual behavior. After the transition, this admonition can be removed. 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. 6rNrr)r7mathceillog2r?repeatarangeshuffle)rrcount permutationsperms r6_van_der_corput_permutationsrsqL S !C IIb499T?* +a /E99RYYt_T2EBL D r9) start_indexscramblerrrgrrrnpt.ArrayLike | Nonec|dkr td|rS|t||}ntj|}|j tj }t |||||St||||S)aVan 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. rng : `numpy.random.Generator`, optional Pseudorandom number generator state. When `rng` is None, a new `numpy.random.Generator` is created using entropy from the operating system. Types other than `numpy.random.Generator` are passed to `numpy.random.default_rng` to instantiate a ``Generator``. 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. rLz'base' must be at least 2rr)rErr?rSastypeint64r#r$)rrrrrrrgs r6van_der_corputrsd ax455  7sL::l3L#**2884 +At[,8'C C"!T;@@r9c ReZdZdZeeddddddeded dzd ed dfd Z ddddeded dzd ed dfd Z e ddddeded e jfdZ ddddeded e jfdZddddddddddededed e jf dZddZded dfdZy)r)aA 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 rng : `numpy.random.Generator`, optional Pseudorandom number generator state. When `rng` is None, a new `numpy.random.Generator` is created using entropy from the operating system. Types other than `numpy.random.Generator` are passed to `numpy.random.default_rng` to instantiate a ``Generator``. .. versionchanged:: 1.15.0 As part of the `SPEC-007 `_ transition from use of `numpy.random.RandomState` to `numpy.random.Generator`, this keyword was changed from `seed` to `rng`. For an interim period, both keywords will continue to work, although only one may be specified at a time. After the interim period, function calls using the `seed` keyword will emit warnings. Following a deprecation period, the `seed` keyword will be removed. 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. **Subclassing** When subclassing `QMCEngine` to create a new sampler, ``__init__`` and ``random`` must be redefined. * ``__init__(d, rng=None)``: at least fix the dimension. If the sampler does not take advantage of a ``rng`` (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, rng=None): ... super().__init__(d=d, rng=rng) ... ... ... def _random(self, n=1, *, workers=1): ... return self.rng.random((n, self.d)) ... ... ... def reset(self): ... super().__init__(d=self.d, rng=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]]) r0F replace_docN optimizationrrOrz random-cdlloydrr1c,|j|||y)Nr) _initialize)selfrOrrs r6__init__zQMCEngine.__init__s 3?r9ctjt|tjr|dkr t d||_t |tjjrt|dd|_ nt||_ tj|j|_d|_dd|jdddd}||_t#|||_y) Nrz&d must be a non-negative integer valuerdi'h㈵> ) n_nochangen_itersrtolmaxiter qhull_options)r? issubdtypetyper@rErOr<rArDrrr7copydeepcopyrng_seed num_generated _optimization_select_optimizeroptimization_method)r rOrrconfigs r6rzQMCEngine._initializes}}T!Wbjj1QUEF F c299.. /!#q)!,DH*#.DH dhh/ 88!  *#4\6#J r9rrlrrgcyr3r4)r rrgs r6_randomzQMCEngine._randoms r9c|j||}|j|j|}|xj|z c_|S)aMDraw `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. rl)rrr)r rrgrGs r6rAzQMCEngine.randomsH,a1  # # /--f5F a r9)rJrendpointrgrIrHrJrr!c2||}d}tj|}tj|}|r|dz}tj|jtjr.tj|jtjs d}t |t |tr|j||}n|j|}t|||}tj|jtj}|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) rrzD'u_bounds' and 'l_bounds' must be integers or array-like of integers)rrgr)rIrJ) r? atleast_1drr_r@rEr<r+rAr%floorrr)r rIrJrr!rgmessagerGs r6integerszQMCEngine.integerssp  HH==*==* !|H hnnbjj9MM(.."**=1GW% % dF #[[1g[6F[[1[%Fv8D&!((2 r9crtj|j}t||_d|_|S)zReset the engine to base state. Returns ------- engine : QMCEngine Engine reset to its base state. r)rrrr7rr)r rs r6resetzQMCEngine.reset=s/mmDMM*%c* r9c*|j||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#)rAr rs r6 fast_forwardzQMCEngine.fast_forwardKs a  r9r)r1r))__name__ __module__ __qualname____doc__rrr rrr rr?ndarrayrrArr'r)r,r4r9r6r)r)"sm^E2 >B @ @23d: @  @  @3@&>B #K #K23d: #K  #K  #KJ 89  ,5   89,5 B,0P!P) P  P  PP Pd iKr9r)c eZdZdZeddddddded ed ed dzd ed df fdZ ddZ ddddeded e jfdZ xZS)r+aHalton 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:`p` for its :math:`n`-dimension, with :math:`p` the :math:`n`'th prime. Parameters ---------- d : int Dimension of the parameter space. scramble : bool, optional If True, use random scrambling from [2]_. 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 rng : `numpy.random.Generator`, optional Pseudorandom number generator state. When `rng` is None, a new `numpy.random.Generator` is created using entropy from the operating system. Types other than `numpy.random.Generator` are passed to `numpy.random.default_rng` to instantiate a ``Generator``. .. versionchanged:: 1.15.0 As part of the `SPEC-007 `_ transition from use of `numpy.random.RandomState` to `numpy.random.Generator`, this keyword was changed from `seed` to `rng`. For an interim period, both keywords will continue to work, although only one may be specified at a time. After the interim period, function calls using the `seed` keyword will emit warnings. Following a deprecation period, the `seed` keyword will be removed. 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 applicability 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]]) r0FrTN)rrrrOrrrrr1c|d|d|_t| |||t|Dcgc] }t |c}|_||_|jycc}w)NT)rOrrrOrr) _init_quadsuperrrrrr_initialize_permutations)r rOrrrbdim __class__s r6r zHalton.__init__s^!"t+79 alD,4A;74SY7    %%'8sAcdgt|jz|_|jrDt |jD]+\}}t ||j }||j|<-yy)zxInitialize permutations for all Van der Corput sequences. Permutations are only needed for scrambling. Nr)rr _permutationsr enumeraterr)r rr9rs r6r8zHalton._initialize_permutationssh %)6C N#: ==$TYY/ 54;488  )5""1%  5 r9rrlrrgc Dt|}t|jDcgc]7\}}t|||j|j |j ||9}}}tj|jj||jScc}}w)aDraw `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. )rrrrg) rmr=rrrrr<r?arrayTreshaperO)r rrgrr9rGs r6rzHalton._randoms($G, "+499!5 7a !Dd6H6H*.--.2.@.@.C)0277 xx!!))!TVV44 7s`_ transition from use of `numpy.random.RandomState` to `numpy.random.Generator`, this keyword was changed from `seed` to `rng`. For an interim period, both keywords will continue to work, although only one may be specified at a time. After the interim period, function calls using the `seed` keyword will emit warnings. Following a deprecation period, the `seed` keyword will be removed. See Also -------- :ref:`quasi-monte-carlo` 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] Seaholm, Susan K. et al. (1988). 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` Examples -------- Generate samples from a Latin hypercube generator. >>> from scipy.stats import qmc >>> sampler = qmc.LatinHypercube(d=2) >>> sample = sampler.random(n=5) >>> sample array([[0.1545328 , 0.53664833], # random [0.84052691, 0.06474907], [0.52177809, 0.93343721], [0.68033825, 0.36265316], [0.26544879, 0.61163943]]) Compute the quality of the sample using the discrepancy criterion. >>> qmc.discrepancy(sample) 0.0196... # random Samples can be scaled to bounds. >>> l_bounds = [0, 2] >>> u_bounds = [10, 5] >>> qmc.scale(sample, l_bounds, u_bounds) array([[1.54532796, 3.609945 ], # random [8.40526909, 2.1942472 ], [5.2177809 , 4.80031164], [6.80338249, 3.08795949], [2.65448791, 3.83491828]]) 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. **Real-world example** In [9]_, a Latin Hypercube sampling (LHS) 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. r0FrTrN)rstrengthrrrOrrFrrrr1c|d||d|_t | |||||_|j|j d} |||_y#t$r!}|dt|}t||d}~wwxYw)NT)rOrrFr)rOrr)rrLz, is not a valid strength. It must be one of ) r6r7rr _random_lhs_random_oa_lhs lhs_methodKeyErrorrnrE) r rOrrFrrlhs_method_strengthexcr&r:s r6r zLatinHypercube.__init__s!"t+79 aS|D  ""   /(;H(EDO /"&!"569;GW%3 . /s A A6A11A6rlrrgc(|j|}|Sr3)rJ)r rrglhss r6rzLatinHypercube._randomsooa  r9c|jsd}n(|jj||jf}t j t j d|dz|jdf}t|jD]$}|jj||ddf&|j}||z |z }|S)zBase LHS algorithm.rsizerN) rruniformrOr?tilerrrr@)r rsamplespermsrs r6rHzLatinHypercube._random_lhs s}}*-Ghh&&QK&8G !QU+ %tvv *A HH  U1a4[ ) *7?a'r9ctj|jt}|dz}|dz}t |dz}||vs||k7rt d|dddz|j |dzkDr t dtj||ft}tjtj|d}tjtj|d jd d|ddddf<td|D]9}tj|ddd f||dddfzz||ddd|zdz f<;tj||ft} t|D]0} |j j#|} | |dd| f| dd| f<2| }tj||f } t%d|j&d|j } t|D]V} t|D]F}|dd| f|k(}| j)|j+}||dd| f|z| dd| f|<HX| |z} | ddd|j fS)z)Orthogonal array based LHS of strength 2.rLrz8n is not the square of a prime number. Close values are Nz*n is too small for d. Must be n > (d-1)**2)rVr_)rLrrr)rV)rOrrFr)r?sqrtrrrrErOzerosrTrstackmeshgridrArmodemptyr permutationr,rrAflatten)r rpn_rown_colr oa_samplearraysp_ oa_sample_jrV oa_lhs_sample lhs_engineridxrOs r6rIzLatinHypercube._random_oa_lhssr GGAJ  c "1A!!a%( F?a5j%bc{A~.0  66AE>IJ JHHE5>= 1v.88BKK$8)+--4WR^ !RaR%1+ CB#%66)AqD/,.yA,>+?@A$CIa2ai  C XXUEN#> u 6AHH((+E$Yq!t_5Jq!t  6 u~6 #a$--!(,2 u FA1X F1o* ''*224+.1a41E+E ad#C( F F  QZ((r9r-)r)r.r/r0r1rr rrrrr r?r2rrHrIrCrDs@r6r,r,saFE2=A ////23d: /  /  /3/489,5  Yrzz ,) ,)"**,)r9r,ceZdZUdZeZeeed<e dddddddd e d e d e dzd e d e ddzddf fdZddZ dddde de dej"fdZde dej"fdZdfd Zde ddfdZxZS)r*aIEngine 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 rng : `numpy.random.Generator`, optional Pseudorandom number generator state. When `rng` is None, a new `numpy.random.Generator` is created using entropy from the operating system. Types other than `numpy.random.Generator` are passed to `numpy.random.default_rng` to instantiate a ``Generator``. .. versionchanged:: 1.15.0 As part of the `SPEC-007 `_ transition from use of `numpy.random.RandomState` to `numpy.random.Generator`, this keyword was changed from `seed` to `rng`. For an interim period, both keywords will continue to work, although only one may be specified at a time. After the interim period, function calls using the `seed` keyword will emit warnings. Following a deprecation period, the `seed` keyword will be removed. 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]]) MAXDIMr0FrTN)rbitsrrrOrrorrrr1c|d||d|_t| |||||jkDrt d|jd||_|||_|j d|_|j dkrtj|_ nCd|j cxkrdkr#n t d tj|_ n t d d |j z|_ tj||j f|j |_ t|j||j |s'tj||j |_n|j!|jj#|_d d |j zz |_|j$|j&zj)dd|_|j*j-tj.|_y)NT)rOrrorr5z$Maximum supported dimensionality is . @zMaximum supported 'bits' is 64rLr)dimrorPrrY)r6r7rrnrErorr?uint32dtype_iuint64maxnr[_svr_shift _scrambler_quasi_scalerA _first_pointrra)r rOrrorrr:s r6r zSobol.__init__s!"tT+79 alD t{{?6t{{m1E     99 DI 99?99DL $)) !r !=> >99DL=> >tyyL  "xxDIIdllKdhhADII6&(hhq &EDK NN kk&&( AN* ![[4;;6??2F --44RZZ@r9c tjt|jd|j|j f|j dtj|j |j z|_tjt|jd|j|j |j f|j }t|j|j ||jy)z&Scramble the sequence using LMS+shift.rL)rRr_r)ruroltmsvN) r?dotrrrOrorwrr{trilrrz)r rs r6r|zSobol._scramblesff 1DFFDII+>#|| - 499DLL9 9  ggl488Q)-DII(F)-78 TYY r9rrlrrgc Ztj||jftj}|dk(r|S|j|z}||j kDr\d|j d|j d|jd|jd|d|d }|j d k7r|d z }t||jdk(r||d z zdk(stjd d |d k(r|j}|St|d z |j|j|j|j|j|tj|j|gd|}|St||jd z |j|j|j|j||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. rrz At most 2**=z# distinct points can be generated. 0 points have been previously generated, then: n=+z. rtzConsider increasing `bits`.rzEThe balance properties of Sobol' points require n to be a power of 2.rrt)rnum_genrur%rquasirGN)r?r_rOrarryrorErxryrrr~rzr} concatenate)r rrgrGtotal_nmsgs r6rz Sobol._random&s  XXq$&&kD 6M$$q( TYY dii[$))5"0012&&*&8&8%91#QwirK  yyB44S/ !    "QK1$ 7CDFAv**" !eT%7%7TVV++$(($++! &&/1 T//!3kkdhhdkk   r9mc d|z}|j|z}||dz zdk(s,td|jd|jd|d|d |j|S) aDraw 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. rLrrzFThe balance properties of Sobol' points require n to be a power of 2. rz+2**rzJ. If you still want to do this, the function 'Sobol.random()' can be used.)rrErA)r rrrs r6 random_base2zSobol.random_base2`s" F$$q(7Q;'1,66:6H6H5IJ""&"4"4!5T!AgYG?? {{1~r9cbt||jj|_|S)zReset the engine to base state. Returns ------- engine : Sobol Engine reset to its base state. )r7r)r{rr}r r:s r6r)z Sobol.resets'  kk&&(  r9c<|jdk(r iGr9r*creZdZdZedddddddddd d ed ed ed dededdzdeddddddffdZ dZ d#dddedede jfdZ de jfdZd$fd Z d#de jd ed ede jfd!Z d#de jd ed ede jfd"ZxZS)%r-aPoisson 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 rng : `numpy.random.Generator`, optional Pseudorandom number generator state. When `rng` is None, a new `numpy.random.Generator` is created using entropy from the operating system. Types other than `numpy.random.Generator` are passed to `numpy.random.default_rng` to instantiate a ``Generator``. .. versionchanged:: 1.15.0 As part of the `SPEC-007 `_ transition from use of `numpy.random.RandomState` to `numpy.random.Generator`, this keyword was changed from `seed` to `rng`. For an interim period, both keywords will continue to work, although only one may be specified at a time. After the interim period, function calls using the `seed` keyword will emit warnings. Following a deprecation period, the `seed` keyword will be removed. l_bounds, u_bounds : array_like (d,) Lower and upper bounds of target sample data. 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 ` 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 `__. 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, rng=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). r0Frg?volumerrN)radius hypersphere ncandidatesrrrIrJrOrrrsurfacerrrrrIrrJr1cd|||||d|_t | ||||j|jd} | ||_|dk(rdnd|_ ||_ |jdz|_ ||_ |tj|}|tj|}t!||t#|\|_|_tj(d 5|jtj*|j,z |_tj0|j&|j$z |j.z j3t"|_ddd|j7y#t $r!} |dt| } t| | d} ~ wwxYw#1swYGxYw) N)rOrrrrr5rz? is not a valid hypersphere sampling method. It must be one of rrLgjt?rNignore)divide)r6r7r_hypersphere_volume_sample_hypersphere_surface_samplehypersphere_methodrKrnrE radius_factorrradius_squaredrr?rr[rUrrIrJerrstaterZrO cell_sizerr grid_size_initialize_grid_pool) r rOrrrrrrIrJhypersphere_samplerMr&r:s r6r zPoissonDisk.__init__&s!"V*5*5+79 alD5577   /&8&ED ##."9Qu "kk1n'  wwqzH  xx{H'7CF( $ t}[[ ) ![[277466?:DN6$..HIfSk N  ""$? //"..12D.E-HJ W%3 .  /2  s$ E9BF&9 F#FF#&F/cg|_tjtj|j|j tj |_|jjtjy)zSampling pool and sample grid.rN) sample_poolr?r_appendrrOfloat32 sample_gridfillnanr s r6rz!PoissonDisk._initialize_grid_poolbsT88 IIdnndff -**  bff%r9rrlrrgc |dk(sjdk(r!tj|jfSdtjdtffd }d dtjdt dtffd }dtjddf fd }g t jdk(r9|jjjjd }nd}t jr||krtjt j}j|}j|=j|jjzj } | D](} || s || r|| |d z }||k\s(nt jr||krxj"|z c_tj$ S) aDraw `n` in the interval ``[l_bounds, u_bounds]``. 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. rrGr1ctjD].}||j|kDs||j|ks.yy)NFT)rrOrJrI)rGrr s r6 in_limitsz&PoissonDisk._random..in_limitssK466] !1I a 00F1I a@P4P  !r9 candidaterc .|jz jz jt}t j ||z jjt}t j ||zdzj}t jjt|dsytjDcgc]}t||||}}t jd5t jt j t j"|jt|z jj$kr dddy dddycc}w#1swYyxYw) zz Check if there are samples closer than ``radius_squared`` to the `candidate` sample. rrTr)invalidrNF)rIrrrr?maximumminimumrisnanrtuplerrOslicerrwrsquarer)rrindicesind_minind_maxrar s r6in_neighborhoodz,PoissonDisk._random..in_neighborhoodsF "DMM1T^^CKKCPGjj1dmm.B.B3.GHGjj1q$..AG88D,,U7^.>uQx.H"HI!VV++,     G sFA/F  FNcjj||jz jz j t }|j t|<j|yr3)rrrIrrrrr)rr curr_sampler s r6 add_samplez'PoissonDisk._random..add_samples[    # #I .!DMM1T^^CKKCPG/8D  U7^ ,   y )r9rrL)rOr?r_r2rrrrrrSrIrJrrrrrrr?) r rrgrrr num_drawn idx_centercenter candidatesrrs ` @r6rzPoissonDisk._randomns& 6TVVq[88QK( ( bjj T   rzz c $ 8 *"** * * )+ t A % txx'' t}}E FII$""# A %dhhD4D4D0EFJ%%j1F  ,00 d&8&88$:J:JJ (  Y' 0Jy)NI A~  $""# A ( i'xx $$r9c@|jtjS)a&Draw ``n`` samples in the interval ``[l_bounds, u_bounds]``. 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. )rAr?infrs r6 fill_spacezPoissonDisk.fill_spaces${{266""r9cDt||j|S)zReset the engine to base state. Returns ------- engine : PoissonDisk Engine reset to its base state. )r7r)rrs r6r)zPoissonDisk.resets   ""$ r9rrc|jj||jf}tj|dzd}|t |jdz |dz d|jz zztj |z }tj|jddd|jf}|tj||z}|S)z$Uniform sampling within hypersphere.rQrLrrrY) rstandard_normalrOr?rrrZrTrAmultiply) r rrrxssqfrfr_tiledrbs r6rz&PoissonDisk._hypersphere_volume_samples HH $ $:tvv*> $ ?ffQT" htvvaxQ/!DFF(; ;bggcl J77 JJr1 466{  R[[H- -r9c|jj||jf}|tjj |ddddfz}|tj ||z}|S)z.Uniform sampling on the hypersphere's surface.rQrrN)rrrOr?linalgnormr)r rrrvecrbs r6rz'PoissonDisk._hypersphere_surface_samplesb hh&&Z,@&A ryy~~c~*1d733 R[[f- -r9r-)r1r-)r.r/r0r1rr r rrr rr?r2rrr)rrrCrDs@r6r-r-s\{zE2 !%4`_ transition from use of `numpy.random.RandomState` to `numpy.random.Generator`, this keyword was changed from `seed` to `rng`. For an interim period, both keywords will continue to work, although only one may be specified at a time. After the interim period, function calls using the `seed` keyword will emit warnings. Following a deprecation period, the `seed` keyword will be removed. 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() r0FrNT)cov_root inv_transformenginerr|rHcovrrrrrr1c tjtj|}|jd}|tjtj|}|jd|jdk(s t dtj ||js t d tjj|j}nC|?tj|}|jd|jdk(s t dd}||_|sdt!j"|dz z} n|} |At%|tj&j(rdnd } | |i} t+d| d d d | |_n=t%|t.r"|j0| k7r t d ||_n t d||_||_||_y#tjj$rtjj|\}} tj|dk\s t dtj|dd}| tj|zj}Y_wxYw)Nrz/Dimension mismatch between mean and covariance.z#Covariance matrix is not symmetric.g:0yEzCovariance matrix not PSD.rQrLr0rTrrrOrrozDimension 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`.r4)r?rSr$rV atleast_2drEallclose transposercholesky LinAlgErroreighrYcliprZ_inv_transformrrr<rArCr*rr)rO_mean _corr_matrix_d) r r|rrrrrrOeigvaleigvec engine_dimkwargkwargss r6r zMultivariateNormalQMC.__init__4 sJzz"---. JJqM ?**R]]3/0C::a=CIIaL0 "/00;;sCMMO4 !FGG B99--c2<<> !}}X.H::a=HNN1$55 "/00H+TYYq1u--JJ >)bii.C.CDF%ES\Ft"8>DK *xx:% "455!DKFG G $[99(( B!#!4vvf/0$%ABBd3"RWWV_4??A  Bs<-G**BJ  J rcF|j|}|j|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_sampless r6rAzMultivariateNormalQMC.random} s#44Q7 |,,r9rcp|j||jz|jzS||jzSr3)rr)r rs r6rz MultivariateNormalQMC._correlate s9    ($"3"33djj@ @ $**, ,r9cf|jj|}|jr(tjj dd|dz zzSt jd|jdd}t jdt j|dd|fz}dtjz|ddd|zfz}t j|}t j|}t j||z||zgdj!|d}|ddd|j"fS) a3Draw `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. rgA?rrYrLrXNr)rrArstatsrppfr?rrVrZlogrpicossinr\rAr) r rrUevenRsthetasrrtransf_sampless r6rz.MultivariateNormalQMC._standard_normal_samples s++$$Q'   ::>>#w}(E"EF F99Q b 115DbffWQW%5667B[71a$h;#77F&&.C&&.CXXrCxc&:&(**1'!R. "!YtwwY,/ /r9r3r-)r.r/r0r1rrr)rr r r?r2rArrr4r9r6r/r/ s)VE2+/F 04"&'+ F!F(F - F  F$FF F3FP- -"**-"-rzz-bjj-0)0BJJ0r9r/c zeZdZdZedddddddd ed edzd ed df d Zdded e jfdZ y)r.aQMC 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. rng : `numpy.random.Generator`, optional Pseudorandom number generator state. When `rng` is None, a new `numpy.random.Generator` is created using entropy from the operating system. Types other than `numpy.random.Generator` are passed to `numpy.random.default_rng` to instantiate a ``Generator``. .. versionchanged:: 1.15.0 As part of the `SPEC-007 `_ transition from use of `numpy.random.RandomState` to `numpy.random.Generator`, this keyword was changed from `seed` to `rng`. For an interim period, both keywords will continue to work, although only one may be specified at a time. After the interim period, function calls using the `seed` keyword will emit warnings. Following a deprecation period, the `seed` keyword will be removed. 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() r0FrN)rrpvalsrHn_trialsrrr1ctjtj||_tj|dkr t dtj tj|ds t d||_|At|tjjrdnd}||i}td dddd ||_ yt|tr"|jdk7r t d ||_ yt d ) Nrz'Elements of pvals must be non-negative.rz Elements of pvals must sum to 1.r0rTrrrz Dimension of `engine` must be 1.rr4)r?r$rSrrXrEiscloserrr<rArCr*rr)rO)r rrrrrrs r6r zMultinomialQMC.__init__ s]]2::e#45 66%=1 FG Gzz"&&-+?@ @  >)bii.C.CDF%ES\Fd/5DK *xx1} !CDD DKFG Gr9rc tj|t|jf}t |D]}|j j |jj}tj|jt}ttj|jt|tj|jtj}t||||||<|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_rrrrrArravel empty_likefloatrr? zeros_likeintpr)r rrGr base_draws p_cumulativesample_s r6rAzMultinomialQMC.random s1c$**o./q A++DMM:@@BJ==5AL rxx %@, OmmDJJbgg>G  L' :F1I   r9r-) r.r/r0r1rr r)rr r?r2rAr4r9r6r.r. s~3jE2 $( GGG D G  G G3G< "**r9r.rrrcttd}|$ |j}||}t |fi|}|Sd}|S#t$r!}|dt |}t ||d}~wwxYw)z#A factory for optimization methods.rNz7 is not a valid optimization method. It must be one of ) _random_cd&_lloyd_centroidal_voronoi_tessellationrZrKrnrEr)rrr optimizer_rMr& optimizers r6rr$ s  70  /'--/L,\:JJ1&1    /&)*2368GW%3 .  /s8 A"AA" best_samplerrrc ~|j\}}|dk(s|dk(rtj||fS|dk(s|dk(r|St|}d|dz gd|dz gd|dz gf}d} d} | |kr| |kr}| dz } t |g|dddi} t |g|dddi} t |g|dddi} t || | | |}||kr|| | f|| | fc|| | f<|| | f<|}d} n| dz } | |kr| |kr}|S)aOptimal 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. rrr!TrL)rVr?r_r&rr)rrrrrrrO best_discbounds n_nochange_n_iters_colrow_1row_2rs r6rr@ sh    DAqAvaxxAAvaK(I!a%j!a%j!a%jFKH  "x''9A 3::T:S<6!9>&+ . 2 2 44r9decayrctj|}t||}t|jD]a\}}|j |Dcgc] }|dk7s | }}|j |} tj| d} ||| ||z |zz||<ctjtj|dk\|dkd} || || <|Scc}w)ufLloyd-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. )rrYrrr) r?rrr= point_regionregionsverticesr|rY logical_and) rGr r new_samplevoronoiiirlrregionvertscentroidis_valids r6_lloyd_iterationr-{ sHv&JfM:GW112FC%__S1=Q"W!==  (775q)x&*'<&EE 2F$vvbnnZ1_jAoFQOH!(+F8 M%>s  CCr r)rrrrrc ~tj|j}|jdk(s t d|j ddk\s t d|j dkDs|jdkr t d|d}|j dd k\r|d z }| tjd z }t|Dcgc]}tj| |z d z }}t| }t|D]5} t||| |}t| } t| |z |kr|S| }7|Scc}w)aApproximate 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 rLz`sample` is not a 2D arrayrz`sample` dimension is not >= 2rPrQz!`sample` is not in unit hypercubez Qbb Qc Qz QJrz Qxg?g?rb)rGr r)r?rSrrTrErVrWrXrrexprr-r) rGrrrrrootrr l1_oldrl1_news r6rr sOV  ZZ  $ $ &F ;;! 566 <<?a 9::  rvzz|b0<==& <<?a  U "M 8bffSk !D,1'N ;qRVVQBI s " ;E ; V $F 7^ !U1X+  ( v # %  MF  M! 0)ros cpu_countNotImplementedErrorrErls r6rmrmQ sl'lG"},,. ?%:  N A6wi@""# # Nr9rOz7tuple[npt.NDArray[np.generic], npt.NDArray[np.generic]]c tj||}tj||}tj||ks td||fS#t$r}d}t||d}~wwxYw)aBounds 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? broadcast_torErY)rIrJrOrZr[rMrs r6rUrUo st$'!,!, 66%%- LMM %< ''o3&'s,A A1A,,A1).r3)rp euclideanrr-)Zr1rrr=r4rxabcrr functoolsrtypingrrrr collections.abcr numpyr?scipy._lib._utilr r r r numpy.typingnpt scipy.statsrrrrscipy.sparse.csgraphr scipy.spatialrr scipy.specialr_sobolrrrrrrr_qmc_cyrrr r!r"r#r$__all__rArDr7rr2r%rcr r&strr'r(rrrlistrrrr)r+r,r*r-r/r.dictrrrr-rrmrUr4r9r6rLs,  # %NNII6+" 6  Y- 8K8K  ]} => P2 P2P2P2  P2 ZZ P2fo"**B 7; G/G/G/34 G/  G/ $) G/X-6!zDzD()zDzD',zDz:G:G:G$:G).:GzWWW#W#W$WtAA A@$ $d3i$P)-, ,%,ZZ,bBA"#/3BA BABA BA  BA - BABABA$&::BAJxxv f5Yf5R@)Y@)F \I\~ ])]@ k0k0\kk\./$6@D _844&)47:4AN44ZZ4n5RZZ5E5= JJ= ==ZZ =F $ S S S S : S  SZZSly<)8=@>r9