Source code for naginterfaces.library.rand

# -*- coding: utf-8 -*-
r"""
Module Summary
--------------
Interfaces for the NAG Mark 27.3 `rand` Chapter.

``rand`` - Random Number Generators

This module is concerned with the generation of sequences of independent pseudorandom and quasi-random numbers from various distributions, and models.

See Also
--------
``naginterfaces.library.examples.rand`` :
    This subpackage contains examples for the ``rand`` module.
    See also the :ref:`library_rand_ex` subsection.

Functionality Index
-------------------

**Brownian bridge**

  circulant embedding generator

    generate fractional Brownian motion: :meth:`field_fracbm_generate`

  increments generator

    generate Wiener increments: :meth:`bb_inc`

    initialize generator: :meth:`bb_inc_init`

  path generator

    create bridge construction order: :meth:`bb_make_bridge_order`

    generate a free or non-free (pinned) Wiener process for a given set of time steps: :meth:`bb`

    initialize generator: :meth:`bb_init`

**Generating samples, matrices and tables**

  permutation of real matrix, vector, vector triplet

    :math:`K-`\ fold cross-validation: :meth:`kfold_xyw`

    random sub-sampling validation: :meth:`subsamp_xyw`

  random correlation matrix: :meth:`matrix_corr`

  random orthogonal matrix: :meth:`matrix_orthog`

  random permutation of an integer vector: :meth:`permute`

  random sample from an integer vector

    unequal weights, without replacement: :meth:`sample_wgt`

    unweighted, without replacement: :meth:`sample`

  random table: :meth:`matrix_2waytable`

**Generation of time series**

  asymmetric GARCH Type II: :meth:`times_garch_asym2`

  asymmetric GJR GARCH: :meth:`times_garch_gjr`

  EGARCH: :meth:`times_garch_exp`

  exponential smoothing: :meth:`times_smooth_exp`

  type I AGARCH: :meth:`times_garch_asym1`

  univariate ARMA: :meth:`times_arma`

  vector ARMA: :meth:`times_mv_varma`

**Pseudorandom numbers**

  array of variates from multivariate distributions

    Dirichlet distribution: :meth:`dist_dirichlet`

    multinomial distribution: :meth:`int_multinomial`

    Normal distribution: :meth:`multivar_normal`

    Student's :math:`t` distribution: :meth:`multivar_students_t`

  copulas

    Clayton/Cook--Johnson copula (bivariate): :meth:`copula_clayton_bivar`

    Clayton/Cook--Johnson copula (multivariate): :meth:`copula_clayton`

    Frank copula (bivariate): :meth:`copula_frank_bivar`

    Frank copula (multivariate): :meth:`copula_frank`

    Gaussian copula: :meth:`copula_normal`

    Gumbel--Hougaard copula: :meth:`copula_gumbel`

    Plackett copula: :meth:`copula_plackett_bivar`

    Student's :math:`t` copula: :meth:`copula_students_t`

  initialize generator

    multiple streams

      leap-frog: :meth:`init_leapfrog`

      skip-ahead: :meth:`init_skipahead`

      skip-ahead (power of 2): :meth:`init_skipahead_power2`

    nonrepeatable sequence: :meth:`init_nonrepeat`

    repeatable sequence: :meth:`init_repeat`

  vector of variates from discrete univariate distributions

    binomial distribution: :meth:`int_binomial`

    geometric distribution: :meth:`int_geom`

    hypergeometric distribution: :meth:`int_hypergeom`

    logarithmic distribution: :meth:`int_log`

    logical value :math:`\mathbf{True}` or :math:`\mathbf{False}`: :meth:`logical`

    negative binomial distribution: :meth:`int_negbin`

    Poisson distribution: :meth:`int_poisson`

    uniform distribution: :meth:`int_uniform`

    user-supplied distribution: :meth:`int_general`

    variate array from discrete distributions with array of parameters

      Poisson distribution with varying mean: :meth:`int_poisson_varmean`

  vectors of variates from continuous univariate distributions

    :math:`\chi^2` square distribution: :meth:`dist_chisq`

    beta distribution: :meth:`dist_beta`

    Cauchy distribution: :meth:`dist_cauchy`

    exponential mix distribution: :meth:`dist_expmix`

    :math:`F`-distribution: :meth:`dist_f`

    gamma distribution: :meth:`dist_gamma`

    logistic distribution: :meth:`dist_logistic`

    log-normal distribution: :meth:`dist_lognormal`

    negative exponential distribution: :meth:`dist_exp`

    Normal distribution: :meth:`dist_normal`

    real number from the continuous uniform distribution: :meth:`dist_uniform01`

    Student's :math:`t`-distribution: :meth:`dist_students_t`

    triangular distribution: :meth:`dist_triangular`

    uniform distribution: :meth:`dist_uniform`

    von Mises distribution: :meth:`dist_vonmises`

    Weibull distribution: :meth:`dist_weibull`

**Quasi-random numbers**

  array of variates from univariate distributions

    log-normal distribution: :meth:`quasi_lognormal`

    Normal distribution: :meth:`quasi_normal`

    uniform distribution: :meth:`quasi_uniform`

  initialize generator

    scrambled Sobol or Niederreiter: :meth:`quasi_init_scrambled`

    Sobol, Niederreiter or Faure: :meth:`quasi_init`

**Random fields**

  one-dimensional

    generation: :meth:`field_1d_generate`

    initialize generator

      preset variogram: :meth:`field_1d_predef_setup`

      user-defined variogram: :meth:`field_1d_user_setup`

  two-dimensional

    generation: :meth:`field_2d_generate`

    initialize generator

      preset variogram: :meth:`field_2d_predef_setup`

      user-defined variogram: :meth:`field_2d_user_setup`

For full information please refer to the NAG Library document

https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05intro.html
"""

# NAG Copyright 2017-2021.

[docs]def init_repeat(genid, seed, subid=0): r""" ``init_repeat`` initializes the selected base generator, as used by the group of pseudorandom number functions (see :meth:`init_leapfrog`--:meth:`init_skipahead`, :meth:`permute`, :meth:`sample`, :meth:`times_garch_asym1`--:meth:`times_mv_varma`, :meth:`matrix_orthog`--:meth:`matrix_2waytable`, :meth:`copula_students_t`, :meth:`copula_normal`, :meth:`multivar_students_t`, :meth:`multivar_normal` and :meth:`dist_uniform01`--:meth:`int_uniform`) and the quasi-random scrambled sequence initialization function, :meth:`quasi_init_scrambled`. .. _g05kf-py2-py-doc: For full information please refer to the NAG Library document for g05kf https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05kff.html .. _g05kf-py2-py-parameters: **Parameters** **genid** : int Must contain the type of base generator to use. :math:`\mathrm{genid} = 1` NAG basic generator. :math:`\mathrm{genid} = 2` Wichmann Hill I generator. :math:`\mathrm{genid} = 3` Mersenne Twister. :math:`\mathrm{genid} = 4` Wichmann Hill II generator. :math:`\mathrm{genid} = 5` ACORN generator. :math:`\mathrm{genid} = 6` L'Ecuyer MRG32k3a generator. See `the G05 Introduction <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05intro.html>`__ for details of each of the base generators. **seed** : int, array-like, shape :math:`\left(\textit{lseed}\right)` The initial (seed) values for the selected base generator. The number of initial values required varies with each of the base generators. If :math:`\mathrm{genid} = 1`, one seed is required. If :math:`\mathrm{genid} = 2`, four seeds are required. If :math:`\mathrm{genid} = 3`, :math:`624` seeds are required. If :math:`\mathrm{genid} = 4`, four seeds are required. If :math:`\mathrm{genid} = 5`, :math:`\left(k+1\right)p` seeds are required, where :math:`k` and :math:`p` are defined by :math:`\mathrm{subid}`. For the ACORN generator it is recommended that an odd value is used for :math:`\mathrm{seed}[0]`. If :math:`\mathrm{genid} = 6`, six seeds are required. If insufficient seeds are provided then the first :math:`\textit{lseed}-1` values supplied in :math:`\mathrm{seed}` are used and the remaining values are randomly generated using the NAG basic generator. In such cases the NAG basic generator is initialized using the value supplied in :math:`\mathrm{seed}[\textit{lseed}-1]`. **subid** : int, optional If :math:`\mathrm{genid} = 2`, :math:`\mathrm{subid}` indicates which of the :math:`273` sub-generators to use. In this case, the :math:`\left(\left(\left\lvert \mathrm{subid}\right\rvert +272\right) mod 273\right)+1` sub-generator is used. If :math:`\mathrm{genid} = 5`, :math:`\mathrm{subid}` indicates the values of :math:`k` and :math:`p` to use, where :math:`k` is the order of the generator, and :math:`p` controls the size of the modulus, :math:`M`, with :math:`M = 2^{\left(p\times 30\right)}`. If :math:`\mathrm{subid} < 1`, the default values of :math:`k = 10` and :math:`p = 2` are used, otherwise values for :math:`k` and :math:`p` are calculated from the formula, :math:`\mathrm{subid} = k+1000\left(p-1\right)`. If :math:`\mathrm{genid} = 6` and :math:`\mathrm{mod}\left(\mathrm{subid}, 2\right) = 0` the range of the generator is set to :math:`\left(0, 1\right]`, otherwise the range is set to :math:`\left(0, 1\right)`; in this case the sequence is identical to the implementation of MRG32k3a in TestU01 (see L'Ecuyer and Simard (2002)) for identical seeds. For all other values of :math:`\mathrm{genid}`, :math:`\mathrm{subid}` is not referenced. **Returns** **statecomm** : dict, RNG communication object RNG communication structure. .. _g05kf-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{genid} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{genid} = 1`, :math:`2`, :math:`3`, :math:`4`, :math:`5` or :math:`6`. (`errno` :math:`3`) On entry, invalid :math:`\mathrm{seed}`. (`errno` :math:`4`) On entry, :math:`\textit{lseed} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\textit{lseed}\geq 1`. .. _g05kf-py2-py-notes: **Notes** ``init_repeat`` selects a base generator through the input value of the arguments :math:`\mathrm{genid}` and :math:`\mathrm{subid}`, and then initializes it based on the values given in the array :math:`\mathrm{seed}`. A given base generator will yield different sequences of random numbers if initialized with different values of :math:`\mathrm{seed}`. Alternatively, the same sequence of random numbers will be generated if the same value of :math:`\mathrm{seed}` is used. It should be noted that there is no guarantee of statistical properties between sequences, only within sequences. A definition of some of the terms used in this description, along with details of the various base generators can be found in `the G05 Introduction <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05intro.html>`__. .. _g05kf-py2-py-references: **References** L'Ecuyer, P and Simard, R, 2002, `TestU01: a software library in ANSI C for empirical testing of random number generators`, Departement d'Informatique et de Recherche Operationnelle, Universite de Montreal, https://www.iro.umontreal.ca/~lecuyer Maclaren, N M, 1989, `The generation of multiple independent sequences of pseudorandom numbers`, Appl. Statist. (38), 351--359 Matsumoto, M and Nishimura, T, 1998, `Mersenne twister: a 623-dimensionally equidistributed uniform pseudorandom number generator`, ACM Transactions on Modelling and Computer Simulations Wichmann, B A and Hill, I D, 2006, `Generating good pseudo-random numbers`, Computational Statistics and Data Analysis (51), 1614--1622 Wikramaratna, R S, 1989, `ACORN - a new method for generating sequences of uniformly distributed pseudo-random numbers`, Journal of Computational Physics (83), 16--31 See Also -------- :meth:`naginterfaces.library.examples.correg.glm_binomial_ex.main` :meth:`naginterfaces.library.examples.fit.dim2_spline_ts_sctr_ex.main` :meth:`naginterfaces.library.examples.rand.bb_inc_ex.main` :meth:`naginterfaces.library.examples.rand.copula_students_t_ex.main` """ raise NotImplementedError
[docs]def init_nonrepeat(genid, subid=0): r""" ``init_nonrepeat`` initializes the selected base generator to generate a non-repeatable sequence of variates. The base generator can then be used by the group of pseudorandom number functions (see :meth:`init_leapfrog`--:meth:`init_skipahead`, :meth:`permute`, :meth:`sample`, :meth:`times_garch_asym1`--:meth:`times_mv_varma`, :meth:`matrix_orthog`--:meth:`matrix_2waytable`, :meth:`copula_students_t`, :meth:`copula_normal`, :meth:`multivar_students_t`, :meth:`multivar_normal` and :meth:`dist_uniform01`--:meth:`int_uniform`) and the quasi-random scrambled sequence initialization function, :meth:`quasi_init_scrambled`. .. _g05kg-py2-py-doc: For full information please refer to the NAG Library document for g05kg https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05kgf.html .. _g05kg-py2-py-parameters: **Parameters** **genid** : int Must contain the type of base generator to use. :math:`\mathrm{genid} = 1` NAG basic generator. :math:`\mathrm{genid} = 2` Wichmann Hill I generator. :math:`\mathrm{genid} = 3` Mersenne Twister. :math:`\mathrm{genid} = 4` Wichmann Hill II generator. :math:`\mathrm{genid} = 5` ACORN generator. :math:`\mathrm{genid} = 6` L'Ecuyer MRG32k3a generator. See `the G05 Introduction <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05intro.html>`__ for details of each of the base generators. **subid** : int, optional If :math:`\mathrm{genid} = 2`, :math:`\mathrm{subid}` indicates which of the :math:`273` sub-generators to use. In this case, the :math:`\left(\left(\left\lvert \mathrm{subid}\right\rvert +272\right) mod 273\right)+1` sub-generator is used. If :math:`\mathrm{genid} = 5`, :math:`\mathrm{subid}` indicates the values of :math:`k` and :math:`p` to use, where :math:`k` is the order of the generator, and :math:`p` controls the size of the modulus, :math:`M`, with :math:`M = 2^{\left(p\times 30\right)}`. If :math:`\mathrm{subid} < 1`, the default values of :math:`k = 10` and :math:`p = 2` are used, otherwise values for :math:`k` and :math:`p` are calculated from the formula, :math:`\mathrm{subid} = k+1000\left(p-1\right)`. If :math:`\mathrm{genid} = 6` and :math:`\mathrm{mod}\left(\mathrm{subid}, 2\right) = 0` the range of the generator is set to :math:`\left(0, 1\right]`, otherwise the range is set to :math:`\left(0, 1\right)`; in this case the sequence is identical to the implementation of MRG32k3a in TestU01 (see L'Ecuyer and Simard (2002)) for identical seeds. For all other values of :math:`\mathrm{genid}`, :math:`\mathrm{subid}` is not referenced. **Returns** **statecomm** : dict, RNG communication object RNG communication structure. .. _g05kg-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{genid} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{genid} = 1`, :math:`2`, :math:`3`, :math:`4`, :math:`5` or :math:`6`. .. _g05kg-py2-py-notes: **Notes** ``init_nonrepeat`` selects a base generator through the input value of the arguments :math:`\mathrm{genid}` and :math:`\mathrm{subid}`, and then initializes it based on the values taken from the real-time clock, resulting in the same base generator yielding different sequences of random numbers each time the calling program is run. It should be noted that there is no guarantee of statistical properties between sequences, only within sequences. A definition of some of the terms used in this description, along with details of the various base generators can be found in `the G05 Introduction <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05intro.html>`__. .. _g05kg-py2-py-references: **References** L'Ecuyer, P and Simard, R, 2002, `TestU01: a software library in ANSI C for empirical testing of random number generators`, Departement d'Informatique et de Recherche Operationnelle, Universite de Montreal, https://www.iro.umontreal.ca/~lecuyer Maclaren, N M, 1989, `The generation of multiple independent sequences of pseudorandom numbers`, Appl. Statist. (38), 351--359 Matsumoto, M and Nishimura, T, 1998, `Mersenne twister: a 623-dimensionally equidistributed uniform pseudorandom number generator`, ACM Transactions on Modelling and Computer Simulations Wichmann, B A and Hill, I D, 2006, `Generating good pseudo-random numbers`, Computational Statistics and Data Analysis (51), 1614--1622 Wikramaratna, R S, 1989, `ACORN - a new method for generating sequences of uniformly distributed pseudo-random numbers`, Journal of Computational Physics (83), 16--31 """ raise NotImplementedError
[docs]def init_leapfrog(n, k, statecomm): r""" ``init_leapfrog`` allows for the generation of multiple, independent, sequences of pseudorandom numbers using the leap-frog method. .. _g05kh-py2-py-doc: For full information please refer to the NAG Library document for g05kh https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05khf.html .. _g05kh-py2-py-parameters: **Parameters** **n** : int :math:`n`, the total number of sequences required. **k** : int :math:`k`, the number of the current sequence. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. .. _g05kh-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 1`. (`errno` :math:`2`) On entry, :math:`\mathrm{k} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`0 < \mathrm{k}\leq \mathrm{n}`. (`errno` :math:`3`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. (`errno` :math:`4`) On entry, cannot use leap-frog with the base generator defined by :math:`\mathrm{statecomm}`\ ['state']. .. _g05kh-py2-py-notes: **Notes** ``init_leapfrog`` adjusts a base generator to allow multiple, independent, sequences of pseudorandom numbers to be generated via the leap-frog method (see `the G05 Introduction <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05intro.html>`__ for details). If, prior to calling ``init_leapfrog`` the base generator defined by :math:`\mathrm{statecomm}`\ ['state'] would produce random numbers :math:`x_1,x_2,x_3,\ldots`, then after calling ``init_leapfrog`` the generator will produce random numbers :math:`x_k,x_{{k+n}},x_{{k+2n}},x_{{k+3n}},\ldots`. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``init_leapfrog``. The leap-frog algorithm can be used in conjunction with the NAG basic generator, both the Wichmann--Hill I and Wichmann--Hill II generators, the Mersenne Twister and L'Ecuyer. .. _g05kh-py2-py-references: **References** Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def init_skipahead(n, statecomm): r""" ``init_skipahead`` allows for the generation of multiple, independent, sequences of pseudorandom numbers using the skip-ahead method. The base pseudorandom number sequence defined by :math:`\mathrm{statecomm}`\ ['state'] is advanced :math:`n` places. .. _g05kj-py2-py-doc: For full information please refer to the NAG Library document for g05kj https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05kjf.html .. _g05kj-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of places to skip ahead. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. .. _g05kj-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`2`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. (`errno` :math:`3`) On entry, cannot use skip-ahead with the base generator defined by :math:`\mathrm{statecomm}`\ ['state']. (`errno` :math:`4`) On entry, the base generator is Mersenne Twister, but the :math:`\mathrm{statecomm}`\ ['state'] vector defined on initialization is not large enough to perform a skip ahead. See the initialization function :meth:`init_repeat` or :meth:`init_nonrepeat`. .. _g05kj-py2-py-notes: **Notes** ``init_skipahead`` adjusts a base generator to allow multiple, independent, sequences of pseudorandom numbers to be generated via the skip-ahead method (see `the G05 Introduction <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05intro.html>`__ for details). If, prior to calling ``init_skipahead`` the base generator defined by :math:`\mathrm{statecomm}`\ ['state'] would produce random numbers :math:`x_1,x_2,x_3,\ldots`, then after calling ``init_skipahead`` the generator will produce random numbers :math:`x_{{n+1}},x_{{n+2}},x_{{n+3}},\ldots`. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``init_skipahead``. The skip-ahead algorithm can be used in conjunction with any of the six base generators discussed in submodule ``rand``. .. _g05kj-py2-py-references: **References** Haramoto, H, Matsumoto, M, Nishimura, T, Panneton, F and L'Ecuyer, P, 2008, `Efficient jump ahead for F2-linear random number generators`, INFORMS J. on Computing (20(3)), 385--390 Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def init_skipahead_power2(n, statecomm): r""" ``init_skipahead_power2`` allows for the generation of multiple, independent, sequences of pseudorandom numbers using the skip-ahead method. The base pseudorandom number sequence defined by :math:`\mathrm{statecomm}`\ ['state'] is advanced :math:`2^n` places. .. _g05kk-py2-py-doc: For full information please refer to the NAG Library document for g05kk https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05kkf.html .. _g05kk-py2-py-parameters: **Parameters** **n** : int :math:`n`, where the number of places to skip-ahead is defined as :math:`2^n`. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. .. _g05kk-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`2`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. (`errno` :math:`3`) On entry, cannot use skip-ahead with the base generator defined by :math:`\mathrm{statecomm}`\ ['state']. (`errno` :math:`4`) On entry, the :math:`\mathrm{statecomm}`\ ['state'] vector defined on initialization is not large enough to perform a skip-ahead (applies to Mersenne Twister base generator). See the initialization function :meth:`init_repeat` or :meth:`init_nonrepeat`. .. _g05kk-py2-py-notes: **Notes** ``init_skipahead_power2`` adjusts a base generator to allow multiple, independent, sequences of pseudorandom numbers to be generated via the skip-ahead method (see `the G05 Introduction <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05intro.html>`__ for details). If, prior to calling ``init_skipahead_power2`` the base generator defined by :math:`\mathrm{statecomm}`\ ['state'] would produce random numbers :math:`x_1,x_2,x_3,\ldots`, then after calling ``init_skipahead_power2`` the generator will produce random numbers :math:`x_{{2^n+1}},x_{{2^n+2}},x_{{2^n+3}},\ldots`. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``init_skipahead_power2``. The skip-ahead algorithm can be used in conjunction with any of the six base generators discussed in `the G05 Introduction <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05intro.html>`__. .. _g05kk-py2-py-references: **References** Haramoto, H, Matsumoto, M, Nishimura, T, Panneton, F and L'Ecuyer, P, 2008, `Efficient jump ahead for F2-linear random number generators`, INFORMS J. on Computing (20(3)), 385--390 Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def permute(indx, statecomm): r""" ``permute`` performs a pseudorandom permutation of a vector of integers. .. _g05nc-py2-py-doc: For full information please refer to the NAG Library document for g05nc https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05ncf.html .. _g05nc-py2-py-parameters: **Parameters** **indx** : int, array-like, shape :math:`\left(n\right)` The :math:`n` integer values to be permuted. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **indx** : int, ndarray, shape :math:`\left(n\right)` The :math:`n` permuted integer values. .. _g05nc-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`2`) On entry, :math:`n = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`n\geq 1`. (`errno` :math:`3`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05nc-py2-py-notes: **Notes** ``permute`` permutes the elements of an integer array without inspecting their values. Each of the :math:`n!` possible permutations of the :math:`n` values may be regarded as being equally probable. Even for modest values of :math:`n` it is theoretically impossible that all :math:`n!` permutations may occur, as :math:`n!` is likely to exceed the cycle length of any of the base generators. For practical purposes this is irrelevant, as the time necessary to generate all possible permutations is many millenia. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``permute``. .. _g05nc-py2-py-references: **References** Kendall, M G and Stuart, A, 1969, `The Advanced Theory of Statistics (Volume 1)`, (3rd Edition), Griffin Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def sample(m, statecomm, ipop=None, n=None): r""" ``sample`` selects a pseudorandom sample without replacement from an integer vector. .. _g05nd-py2-py-doc: For full information please refer to the NAG Library document for g05nd https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05ndf.html .. _g05nd-py2-py-parameters: **Parameters** **m** : int The sample size. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **ipop** : None or int, array-like, shape :math:`\left(\mathrm{n}\right)`, optional The population to be sampled. If :math:`\mathrm{ipop}` is **None**, then the population is assumed to be the set of values :math:`\left(1,2,\ldots,\mathrm{n}\right)` and the array :math:`\mathrm{ipop}` is not referenced. **n** : None or int, optional Note: if this argument is **None** then a default value will be used, determined as follows: :math:`\mathrm{ipop}.\mathrm{shape}[0]`. The number of elements in the population to be sampled. **Returns** **isampl** : int, ndarray, shape :math:`\left(\mathrm{m}\right)` The selected sample. .. _g05nd-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`2`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 1`. (`errno` :math:`4`) On entry, :math:`\mathrm{m} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`1\leq \mathrm{m}\leq \mathrm{n}`. (`errno` :math:`5`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05nd-py2-py-notes: **Notes** ``sample`` selects :math:`m` elements from a population vector :math:`\mathrm{ipop}` of length :math:`n` and places them in a sample vector :math:`\mathrm{isampl}`. Their order in :math:`\mathrm{ipop}` will be preserved in :math:`\mathrm{isampl}`. Each of the (n;m) possible combinations of elements of :math:`\mathrm{isampl}` may be regarded as being equally probable. For moderate or large values of :math:`n` it is theoretically impossible that all combinations of size :math:`m` may occur, unless :math:`m` is near :math:`1` or near :math:`n`. This is because (n;m) exceeds the cycle length of any of the base generators. For practical purposes this is irrelevant, as the time taken to generate all possible combinations is many millenia. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``sample``. .. _g05nd-py2-py-references: **References** Kendall, M G and Stuart, A, 1969, `The Advanced Theory of Statistics (Volume 1)`, (3rd Edition), Griffin Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def sample_wgt(order, wt, m, statecomm, ipop=None): r""" ``sample_wgt`` selects a pseudorandom sample, without replacement and allowing for unequal probabilities. .. _g05ne-py2-py-doc: For full information please refer to the NAG Library document for g05ne https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05nef.html .. _g05ne-py2-py-parameters: **Parameters** **order** : str, length 1 A flag indicating the sorted status of the :math:`\mathrm{wt}` vector. :math:`\mathrm{order} = \text{‘A'}` :math:`\mathrm{wt}` is sorted in ascending order, :math:`\mathrm{order} = \text{‘D'}` :math:`\mathrm{wt}` is sorted in descending order, :math:`\mathrm{order} = \text{‘U'}` :math:`\mathrm{wt}` is unsorted and ``sample_wgt`` will sort the weights prior to using them. Irrespective of the value of :math:`\mathrm{order}`, no checks are made on the sorted status of :math:`\mathrm{wt}`, e.g., it is possible to supply :math:`\mathrm{order} = \text{‘A'}`, even when :math:`\mathrm{wt}` is not sorted. In such cases the :math:`\mathrm{wt}` array will not be sorted internally, but ``sample_wgt`` will still work correctly except, possibly, in cases of extreme weight values. It is usually more efficient to specify a value of :math:`\mathrm{order}` that is consistent with the status of :math:`\mathrm{wt}`. **wt** : float, array-like, shape :math:`\left(n\right)` :math:`w_i`, the relative probability weights. These weights need not sum to :math:`1.0`. **m** : int :math:`m`, the size of the sample required. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **ipop** : None or int, array-like, shape :math:`\left(:\right)`, optional Note: the required length for this argument is determined as follows: if :math:`\mathrm{ipop}\text{ is not }\mathbf{None}`: :math:`n`; otherwise: :math:`0`. The population to be sampled. If :math:`\mathrm{ipop}\text{ is }\mathbf{None}` then the population is assumed to be the set of values :math:`\left(1,2,\ldots,n\right)` and the array :math:`\mathrm{ipop}` is not referenced. Elements of :math:`\mathrm{ipop}` with the same value are not combined, therefore, if :math:`\mathrm{wt}[i-1]\neq 0,\mathrm{wt}[j-1]\neq 0` and :math:`i\neq j` then there is a nonzero probability that the sample will contain both :math:`\mathrm{ipop}[i-1]` and :math:`\mathrm{ipop}[j-1]`. If :math:`\mathrm{ipop}[i-1] = \mathrm{ipop}[j-1]` then that value can appear in :math:`\mathrm{isampl}` more than once. **Returns** **isampl** : int, ndarray, shape :math:`\left(\mathrm{m}\right)` The selected sample. .. _g05ne-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{order}` had an illegal value. (`errno` :math:`2`) On entry, at least one weight was less than zero. (`errno` :math:`5`) On entry, :math:`n = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`n\geq 1`. (`errno` :math:`7`) On entry, :math:`\mathrm{m} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`n = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`0\leq \mathrm{m}\leq n`. (`errno` :math:`8`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. (`errno` :math:`21`) On entry, :math:`\mathrm{m} = \langle\mathit{\boldsymbol{value}}\rangle`, number of nonzero weights :math:`= \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: must be at least :math:`\mathrm{m}` nonzero weights. .. _g05ne-py2-py-notes: **Notes** ``sample_wgt`` selects :math:`m` elements from either the set of values :math:`\left(1,2,\ldots,n\right)` or a supplied population vector of length :math:`n`. The probability of selecting the :math:`i`\ th element is proportional to a user-supplied weight, :math:`w_i`. Each element will appear at most once in the sample, i.e., the sampling is done without replacement. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``sample_wgt``. """ raise NotImplementedError
[docs]def times_garch_asym1(dist, num, ip, iq, theta, gamma, df, fcall, comm, statecomm): r""" ``times_garch_asym1`` generates a given number of terms of a type I :math:`\text{AGARCH}\left(p, q\right)` process (see Engle and Ng (1993)). .. _g05pd-py2-py-doc: For full information please refer to the NAG Library document for g05pd https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05pdf.html .. _g05pd-py2-py-parameters: **Parameters** **dist** : str, length 1 The type of distribution to use for :math:`\epsilon_t`. :math:`\mathrm{dist} = \texttt{'N'}` A Normal distribution is used. :math:`\mathrm{dist} = \texttt{'T'}` A Student's :math:`t`-distribution is used. **num** : int :math:`T`, the number of terms in the sequence. **ip** : int The number of coefficients, :math:`\beta_{\textit{i}}`, for :math:`\textit{i} = 1,2,\ldots,p`. **iq** : int The number of coefficients, :math:`\alpha_{\textit{i}}`, for :math:`\textit{i} = 1,2,\ldots,q`. **theta** : float, array-like, shape :math:`\left(\mathrm{iq}+\mathrm{ip}+1\right)` The first element must contain the coefficient :math:`\alpha_o`, the next :math:`\mathrm{iq}` elements must contain the coefficients :math:`\alpha_{\textit{i}}`, for :math:`\textit{i} = 1,2,\ldots,q`. The remaining :math:`\mathrm{ip}` elements must contain the coefficients :math:`\beta_{\textit{j}}`, for :math:`\textit{j} = 1,2,\ldots,p`. **gamma** : float The asymmetry parameter :math:`\gamma` for the :math:`\text{GARCH}\left(p, q\right)` sequence. **df** : int The number of degrees of freedom for the Student's :math:`t`-distribution. If :math:`\mathrm{dist} = \texttt{'N'}`, :math:`\mathrm{df}` is not referenced. **fcall** : bool If :math:`\mathrm{fcall} = \mathbf{True}`, a new sequence is to be generated, otherwise a given sequence is to be continued using the information in :math:`\mathrm{comm}`\ ['r']. **comm** : dict, communication object, modified in place Communication structure for the reference vector. If :math:`\mathrm{fcall} = \mathbf{False}`, this argument must have been initialized by a prior call to ``times_garch_asym1``. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **ht** : float, ndarray, shape :math:`\left(\mathrm{num}\right)` The conditional variances :math:`h_{\textit{t}}`, for :math:`\textit{t} = 1,2,\ldots,T`, for the :math:`\text{GARCH}\left(p, q\right)` sequence. **et** : float, ndarray, shape :math:`\left(\mathrm{num}\right)` The observations :math:`\epsilon_{\textit{t}}`, for :math:`\textit{t} = 1,2,\ldots,T`, for the :math:`\text{GARCH}\left(p, q\right)` sequence. .. _g05pd-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{dist}` is not valid: :math:`\mathrm{dist} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`2`) On entry, :math:`\mathrm{num} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{num}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{ip} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{ip}\geq 0`. (`errno` :math:`4`) On entry, :math:`\mathrm{iq} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{iq}\geq 1`. (`errno` :math:`5`) On entry, :math:`\mathrm{theta}[\langle\mathit{\boldsymbol{value}}\rangle] = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{theta}[i-1]\geq 0.0`. (`errno` :math:`7`) On entry, :math:`\mathrm{df} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{df}\geq 3`. (`errno` :math:`11`) :math:`\mathrm{ip}` or :math:`\mathrm{iq}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call. Previous value of :math:`\mathrm{ip} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{ip} = \langle\mathit{\boldsymbol{value}}\rangle`. Previous value of :math:`\mathrm{iq} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{iq} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`13`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. (`errno` :math:`51`) On entry, sum of :math:`\mathrm{theta}[\textit{i}-1]`, for :math:`\textit{i} = 2,3,\ldots,\mathrm{ip}+\mathrm{iq}+1` is :math:`\text{}\geq 1.0`: :math:`\mathrm{sum} = \langle\mathit{\boldsymbol{value}}\rangle`. .. _g05pd-py2-py-notes: **Notes** A type I :math:`\text{AGARCH}\left(p, q\right)` process can be represented by: .. math:: h_t = \alpha_0+\sum_{{i = 1}}^q\alpha_i\left(\epsilon_{{t-i}}+\gamma \right)^2+\sum_{{i = 1}}^p\beta_ih_{{t-i}}\text{, }\quad t = 1,2,\ldots,T\text{;} where :math:`\epsilon_t | \psi_{{t-1}} = N\left(0, h_t\right)` or :math:`\epsilon_t | \psi_{{t-1}} = S_t\left({\textit{df}}, h_t\right)`. Here :math:`S_t` is a standardized Student's :math:`t`-distribution with :math:`{\textit{df}}` degrees of freedom and variance :math:`h_t`, :math:`T` is the number of observations in the sequence, :math:`\epsilon_t` is the observed value of the :math:`\text{GARCH}\left(p, q\right)` process at time :math:`t`, :math:`h_t` is the conditional variance at time :math:`t`, and :math:`\psi_t` the set of all information up to time :math:`t`. Symmetric GARCH sequences are generated when :math:`\gamma` is zero, otherwise asymmetric GARCH sequences are generated with :math:`\gamma` specifying the amount by which positive (or negative) shocks are to be enhanced. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``times_garch_asym1``. .. _g05pd-py2-py-references: **References** Bollerslev, T, 1986, `Generalised autoregressive conditional heteroskedasticity`, Journal of Econometrics (31), 307--327 Engle, R, 1982, `Autoregressive conditional heteroskedasticity with estimates of the variance of United Kingdom inflation`, Econometrica (50), 987--1008 Engle, R and Ng, V, 1993, `Measuring and testing the impact of news on volatility`, Journal of Finance (48), 1749--1777 Hamilton, J, 1994, `Time Series Analysis`, Princeton University Press """ raise NotImplementedError
[docs]def times_garch_asym2(dist, num, ip, iq, theta, gamma, df, fcall, comm, statecomm): r""" ``times_garch_asym2`` generates a given number of terms of a type II :math:`\text{AGARCH}\left(p, q\right)` process (see Engle and Ng (1993)). .. _g05pe-py2-py-doc: For full information please refer to the NAG Library document for g05pe https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05pef.html .. _g05pe-py2-py-parameters: **Parameters** **dist** : str, length 1 The type of distribution to use for :math:`\epsilon_t`. :math:`\mathrm{dist} = \texttt{'N'}` A Normal distribution is used. :math:`\mathrm{dist} = \texttt{'T'}` A Student's :math:`t`-distribution is used. **num** : int :math:`T`, the number of terms in the sequence. **ip** : int The number of coefficients, :math:`\beta_{\textit{i}}`, for :math:`\textit{i} = 1,2,\ldots,p`. **iq** : int The number of coefficients, :math:`\alpha_{\textit{i}}`, for :math:`\textit{i} = 1,2,\ldots,q`. **theta** : float, array-like, shape :math:`\left(\mathrm{iq}+\mathrm{ip}+1\right)` The first element must contain the coefficient :math:`\alpha_o`, the next :math:`\mathrm{iq}` elements must contain the coefficients :math:`\alpha_{\textit{i}}`, for :math:`\textit{i} = 1,2,\ldots,q`. The remaining :math:`\mathrm{ip}` elements must contain the coefficients :math:`\beta_{\textit{j}}`, for :math:`\textit{j} = 1,2,\ldots,p`. **gamma** : float The asymmetry parameter :math:`\gamma` for the :math:`\text{GARCH}\left(p, q\right)` sequence. **df** : int The number of degrees of freedom for the Student's :math:`t`-distribution. If :math:`\mathrm{dist} = \texttt{'N'}`, :math:`\mathrm{df}` is not referenced. **fcall** : bool If :math:`\mathrm{fcall} = \mathbf{True}`, a new sequence is to be generated, otherwise a given sequence is to be continued using the information in :math:`\mathrm{comm}`\ ['r']. **comm** : dict, communication object, modified in place Communication structure for the reference vector. If :math:`\mathrm{fcall} = \mathbf{False}`, this argument must have been initialized by a prior call to ``times_garch_asym2``. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **ht** : float, ndarray, shape :math:`\left(\mathrm{num}\right)` The conditional variances :math:`h_{\textit{t}}`, for :math:`\textit{t} = 1,2,\ldots,T`, for the :math:`\text{GARCH}\left(p, q\right)` sequence. **et** : float, ndarray, shape :math:`\left(\mathrm{num}\right)` The observations :math:`\epsilon_{\textit{t}}`, for :math:`\textit{t} = 1,2,\ldots,T`, for the :math:`\text{GARCH}\left(p, q\right)` sequence. .. _g05pe-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{dist}` is not valid: :math:`\mathrm{dist} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`2`) On entry, :math:`\mathrm{num} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{num}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{ip} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{ip}\geq 0`. (`errno` :math:`4`) On entry, :math:`\mathrm{iq} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{iq}\geq 1`. (`errno` :math:`5`) On entry, :math:`\mathrm{theta}[\langle\mathit{\boldsymbol{value}}\rangle] = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{theta}[i-1]\geq 0.0`. (`errno` :math:`7`) On entry, :math:`\mathrm{df} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{df}\geq 3`. (`errno` :math:`11`) :math:`\mathrm{ip}` or :math:`\mathrm{iq}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call. Previous value of :math:`\mathrm{ip} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{ip} = \langle\mathit{\boldsymbol{value}}\rangle`. Previous value of :math:`\mathrm{iq} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{iq} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`13`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. (`errno` :math:`51`) On entry, sum of :math:`\mathrm{theta}[\textit{i}-1]`, for :math:`\textit{i} = 2,3,\ldots,\mathrm{ip}+\mathrm{iq}+1` is :math:`\text{}\geq 1.0`: :math:`\mathrm{sum} = \langle\mathit{\boldsymbol{value}}\rangle`. .. _g05pe-py2-py-notes: **Notes** A type II :math:`\text{AGARCH}\left(p, q\right)` process can be represented by: .. math:: h_t = \alpha_0+\sum_{1}^{q}{\alpha_i\left(\left\lvert \epsilon_{{t-i}}\right\rvert +\gamma \epsilon_{{t-i}}\right)^2}+\sum_{1}^{p}{\beta_ih_{{t-i}}}\text{, }\quad t = 1,2,\ldots,T\text{;} where :math:`\epsilon_t | \psi_{{t-1}} = N\left(0, h_t\right)` or :math:`\epsilon_t | \psi_{{t-1}} = S_t\left({\textit{df}}, h_t\right)`. Here :math:`S_t` is a standardized Student's :math:`t`-distribution with :math:`{\textit{df}}` degrees of freedom and variance :math:`h_t`, :math:`T` is the number of observations in the sequence, :math:`\epsilon_t` is the observed value of the :math:`\text{GARCH}\left(p, q\right)` process at time :math:`t`, :math:`h_t` is the conditional variance at time :math:`t`, and :math:`\psi_t` the set of all information up to time :math:`t`. Symmetric GARCH sequences are generated when :math:`\gamma` is zero, otherwise asymmetric GARCH sequences are generated with :math:`\gamma` specifying the amount by which positive (or negative) shocks are to be enhanced. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``times_garch_asym2``. .. _g05pe-py2-py-references: **References** Bollerslev, T, 1986, `Generalised autoregressive conditional heteroskedasticity`, Journal of Econometrics (31), 307--327 Engle, R, 1982, `Autoregressive conditional heteroskedasticity with estimates of the variance of United Kingdom inflation`, Econometrica (50), 987--1008 Engle, R and Ng, V, 1993, `Measuring and testing the impact of news on volatility`, Journal of Finance (48), 1749--1777 Hamilton, J, 1994, `Time Series Analysis`, Princeton University Press """ raise NotImplementedError
[docs]def times_garch_gjr(dist, num, ip, iq, theta, gamma, df, fcall, comm, statecomm): r""" ``times_garch_gjr`` generates a given number of terms of a GJR :math:`\text{GARCH}\left(p, q\right)` process (see Glosten `et al.` (1993)). .. _g05pf-py2-py-doc: For full information please refer to the NAG Library document for g05pf https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05pff.html .. _g05pf-py2-py-parameters: **Parameters** **dist** : str, length 1 The type of distribution to use for :math:`\epsilon_t`. :math:`\mathrm{dist} = \texttt{'N'}` A Normal distribution is used. :math:`\mathrm{dist} = \texttt{'T'}` A Student's :math:`t`-distribution is used. **num** : int :math:`T`, the number of terms in the sequence. **ip** : int The number of coefficients, :math:`\beta_{\textit{i}}`, for :math:`\textit{i} = 1,2,\ldots,p`. **iq** : int The number of coefficients, :math:`\alpha_{\textit{i}}`, for :math:`\textit{i} = 1,2,\ldots,q`. **theta** : float, array-like, shape :math:`\left(\mathrm{iq}+\mathrm{ip}+1\right)` The first element must contain the coefficient :math:`\alpha_o`, the next :math:`\mathrm{iq}` elements must contain the coefficients :math:`\alpha_{\textit{i}}`, for :math:`\textit{i} = 1,2,\ldots,q`. The remaining :math:`\mathrm{ip}` elements must contain the coefficients :math:`\beta_{\textit{j}}`, for :math:`\textit{j} = 1,2,\ldots,p`. **gamma** : float The asymmetry parameter :math:`\gamma` for the :math:`\text{GARCH}\left(p, q\right)` sequence. **df** : int The number of degrees of freedom for the Student's :math:`t`-distribution. If :math:`\mathrm{dist} = \texttt{'N'}`, :math:`\mathrm{df}` is not referenced. **fcall** : bool If :math:`\mathrm{fcall} = \mathbf{True}`, a new sequence is to be generated, otherwise a given sequence is to be continued using the information in :math:`\mathrm{comm}`\ ['r']. **comm** : dict, communication object, modified in place Communication structure for the reference vector. If :math:`\mathrm{fcall} = \mathbf{False}`, this argument must have been initialized by a prior call to ``times_garch_gjr``. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **ht** : float, ndarray, shape :math:`\left(\mathrm{num}\right)` The conditional variances :math:`h_{\textit{t}}`, for :math:`\textit{t} = 1,2,\ldots,T`, for the :math:`\text{GARCH}\left(p, q\right)` sequence. **et** : float, ndarray, shape :math:`\left(\mathrm{num}\right)` The observations :math:`\epsilon_{\textit{t}}`, for :math:`\textit{t} = 1,2,\ldots,T`, for the :math:`\text{GARCH}\left(p, q\right)` sequence. .. _g05pf-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{dist}` is not valid: :math:`\mathrm{dist} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`2`) On entry, :math:`\mathrm{num} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{num}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{ip} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{ip}\geq 0`. (`errno` :math:`4`) On entry, :math:`\mathrm{iq} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{iq}\geq 1`. (`errno` :math:`5`) On entry, :math:`\mathrm{theta}[\langle\mathit{\boldsymbol{value}}\rangle] = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\gamma = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\alpha_i+\gamma \geq 0`. (`errno` :math:`7`) On entry, :math:`\mathrm{df} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{df}\geq 3`. (`errno` :math:`11`) :math:`\mathrm{ip}` or :math:`\mathrm{iq}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call. Previous value of :math:`\mathrm{ip} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{ip} = \langle\mathit{\boldsymbol{value}}\rangle`. Previous value of :math:`\mathrm{iq} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{iq} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`13`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. (`errno` :math:`51`) On entry, :math:`\mathrm{theta}[\langle\mathit{\boldsymbol{value}}\rangle] = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{theta}[i]\geq 0.0`. (`errno` :math:`52`) On entry, sum of :math:`\mathrm{theta}[i] = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: sum of :math:`\mathrm{theta}[\textit{i}]`, for :math:`\textit{i} = 1,2,\ldots,\mathrm{ip}+\mathrm{iq}` is :math:`\text{} < 1.0`. .. _g05pf-py2-py-notes: **Notes** A GJR :math:`\text{GARCH}\left(p, q\right)` process is represented by: .. math:: h_t = \alpha_0+\sum_{{i = 1}}^q\left(\alpha_i+\gamma I_{{t-i}}\right)\epsilon_{{t-i}}^2+\sum_{{i = 1}}^p\beta_ih_{{t-i}}\text{, }\quad t = 1,2,\ldots,T\text{;} where :math:`I_t = 1` if :math:`\epsilon_t < 0`, :math:`I_t = 0` if :math:`\epsilon_t\geq 0`, and :math:`\epsilon_t | \psi_{{t-1}} = N\left(0, h_t\right)` or :math:`\epsilon_t | \psi_{{t-1}} = S_t\left({\textit{df}}, h_t\right)`. Here :math:`S_t` is a standardized Student's :math:`t`-distribution with :math:`{\textit{df}}` degrees of freedom and variance :math:`h_t`, :math:`T` is the number of observations in the sequence, :math:`\epsilon_t` is the observed value of the :math:`\text{GARCH}\left(p, q\right)` process at time :math:`t`, :math:`h_t` is the conditional variance at time :math:`t`, and :math:`\psi_t` the set of all information up to time :math:`t`. Symmetric GARCH sequences are generated when :math:`\gamma` is zero, otherwise asymmetric GARCH sequences are generated with :math:`\gamma` specifying the amount by which negative shocks are to be enhanced. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``times_garch_gjr``. .. _g05pf-py2-py-references: **References** Bollerslev, T, 1986, `Generalised autoregressive conditional heteroskedasticity`, Journal of Econometrics (31), 307--327 Engle, R, 1982, `Autoregressive conditional heteroskedasticity with estimates of the variance of United Kingdom inflation`, Econometrica (50), 987--1008 Engle, R and Ng, V, 1993, `Measuring and testing the impact of news on volatility`, Journal of Finance (48), 1749--1777 Glosten, L, Jagannathan, R and Runkle, D, 1993, `Relationship between the expected value and the volatility of nominal excess return on stocks`, Journal of Finance (48), 1779--1801 Hamilton, J, 1994, `Time Series Analysis`, Princeton University Press """ raise NotImplementedError
[docs]def times_garch_exp(dist, num, ip, iq, theta, df, fcall, comm, statecomm): r""" ``times_garch_exp`` generates a given number of terms of an exponential :math:`\text{GARCH}\left(p, q\right)` process (see Engle and Ng (1993)). .. _g05pg-py2-py-doc: For full information please refer to the NAG Library document for g05pg https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05pgf.html .. _g05pg-py2-py-parameters: **Parameters** **dist** : str, length 1 The type of distribution to use for :math:`\epsilon_t`. :math:`\mathrm{dist} = \texttt{'N'}` A Normal distribution is used. :math:`\mathrm{dist} = \texttt{'T'}` A Student's :math:`t`-distribution is used. **num** : int :math:`T`, the number of terms in the sequence. **ip** : int The number of coefficients, :math:`\beta_{\textit{i}}`, for :math:`\textit{i} = 1,2,\ldots,p`. **iq** : int The number of coefficients, :math:`\alpha_{\textit{i}}`, for :math:`\textit{i} = 1,2,\ldots,q`. **theta** : float, array-like, shape :math:`\left(2\times \mathrm{iq}+\mathrm{ip}+1\right)` The initial parameter estimates for the vector :math:`\theta`. The first element must contain the coefficient :math:`\alpha_o` and the next :math:`\mathrm{iq}` elements must contain the autoregressive coefficients :math:`\alpha_{\textit{i}}`, for :math:`\textit{i} = 1,2,\ldots,q`. The next :math:`\mathrm{iq}` elements must contain the coefficients :math:`\phi_{\textit{i}}`, for :math:`\textit{i} = 1,2,\ldots,q`. The next :math:`\mathrm{ip}` elements must contain the moving average coefficients :math:`\beta_{\textit{j}}`, for :math:`\textit{j} = 1,2,\ldots,p`. **df** : int The number of degrees of freedom for the Student's :math:`t`-distribution. If :math:`\mathrm{dist} = \texttt{'N'}`, :math:`\mathrm{df}` is not referenced. **fcall** : bool If :math:`\mathrm{fcall} = \mathbf{True}`, a new sequence is to be generated, otherwise a given sequence is to be continued using the information in :math:`\mathrm{comm}`\ ['r']. **comm** : dict, communication object, modified in place Communication structure for the reference vector. If :math:`\mathrm{fcall} = \mathbf{False}`, this argument must have been initialized by a prior call to ``times_garch_exp``. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **ht** : float, ndarray, shape :math:`\left(\mathrm{num}\right)` The conditional variances :math:`h_{\textit{t}}`, for :math:`\textit{t} = 1,2,\ldots,T`, for the :math:`\text{GARCH}\left(p, q\right)` sequence. **et** : float, ndarray, shape :math:`\left(\mathrm{num}\right)` The observations :math:`\epsilon_{\textit{t}}`, for :math:`\textit{t} = 1,2,\ldots,T`, for the :math:`\text{GARCH}\left(p, q\right)` sequence. .. _g05pg-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{dist}` is not valid: :math:`\mathrm{dist} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`2`) On entry, :math:`\mathrm{num} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{num}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{ip} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{ip}\geq 0`. (`errno` :math:`4`) On entry, :math:`\mathrm{iq} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{iq}\geq 1`. (`errno` :math:`6`) On entry, :math:`\mathrm{df} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{df}\geq 3`. (`errno` :math:`10`) :math:`\mathrm{ip}` or :math:`\mathrm{iq}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call. Previous value of :math:`\mathrm{ip} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{ip} = \langle\mathit{\boldsymbol{value}}\rangle`. Previous value of :math:`\mathrm{iq} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{iq} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`12`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. (`errno` :math:`20`) Invalid sequence generated, use different parameters. .. _g05pg-py2-py-notes: **Notes** An exponential :math:`\text{GARCH}\left(p, q\right)` process is represented by: .. math:: ln\left(h_t\right) = \alpha_0+\sum_{{i = 1}}^q\alpha_iz_{{t-i}}+\sum_{{i = 1}}^q\phi_i\left(\left\lvert z_{{t-i}}\right\rvert -E\left[\left\lvert z_{{t-i}}\right\rvert \right]\right)+\sum_{{j = 1}}^p\beta_jln\left(h_{{t-j}}\right)\text{, }\quad t = 1,2,\ldots,T\text{;} where :math:`z_t = \frac{\epsilon_t}{{\sqrt{h_t}}}`, :math:`E\left[\left\lvert z_{{t-i}}\right\rvert \right]` denotes the expected value of :math:`\left\lvert z_{{t-i}}\right\rvert`, and :math:`\epsilon_t | \psi_{{t-1}} = N\left(0, h_t\right)` or :math:`\epsilon_t | \psi_{{t-1}} = S_t\left({\textit{df}}, h_t\right)`. Here :math:`S_t` is a standardized Student's :math:`t`-distribution with :math:`{\textit{df}}` degrees of freedom and variance :math:`h_t`, :math:`T` is the number of observations in the sequence, :math:`\epsilon_t` is the observed value of the :math:`\text{GARCH}\left(p, q\right)` process at time :math:`t`, :math:`h_t` is the conditional variance at time :math:`t`, and :math:`\psi_t` the set of all information up to time :math:`t`. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``times_garch_exp``. .. _g05pg-py2-py-references: **References** Bollerslev, T, 1986, `Generalised autoregressive conditional heteroskedasticity`, Journal of Econometrics (31), 307--327 Engle, R, 1982, `Autoregressive conditional heteroskedasticity with estimates of the variance of United Kingdom inflation`, Econometrica (50), 987--1008 Engle, R and Ng, V, 1993, `Measuring and testing the impact of news on volatility`, Journal of Finance (48), 1749--1777 Glosten, L, Jagannathan, R and Runkle, D, 1993, `Relationship between the expected value and the volatility of nominal excess return on stocks`, Journal of Finance (48), 1779--1801 Hamilton, J, 1994, `Time Series Analysis`, Princeton University Press """ raise NotImplementedError
[docs]def times_arma(mode, n, xmean, phi, theta, avar, comm, statecomm): r""" ``times_arma`` generates a realization of a univariate time series from an autoregressive moving average (ARMA) model. The realization may be continued or a new realization generated at subsequent calls to ``times_arma``. .. _g05ph-py2-py-doc: For full information please refer to the NAG Library document for g05ph https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05phf.html .. _g05ph-py2-py-parameters: **Parameters** **mode** : int A code for selecting the operation to be performed by the function. :math:`\mathrm{mode} = 0` Set up reference vector only. :math:`\mathrm{mode} = 1` Generate terms in the time series using reference vector set up in a prior call to ``times_arma``. :math:`\mathrm{mode} = 2` Set up reference vector and generate terms in the time series. **n** : int :math:`n`, the number of observations to be generated. **xmean** : float The mean of the time series. **phi** : float, array-like, shape :math:`\left(\textit{ip}\right)` The autoregressive coefficients of the model, :math:`\phi_1,\phi_2,\ldots,\phi_p`. **theta** : float, array-like, shape :math:`\left(\textit{iq}\right)` The moving average coefficients of the model, :math:`\theta_1,\theta_2,\ldots,\theta_q`. **avar** : float :math:`\sigma^2`, the variance of the Normal perturbations. **comm** : dict, communication object, modified in place Communication structure for the reference vector. If :math:`\mathrm{mode} = 1`, this argument must have been initialized by a prior call to ``times_arma``. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **var** : float The proportion of the variance of a term in the series that is due to the moving-average (error) terms in the model. The smaller this is, the nearer is the model to non-stationarity. **x** : None or float, ndarray, shape :math:`\left(\mathrm{n}\right)` Contains the next :math:`n` observations from the time series. .. _g05ph-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{mode} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{mode} = 0`, :math:`1` or :math:`2`. (`errno` :math:`2`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`4`) On entry, :math:`\textit{ip} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\textit{ip}\geq 0`. (`errno` :math:`5`) On entry, the AR parameters are outside the stationarity region. (`errno` :math:`6`) On entry, :math:`\textit{iq} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\textit{iq}\geq 0`. (`errno` :math:`8`) On entry, :math:`\mathrm{avar} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{avar}\geq 0.0`. (`errno` :math:`9`) Reference vector :math:`\mathrm{comm}`\ ['r'] has been corrupted or not initialized correctly. (`errno` :math:`9`) :math:`\textit{ip}` or :math:`\textit{iq}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call. Previous value of :math:`\textit{ip} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\textit{ip} = \langle\mathit{\boldsymbol{value}}\rangle`. Previous value of :math:`\textit{iq} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\textit{iq} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`11`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05ph-py2-py-notes: **Notes** Let the vector :math:`x_t`, denote a time series which is assumed to follow an autoregressive moving average (ARMA) model of the form: .. math:: \begin{array}{cc}x_t-\mu = &\phi_1\left(x_{{t-1}}-\mu \right)+\phi_2\left(x_{{t-2}}-\mu \right)+ \cdots +\phi_p\left(x_{{t-p}}-\mu \right)+\\&\epsilon_t-\theta_1\epsilon_{{t-1}}-\theta_2\epsilon_{{t-2}} - \cdots -\theta_q\epsilon_{{t-q}}\end{array} where :math:`\epsilon_t`, is a residual series of independent random perturbations assumed to be Normally distributed with zero mean and variance :math:`\sigma^2`. The parameters :math:`\left\{\phi_i\right\}`, for :math:`\textit{i} = 1,2,\ldots,p`, are called the autoregressive (AR) parameters, and :math:`\left\{\theta_j\right\}`, for :math:`\textit{j} = 1,2,\ldots,q`, the moving average (MA) parameters. The parameters in the model are thus the :math:`p` :math:`\phi` values, the :math:`q` :math:`\theta` values, the mean :math:`\mu` and the residual variance :math:`\sigma^2`. ``times_arma`` sets up a reference vector containing initial values corresponding to a stationary position using the method described in Tunnicliffe--Wilson (1979). The function can then return a realization of :math:`x_1,x_2,\ldots,x_n`. On a successful exit, the recent history is updated and saved in the reference vector :math:`\mathrm{comm}`\ ['r'] so that ``times_arma`` may be called again to generate a realization of :math:`x_{{n+1}},x_{{n+2}},\ldots`, etc. See the description of the argument :math:`\mathrm{mode}` in :ref:`Parameters <g05ph-py2-py-parameters>` for details. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``times_arma``. .. _g05ph-py2-py-references: **References** Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley Tunnicliffe--Wilson, G, 1979, `Some efficient computational procedures for high order ARMA models`, J. Statist. Comput. Simulation (8), 301--309 """ raise NotImplementedError
[docs]def times_mv_varma(mode, n, xmean, ip, phi, iq, theta, var, comm, statecomm): r""" ``times_mv_varma`` generates a realization of a multivariate time series from a vector autoregressive moving average (VARMA) model. The realization may be continued or a new realization generated at subsequent calls to ``times_mv_varma``. .. _g05pj-py2-py-doc: For full information please refer to the NAG Library document for g05pj https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05pjf.html .. _g05pj-py2-py-parameters: **Parameters** **mode** : int A code for selecting the operation to be performed by the function. :math:`\mathrm{mode} = 0` Set up reference vector and compute a realization of the recent history. :math:`\mathrm{mode} = 1` Generate terms in the time series using reference vector set up in a prior call to ``times_mv_varma``. :math:`\mathrm{mode} = 2` Combine the operations of :math:`\mathrm{mode} = 0` or :math:`1`. :math:`\mathrm{mode} = 3` A new realization of the recent history is computed using information stored in the reference vector, and the following sequence of time series values are generated. If :math:`\mathrm{mode} = 1` or :math:`3`, you must ensure that the reference vector :math:`\mathrm{comm}`\ ['r'] and the values of :math:`\textit{k}`, :math:`\mathrm{ip}`, :math:`\mathrm{iq}`, :math:`\mathrm{xmean}`, :math:`\mathrm{phi}`, :math:`\mathrm{theta}`, :math:`\mathrm{var}` and :math:`\textit{ldvar}` have not been changed between calls to ``times_mv_varma``. **n** : int :math:`n`, the number of observations to be generated. **xmean** : float, array-like, shape :math:`\left(k\right)` :math:`\mu`, the vector of means of the multivariate time series. **ip** : int :math:`p`, the number of autoregressive parameter matrices. **phi** : float, array-like, shape :math:`\left(k\times k\times \mathrm{ip}\right)` Must contain the elements of the :math:`\mathrm{ip}\times k\times k` autoregressive parameter matrices of the model, :math:`\phi_1,\phi_2,\ldots,\phi_p`. If :math:`\mathrm{phi}` is considered as a three-dimensional array, dimensioned as :math:`\mathrm{phi}[k-1,k-1,\mathrm{ip}-1]`, the :math:`\left(i, j\right)`\ th element of :math:`\phi_{\textit{l}}` would be stored in :math:`\mathrm{phi}[i-1,j-1,\textit{l}-1]`; that is, :math:`\mathrm{phi}[\left(\textit{l}-1\right)\times k\times k+\left(j-1\right)\times k+i-1]` must be set equal to the :math:`\left(i, j\right)`\ th element of :math:`\phi_{\textit{l}}`, for :math:`\textit{l} = 1,2,\ldots,p`, :math:`i = 1,2,\ldots,k` and :math:`j = 1,2,\ldots,k`. **iq** : int :math:`q`, the number of moving average parameter matrices. **theta** : float, array-like, shape :math:`\left(k\times k\times \mathrm{iq}\right)` Must contain the elements of the :math:`\mathrm{iq}\times k\times k` moving average parameter matrices of the model, :math:`\theta_1,\theta_2,\ldots,\theta_q`. If :math:`\mathrm{theta}` is considered as a three-dimensional array, dimensioned as :math:`\mathrm{theta}`\ (:math:`\textit{k}`,\ :math:`\textit{k}`,\ :math:`\mathrm{iq}`), the :math:`\left(i, j\right)`\ th element of :math:`\theta_{\textit{l}}` would be stored in :math:`\mathrm{theta}[\textit{i}-1,\textit{j}-1,\textit{l}-1]`; that is, :math:`\mathrm{theta}[\left(\textit{l}-1\right)\times k\times k+\left(\textit{j}-1\right)\times k+\textit{i}-1]` must be set equal to the :math:`\left(\textit{i}, \textit{j}\right)`\ th element of :math:`\theta_{\textit{l}}`, for :math:`\textit{j} = 1,2,\ldots,k`, for :math:`\textit{i} = 1,2,\ldots,k`, for :math:`\textit{l} = 1,2,\ldots,q`. **var** : float, array-like, shape :math:`\left(k, k\right)` :math:`\mathrm{var}[\textit{i}-1,\textit{j}-1]` must contain the (:math:`\textit{i},\textit{j}`)th element of :math:`\Sigma`, for :math:`\textit{j} = 1,2,\ldots,k`, for :math:`\textit{i} = 1,2,\ldots,k`. Only the lower triangle is required. **comm** : dict, communication object, modified in place Communication structure for the reference vector. If :math:`\mathrm{mode} = 1` or :math:`3`, this argument must have been initialized by a prior call to ``times_mv_varma``. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(k, \mathrm{n}\right)` :math:`\mathrm{x}[\textit{i}-1,\textit{t}-1]` will contain a realization of the :math:`\textit{i}`\ th component of :math:`X_{\textit{t}}`, for :math:`\textit{t} = 1,2,\ldots,n`, for :math:`\textit{i} = 1,2,\ldots,k`. .. _g05pj-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{mode} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{mode} = 0`, :math:`1`, :math:`2` or :math:`3`. (`errno` :math:`2`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`k = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`k\geq 1`. (`errno` :math:`5`) On entry, :math:`\mathrm{ip} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{ip}\geq 0`. (`errno` :math:`6`) On entry, the AR parameters are outside the stationarity region. (`errno` :math:`7`) On entry, :math:`\mathrm{iq} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{iq}\geq 0`. (`errno` :math:`8`) On entry, the moving average parameter matrices are such that the model is non-invertible. (`errno` :math:`9`) On entry, the covariance matrix :math:`\mathrm{var}` is not positive semidefinite to machine precision. (`errno` :math:`11`) :math:`\textit{k}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call. Previous value of :math:`k = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`k = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`13`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. (`errno` :math:`20`) An excessive number of iterations were required by the NAG function used to evaluate the eigenvalues of the matrices used to test for stationarity or invertibility. (`errno` :math:`21`) The reference vector cannot be computed because the AR parameters are too close to the boundary of the stationarity region. (`errno` :math:`22`) An excessive number of iterations were required by the NAG function used to evaluate the eigenvalues of the covariance matrix. **Warns** **NagAlgorithmicWarning** (`errno` :math:`23`) An excessive number of iterations were required by the NAG function used to evaluate the eigenvalues stored in the reference vector. .. _g05pj-py2-py-notes: **Notes** Let the vector :math:`X_t = \left(x_{{1t}}, x_{{2t}}, \ldots, x_{{kt}}\right)^\mathrm{T}`, denote a :math:`k`-dimensional time series which is assumed to follow a vector autoregressive moving average (VARMA) model of the form: .. math:: \begin{array}{cc}X_t-\mu = &\phi_1\left(X_{{t-1}}-\mu \right)+\phi_2\left(X_{{t-2}}-\mu \right)+ \cdots +\phi_p\left(X_{{t-p}}-\mu \right)+\\&\epsilon_t-\theta_1\epsilon_{{t-1}}-\theta_2\epsilon_{{t-2}} - \cdots -\theta_q\epsilon_{{t-q}}\end{array} where :math:`\epsilon_t = \left(\epsilon_{{1t}}, \epsilon_{{2t}}, \ldots, \epsilon_{{kt}}\right)^\mathrm{T}`, is a vector of :math:`k` residual series assumed to be Normally distributed with zero mean and covariance matrix :math:`\Sigma`. The components of :math:`\epsilon_t` are assumed to be uncorrelated at non-simultaneous lags. The :math:`\phi_i`'s and :math:`\theta_j`'s are :math:`k\times k` matrices of parameters. :math:`\left\{\phi_i\right\}`, for :math:`\textit{i} = 1,2,\ldots,p`, are called the autoregressive (AR) parameter matrices, and :math:`\left\{\theta_j\right\}`, for :math:`\textit{j} = 1,2,\ldots,q`, the moving average (MA) parameter matrices. The parameters in the model are thus the :math:`p` :math:`k\times k` :math:`\phi`-matrices, the :math:`q` :math:`k\times k` :math:`\theta`-matrices, the mean vector :math:`\mu` and the residual error covariance matrix :math:`\Sigma`. Let .. math:: A\left(\phi \right) = \left[\begin{array}{ccccccc}\phi_1&I&0&.&.&.&0\\\phi_2&0&I&0&.&.&0\\.&&&.&&&\\.&&&&.&&\\.&&&&&.&\\\phi_{{p-1}}&0&.&.&.&0&I\\\phi_p&0&.&.&.&0&0\end{array}\right]_{{pk\times pk}}\quad \text{ and }\quad B\left(\theta \right) = \left[\begin{array}{ccccccc}\theta_1&I&0&.&.&.&0\\\theta_2&0&I&0&.&.&0\\.&&&.&&&\\.&&&&.&&\\.&&&&&.&\\\theta_{{q-1}}&0&.&.&.&0&I\\\theta_q&0&.&.&.&0&0\end{array}\right]_{{qk\times qk}} where :math:`I` denotes the :math:`k\times k` identity matrix. The model `(1) <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05pjf.html#eqn1>`__ must be both stationary and invertible. The model is said to be stationary if the eigenvalues of :math:`A\left(\phi \right)` lie inside the unit circle and invertible if the eigenvalues of :math:`B\left(\theta \right)` lie inside the unit circle. For :math:`k\geq 6` the VARMA model `(1) <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05pjf.html#eqn1>`__ is recast into state space form and a realization of the state vector at time zero computed. For all other cases the function computes a realization of the pre-observed vectors :math:`X_0,X_{-1},\ldots,X_{{1-p}}`, :math:`\epsilon_0,\epsilon_{-1},\ldots,\epsilon_{{1-q}}`, from `(1) <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05pjf.html#eqn1>`__, see Shea (1988). This realization is then used to generate a sequence of successive time series observations. Note that special action is taken for pure MA models, that is for :math:`p = 0`. At your request a new realization of the time series may be generated more efficiently using the information in a reference vector created during a previous call to ``times_mv_varma``. See the description of the argument :math:`\mathrm{mode}` in :ref:`Parameters <g05pj-py2-py-parameters>` for details. The function returns a realization of :math:`X_1,X_2,\ldots,X_n`. On a successful exit, the recent history is updated and saved in the array :math:`\mathrm{comm}`\ ['r'] so that ``times_mv_varma`` may be called again to generate a realization of :math:`X_{{n+1}},X_{{n+2}},\ldots`, etc. See the description of the argument :math:`\mathrm{mode}` in :ref:`Parameters <g05pj-py2-py-parameters>` for details. Further computational details are given in Shea (1988). Note, however, that ``times_mv_varma`` uses a spectral decomposition rather than a Cholesky factorization to generate the multivariate Normals. Although this method involves more multiplications than the Cholesky factorization method and is thus slightly slower it is more stable when faced with ill-conditioned covariance matrices. A method of assigning the AR and MA coefficient matrices so that the stationarity and invertibility conditions are satisfied is described in Barone (1987). One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``times_mv_varma``. .. _g05pj-py2-py-references: **References** Barone, P, 1987, `A method for generating independent realisations of a multivariate normal stationary and invertible ARMA` :math:`\left(p, q\right)` `process`, J. Time Ser. Anal. (8), 125--130 Shea, B L, 1988, `A note on the generation of independent realisations of a vector autoregressive moving average process`, J. Time Ser. Anal. (9), 403--410 """ raise NotImplementedError
[docs]def times_smooth_exp(mode, n, itype, p, param, init, var, comm, statecomm, e): r""" ``times_smooth_exp`` simulates from an exponential smoothing model, where the model uses either single exponential, double exponential or a Holt--Winters method. .. _g05pm-py2-py-doc: For full information please refer to the NAG Library document for g05pm https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05pmf.html .. _g05pm-py2-py-parameters: **Parameters** **mode** : int Indicates if ``times_smooth_exp`` is continuing from a previous call or, if not, how the initial values are computed. :math:`\mathrm{mode} = 0` Values for :math:`m_0`, :math:`r_0` and :math:`s_{{-\textit{j}}}`, for :math:`\textit{j} = 0,1,\ldots,p-1`, are supplied in :math:`\mathrm{init}`. :math:`\mathrm{mode} = 1` ``times_smooth_exp`` continues from a previous call using values that are supplied in :math:`\mathrm{comm}`\ ['r']. :math:`\mathrm{comm}`\ ['r'] is not updated. :math:`\mathrm{mode} = 2` ``times_smooth_exp`` continues from a previous call using values that are supplied in :math:`\mathrm{comm}`\ ['r']. :math:`\mathrm{comm}`\ ['r'] is updated. **n** : int The number of terms of the time series being generated. **itype** : int The smoothing function. :math:`\mathrm{itype} = 1` Single exponential. :math:`\mathrm{itype} = 2` Brown's double exponential. :math:`\mathrm{itype} = 3` Linear Holt. :math:`\mathrm{itype} = 4` Additive Holt--Winters. :math:`\mathrm{itype} = 5` Multiplicative Holt--Winters. **p** : int If :math:`\mathrm{itype} = 4` or :math:`5`, the seasonal order, :math:`p`, otherwise :math:`\mathrm{p}` is not referenced. **param** : float, array-like, shape :math:`\left(:\right)` Note: the required length for this argument is determined as follows: if :math:`\mathrm{itype}\text{ in } (1, 2)`: :math:`1`; if :math:`\mathrm{itype}=3`: :math:`3`; if :math:`\mathrm{itype}\text{ in } (4, 5)`: :math:`4`; otherwise: :math:`0`. The smoothing parameters. If :math:`\mathrm{itype} = 1` or :math:`2`, :math:`\mathrm{param}[0] = \alpha` and any remaining elements of :math:`\mathrm{param}` are not referenced. If :math:`\mathrm{itype} = 3`, :math:`\mathrm{param}[0] = \alpha`, :math:`\mathrm{param}[1] = \gamma`, :math:`\mathrm{param}[2] = \phi` and any remaining elements of :math:`\mathrm{param}` are not referenced. If :math:`\mathrm{itype} = 4` or :math:`5`, :math:`\mathrm{param}[0] = \alpha`, :math:`\mathrm{param}[1] = \gamma`, :math:`\mathrm{param}[2] = \beta` and :math:`\mathrm{param}[3] = \phi` and any remaining elements of :math:`\mathrm{param}` are not referenced. **init** : float, array-like, shape :math:`\left(:\right)` Note: the required length for this argument is determined as follows: if :math:`\mathrm{itype}=1`: :math:`1`; if :math:`\mathrm{itype}\text{ in } (2, 3)`: :math:`2`; if :math:`\mathrm{itype}\text{ in } (4, 5)`: :math:`{2+\mathrm{p}}`; otherwise: :math:`0`. If :math:`\mathrm{mode} = 0`, the initial values for :math:`m_0`, :math:`r_0` and :math:`s_{{-\textit{j}}}`, for :math:`\textit{j} = 0,1,\ldots,p-1`, used to initialize the smoothing. If :math:`\mathrm{itype} = 1`, :math:`\mathrm{init}[0] = m_0` and any remaining elements of :math:`\mathrm{init}` are not referenced. If :math:`\mathrm{itype} = 2` or :math:`3`, :math:`\mathrm{init}[0] = m_0` and :math:`\mathrm{init}[1] = r_0` and any remaining elements of :math:`\mathrm{init}` are not referenced. If :math:`\mathrm{itype} = 4` or :math:`5`, :math:`\mathrm{init}[0] = m_0`, :math:`\mathrm{init}[1] = r_0` and :math:`\mathrm{init}[2]` to :math:`\mathrm{init}[2+p-1]` hold the values for :math:`s_{{-\textit{j}}}`, for :math:`\textit{j} = 0,1,\ldots,p-1`. Any remaining elements of :math:`\mathrm{init}` are not referenced. **var** : float The variance, :math:`\sigma^2` of the Normal distribution used to generate the errors :math:`\epsilon_i`. If :math:`\mathrm{var}\leq 0.0` then Normally distributed errors are not used. **comm** : dict, communication object, modified in place Communication structure for the reference vector. If :math:`\mathrm{mode} = 1` or :math:`2`, this argument must have been initialized by a prior call to ``times_smooth_exp``. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **e** : float, array-like, shape :math:`\left(\textit{en}\right)` If :math:`\textit{en} > 0` and :math:`\mathrm{var}\leq 0.0`, a vector from which the errors, :math:`\epsilon_t` are randomly drawn, with replacement. If :math:`\textit{en}\leq 0`, :math:`\mathrm{e}` is not referenced. **Returns** **x** : float, ndarray, shape :math:`\left(\mathrm{n}\right)` The generated time series, :math:`x_{\textit{t}}`, for :math:`\textit{t} = 1,2,\ldots,n`. .. _g05pm-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{mode} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{mode} = 0`, :math:`1` or :math:`2`. (`errno` :math:`2`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{itype} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{itype} = 1`, :math:`2`, :math:`3`, :math:`4` or :math:`5`. (`errno` :math:`4`) On entry, :math:`\mathrm{p} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: if :math:`\mathrm{itype} = 4` or :math:`5`, :math:`\mathrm{p}\geq 2`. (`errno` :math:`5`) On entry, :math:`\mathrm{param}[\langle\mathit{\boldsymbol{value}}\rangle] = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`0\leq \mathrm{param}[i]\leq 1`. (`errno` :math:`5`) On entry, :math:`\mathrm{param}[\langle\mathit{\boldsymbol{value}}\rangle] = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: if :math:`\mathrm{itype} = 2`, :math:`0 < \mathrm{param}[i]\leq 1`. (`errno` :math:`5`) On entry, :math:`\mathrm{param}[\langle\mathit{\boldsymbol{value}}\rangle] = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{param}[i]\geq 0`. (`errno` :math:`8`) On entry, some of the elements of the array :math:`\mathrm{comm}`\ ['r'] have been corrupted or have not been initialized. (`errno` :math:`9`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. (`errno` :math:`12`) Model unsuitable for multiplicative Holt--Winter, try a different set of parameters. .. _g05pm-py2-py-notes: **Notes** ``times_smooth_exp`` returns :math:`\left\{x_t:t = 1,2,\ldots,n\right\}`, a realization of a time series from an exponential smoothing model defined by one of five smoothing functions: Single Exponential Smoothing .. math:: \begin{array}{ccc}x_t& = & m_{{t-1}} + \epsilon_t \\m_t& = & \alpha x_t + \left(1-\alpha \right) m_{{t-1}} \end{array} Brown Double Exponential Smoothing .. math:: \begin{array}{ccc}x_t& = & m_{{t-1}} + \frac{r_{{t-1}}}{\alpha } + \epsilon_t \\m_t& = & \alpha x_t + \left(1-\alpha \right) m_{{t-1}} \\r_t& = & \alpha \left(m_t-m_{{t-1}}\right) + \left(1-\alpha \right) r_{{t-1}} \end{array} Linear Holt Exponential Smoothing .. math:: \begin{array}{ccc}x_t& = & m_{{t-1}} + \phi r_{{t-1}} + \epsilon_t \\m_t& = & \alpha x_t + \left(1-\alpha \right) \left(m_{{t-1}}+\phi r_{{t-1}}\right) \\r_t& = & \gamma \left(m_t-m_{{t-1}}\right) + \left(1-\gamma \right) \phi r_{{t-1}} \end{array} Additive Holt--Winters Smoothing .. math:: \begin{array}{ccc}x_t& = & m_{{t-1}} + \phi r_{{t-1}} + s_{{t-1-p}} + \epsilon_t \\ m_t & = & \alpha \left(x_t-s_{{t-p}}\right) + \left(1-\alpha \right) \left(m_{{t-1}}+\phi r_{{t-1}}\right) \\r_t& = & \gamma \left(m_t-m_{{t-1}}\right) + \left(1-\gamma \right) \phi r_{{t-1}} \\s_t& = & \beta \left(x_t-m_t\right) + \left(1-\beta \right) s_{{t-p}} \end{array} Multiplicative Holt--Winters Smoothing .. math:: \begin{array}{ccc}x_t& = & \left(m_{{t-1}}+\phi r_{{t-1}}\right) \times s_{{t-1-p}} + \epsilon_t \\m_t& = & \alpha x_t / s_{{t-p}} + \left(1-\alpha \right) \left(m_{{t-1}}+\phi r_{{t-1}}\right) \\r_t& = & \gamma \left(m_t-m_{{t-1}}\right) + \left(1-\gamma \right) \phi r_{{t-1}} \\s_t& = & \beta x_t / m_t + \left(1-\beta \right) s_{{t-p}} \end{array} where :math:`m_t` is the mean, :math:`r_t` is the trend and :math:`s_t` is the seasonal component at time :math:`t` with :math:`p` being the seasonal order. The errors, :math:`\epsilon_t` are either drawn from a normal distribution with mean zero and variance :math:`\sigma^2` or randomly sampled, with replacement, from a user-supplied vector. .. _g05pm-py2-py-references: **References** Chatfield, C, 1980, `The Analysis of Time Series`, Chapman and Hall """ raise NotImplementedError
[docs]def kfold_xyw(k, fold, x, statecomm, sordx=1, y=None, w=None): r""" ``kfold_xyw`` generates training and validation datasets suitable for use in cross-validation or jack-knifing. .. _g05pv-py2-py-doc: For full information please refer to the NAG Library document for g05pv https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05pvf.html .. _g05pv-py2-py-parameters: **Parameters** **k** : int :math:`K`, the number of folds. **fold** : int The number of the fold to return as the validation dataset. On the first call to ``kfold_xyw`` :math:`\mathrm{fold}` should be set to :math:`1` and then incremented by one at each subsequent call until all :math:`K` sets of training and validation datasets have been produced. See `Further Comments <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05pvf.html#fcomments>`__ for more details on how a different calling sequence can be used. **x** : float, ndarray, shape :math:`\left(:, :\right)`, modified in place Note: the required extent for this argument in dimension 1 is determined as follows: if :math:`\mathrm{sordx}=2`: :math:`m`; otherwise: :math:`n`. Note: the required extent for this argument in dimension 2 is determined as follows: if :math:`\mathrm{sordx}=1`: :math:`m`; if :math:`\mathrm{sordx}=2`: :math:`n`; otherwise: :math:`0`. The way the data is stored in :math:`\mathrm{x}` is defined by :math:`\mathrm{sordx}`. If :math:`\mathrm{sordx} = 1`, :math:`\mathrm{x}[\textit{i}-1,\textit{j}-1]` contains the :math:`\textit{i}`\ th observation for the :math:`\textit{j}`\ th variable, for :math:`i = 1,2,\ldots,n` and :math:`j = 1,2,\ldots,m`. If :math:`\mathrm{sordx} = 2`, :math:`\mathrm{x}[\textit{j}-1,\textit{i}-1]` contains the :math:`\textit{i}`\ th observation for the :math:`\textit{j}`\ th variable, for :math:`i = 1,2,\ldots,n` and :math:`j = 1,2,\ldots,m`. `On entry`: if :math:`\mathrm{fold} = 1`, :math:`\mathrm{x}` must hold :math:`X_o`, the values of :math:`X` for the original dataset, otherwise, :math:`\mathrm{x}` must not be changed since the last call to ``kfold_xyw``. `On exit`: values of :math:`X` for the training and validation datasets, with :math:`X_t` held in observations :math:`1` to :math:`\mathrm{nt}` and :math:`X_v` in observations :math:`\mathrm{nt}+1` to :math:`n`. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **sordx** : int, optional Determines how variables are stored in :math:`\mathrm{x}`. **y** : None or float, ndarray, shape :math:`\left(:\right)`, optional, modified in place Note: the required length for this argument is determined as follows: if :math:`\mathrm{y}\text{ is not }\mathbf{None}`: :math:`n`; otherwise: :math:`0`. If the original dataset does not include :math:`y_o` then :math:`\mathrm{y}` must be set to **None**. `Optionally, on entry`: :math:`y_o`, the values of :math:`y` for the original dataset. If :math:`\mathrm{fold} \neq 1`, :math:`\mathrm{y}` must hold the vector returned in :math:`\textit{sy}` by the last call to ``kfold_xyw``. `On exit`, if not **None** on entry: values of :math:`y` for the training and validation datasets, with :math:`y_t` held in elements :math:`1` to :math:`\mathrm{nt}` and :math:`y_v` in elements :math:`\mathrm{nt}+1` to :math:`n`. **w** : None or float, ndarray, shape :math:`\left(:\right)`, optional, modified in place Note: the required length for this argument is determined as follows: if :math:`\mathrm{w}\text{ is not }\mathbf{None}`: :math:`n`; otherwise: :math:`0`. `Optionally, on entry`: if :math:`\mathrm{fold} \neq 1`, :math:`\mathrm{w}` must hold the vector returned in :math:`\textit{sw}` by the last call to ``kfold_xyw``. `On exit`, if not **None** on entry: values of :math:`w` for the training and validation datasets, with :math:`w_t` held in elements :math:`1` to :math:`\mathrm{nt}` and :math:`w_v` in elements :math:`\mathrm{nt}+1` to :math:`n`. **Returns** **nt** : int :math:`n_t`, the number of observations in the training dataset. .. _g05pv-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`11`) On entry, :math:`\mathrm{k} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`n = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`2\leq \mathrm{k}\leq n`. (`errno` :math:`21`) On entry, :math:`\mathrm{fold} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{k} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`1\leq \mathrm{fold}\leq \mathrm{k}`. (`errno` :math:`31`) On entry, :math:`n = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`n\geq 1`. (`errno` :math:`41`) On entry, :math:`m = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`m\geq 1`. (`errno` :math:`51`) On entry, :math:`\mathrm{sordx} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{sordx} = 1` or :math:`2`. (`errno` :math:`71`) On entry, :math:`\textit{ldx} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`n = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: if :math:`\mathrm{sordx} = 1`, :math:`\textit{ldx}\geq n`. (`errno` :math:`72`) On entry, :math:`\textit{ldx} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`m = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: if :math:`\mathrm{sordx} = 2`, :math:`\textit{ldx}\geq m`. (`errno` :math:`131`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. **Warns** **NagAlgorithmicWarning** (`errno` :math:`61`) More than :math:`50\%` of the data did not move when the data was shuffled. :math:`\langle\mathit{\boldsymbol{value}}\rangle` of the :math:`\langle\mathit{\boldsymbol{value}}\rangle` observations stayed put. .. _g05pv-py2-py-notes: **Notes** Let :math:`X_o` denote a matrix of :math:`n` observations on :math:`m` variables and :math:`y_o` and :math:`w_o` each denote a vector of length :math:`n`. For example, :math:`X_o` might represent a matrix of independent variables, :math:`y_o` the dependent variable and :math:`w_o` the associated weights in a weighted regression. ``kfold_xyw`` generates a series of training datasets, denoted by the matrix, vector, vector triplet :math:`\left(X_t,y_t,w_t\right)` of :math:`n_t` observations, and validation datasets, denoted :math:`\left(X_v,y_v,w_v\right)` with :math:`n_v` observations. These training and validation datasets are generated as follows. Each of the original :math:`n` observations is randomly assigned to one of :math:`K` equally sized groups or folds. For the :math:`k`\ th sample the validation dataset consists of those observations in group :math:`k` and the training dataset consists of all those observations not in group :math:`k`. Therefore, at most :math:`K` samples can be generated. If :math:`n` is not divisible by :math:`K` then the observations are assigned to groups as evenly as possible, therefore, any group will be at most one observation larger or smaller than any other group. When using :math:`K = n` the resulting datasets are suitable for leave-one-out cross-validation, or the training dataset on its own for jack-knifing. When using :math:`K\neq n` the resulting datasets are suitable for :math:`K`-fold cross-validation. Datasets suitable for reversed cross-validation can be obtained by switching the training and validation datasets, i.e., use the :math:`k`\ th group as the training dataset and the rest of the data as the validation dataset. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``kfold_xyw``. See Also -------- :meth:`naginterfaces.library.examples.correg.glm_binomial_ex.main` """ raise NotImplementedError
[docs]def subsamp_xyw(nt, x, statecomm, sordx=1, y=None, w=None): r""" ``subsamp_xyw`` generates a dataset suitable for use with repeated random sub-sampling validation. .. _g05pw-py2-py-doc: For full information please refer to the NAG Library document for g05pw https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05pwf.html .. _g05pw-py2-py-parameters: **Parameters** **nt** : int :math:`n_t`, the number of observations in the training dataset. **x** : float, ndarray, shape :math:`\left(:, :\right)`, modified in place Note: the required extent for this argument in dimension 1 is determined as follows: if :math:`\mathrm{sordx}=2`: :math:`m`; otherwise: :math:`n`. Note: the required extent for this argument in dimension 2 is determined as follows: if :math:`\mathrm{sordx}=1`: :math:`m`; if :math:`\mathrm{sordx}=2`: :math:`n`; otherwise: :math:`0`. The way the data is stored in :math:`\mathrm{x}` is defined by :math:`\mathrm{sordx}`. If :math:`\mathrm{sordx} = 1`, :math:`\mathrm{x}[\textit{i}-1,\textit{j}-1]` contains the :math:`\textit{i}`\ th observation for the :math:`\textit{j}`\ th variable, for :math:`i = 1,2,\ldots,n` and :math:`j = 1,2,\ldots,m`. If :math:`\mathrm{sordx} = 2`, :math:`\mathrm{x}[\textit{j}-1,\textit{i}-1]` contains the :math:`\textit{i}`\ th observation for the :math:`\textit{j}`\ th variable, for :math:`i = 1,2,\ldots,n` and :math:`j = 1,2,\ldots,m`. `On entry`: :math:`\mathrm{x}` must hold :math:`X_o`, the values of :math:`X` for the original dataset. This may be the same :math:`\mathrm{x}` as updated by a previous call to ``subsamp_xyw``. `On exit`: values of :math:`X` for the training and validation datasets, with :math:`X_t` held in observations :math:`1` to :math:`\mathrm{nt}` and :math:`X_v` in observations :math:`\mathrm{nt}+1` to :math:`n`. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **sordx** : int, optional Determines how variables are stored in :math:`\mathrm{x}`. **y** : None or float, ndarray, shape :math:`\left(:\right)`, optional, modified in place Note: the required length for this argument is determined as follows: if :math:`\mathrm{y}\text{ is not }\mathbf{None}`: :math:`n`; otherwise: :math:`0`. `Optionally, on entry`: :math:`\mathrm{y}` must hold :math:`y_o`, the values of :math:`y` for the original dataset. This may be the same :math:`\mathrm{y}` as updated by a previous call to ``subsamp_xyw``. `On exit`, if not **None** on entry: values of :math:`y` for the training and validation datasets, with :math:`y_t` held in elements :math:`1` to :math:`\mathrm{nt}` and :math:`y_v` in elements :math:`\mathrm{nt}+1` to :math:`n`. **w** : None or float, ndarray, shape :math:`\left(:\right)`, optional, modified in place Note: the required length for this argument is determined as follows: if :math:`\mathrm{w}\text{ is not }\mathbf{None}`: :math:`n`; otherwise: :math:`0`. `Optionally, on entry`: :math:`\mathrm{w}` must hold :math:`w_o`, the values of :math:`w` for the original dataset. This may be the same :math:`\mathrm{w}` as updated by a previous call to ``subsamp_xyw``. `On exit`, if not **None** on entry: values of :math:`w` for the training and validation datasets, with :math:`w_t` held in elements :math:`1` to :math:`\mathrm{nt}` and :math:`w_v` in elements :math:`\mathrm{nt}+1` to :math:`n`. .. _g05pw-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`11`) On entry, :math:`\mathrm{nt} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`n = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`1\leq \mathrm{nt}\leq n`. (`errno` :math:`21`) On entry, :math:`n = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`n\geq 1`. (`errno` :math:`31`) On entry, :math:`m = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`m\geq 1`. (`errno` :math:`41`) On entry, :math:`\mathrm{sordx} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{sordx} = 1` or :math:`2`. (`errno` :math:`61`) On entry, :math:`\textit{ldx} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`n = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: if :math:`\mathrm{sordx} = 1`, :math:`\textit{ldx}\geq n`. (`errno` :math:`62`) On entry, :math:`\textit{ldx} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`m = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: if :math:`\mathrm{sordx} = 2`, :math:`\textit{ldx}\geq m`. (`errno` :math:`111`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05pw-py2-py-notes: **Notes** Let :math:`X_o` denote a matrix of :math:`n` observations on :math:`m` variables and :math:`y_o` and :math:`w_o` each denote a vector of length :math:`n`. For example, :math:`X_o` might represent a matrix of independent variables, :math:`y_o` the dependent variable and :math:`w_o` the associated weights in a weighted regression. ``subsamp_xyw`` generates a series of training datasets, denoted by the matrix, vector, vector triplet :math:`\left(X_t,y_t,w_t\right)` of :math:`n_t` observations, and validation datasets, denoted :math:`\left(X_v,y_v,w_v\right)` with :math:`n_v` observations. These training and validation datasets are generated by randomly assigning each observation to either the training dataset or the validation dataset. The resulting datasets are suitable for use with repeated random sub-sampling validation. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``subsamp_xyw``. """ raise NotImplementedError
[docs]def matrix_orthog(side, init, statecomm, a): r""" ``matrix_orthog`` generates a random orthogonal matrix. .. _g05px-py2-py-doc: For full information please refer to the NAG Library document for g05px https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05pxf.html .. _g05px-py2-py-parameters: **Parameters** **side** : str, length 1 Indicates whether the matrix :math:`A` is multiplied on the left or right by the random orthogonal matrix :math:`U`. :math:`\mathrm{side} = \texttt{'L'}` The matrix :math:`A` is multiplied on the left, i.e., premultiplied. :math:`\mathrm{side} = \texttt{'R'}` The matrix :math:`A` is multiplied on the right, i.e., post-multiplied. **init** : str, length 1 Indicates whether or not :math:`\mathrm{a}` should be initialized to the identity matrix. :math:`\mathrm{init} = \texttt{'I'}` :math:`\mathrm{a}` is initialized to the identity matrix. :math:`\mathrm{init} = \texttt{'N'}` :math:`\mathrm{a}` is not initialized and the matrix :math:`A` must be supplied in :math:`\mathrm{a}`. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **a** : float, array-like, shape :math:`\left(m, n\right)` If :math:`\mathrm{init} = \texttt{'N'}`, :math:`\mathrm{a}` must contain the matrix :math:`A`. **Returns** **a** : float, ndarray, shape :math:`\left(m, n\right)` The matrix :math:`UA` when :math:`\mathrm{side} = \texttt{'L'}` or the matrix :math:`AU` when :math:`\mathrm{side} = \texttt{'R'}`. .. _g05px-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{side}` is not valid: :math:`\mathrm{side} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`2`) On entry, :math:`\mathrm{init}` is not valid: :math:`\mathrm{init} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`3`) On entry, :math:`\mathrm{side} = \langle\mathit{\boldsymbol{value}}\rangle`, :math:`m = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: if :math:`\mathrm{side} = \texttt{'L'}`, :math:`m > 1`; otherwise :math:`m\geq 1`. (`errno` :math:`4`) On entry, :math:`\mathrm{side} = \langle\mathit{\boldsymbol{value}}\rangle`, :math:`n = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: if :math:`\mathrm{side} = \texttt{'R'}`, :math:`n > 1`; otherwise :math:`n\geq 1`. (`errno` :math:`5`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. (`errno` :math:`8`) On entry, :math:`\mathrm{side} = \langle\mathit{\boldsymbol{value}}\rangle`, :math:`m = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: if :math:`\mathrm{side} = \texttt{'L'}`, :math:`m > 1`; otherwise :math:`m\geq 1`. (`errno` :math:`8`) On entry, :math:`\mathrm{side} = \langle\mathit{\boldsymbol{value}}\rangle`, :math:`n = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: if :math:`\mathrm{side} = \texttt{'R'}`, :math:`n > 1`; otherwise :math:`n\geq 1`. .. _g05px-py2-py-notes: **Notes** ``matrix_orthog`` pre - or post-multiplies an :math:`m\times n` matrix :math:`A` by a random orthogonal matrix :math:`U`, overwriting :math:`A`. The matrix :math:`A` may optionally be initialized to the identity matrix before multiplying by :math:`U`, hence :math:`U` is returned. :math:`U` is generated using the method of Stewart (1980). The algorithm can be summarised as follows. Let :math:`x_1,x_2,\ldots,x_{{n-1}}` follow independent multinormal distributions with zero mean and variance :math:`I\sigma^2` and dimensions :math:`n,n-1,\ldots,2`; let :math:`H_j = \mathrm{diag}\left(I_{{j-1}},H_j^*\right)`, where :math:`I_{{j-1}}` is the identity matrix and :math:`H_j^*` is the Householder transformation that reduces :math:`x_j` to :math:`r_{{jj}}e_1`, :math:`e_1` being the vector with first element one and the remaining elements zero and :math:`r_{{jj}}` being a scalar, and let :math:`D = \mathrm{diag}\left(\mathrm{sign}\left(r_{11}\right),\mathrm{sign}\left(r_{22}\right),\ldots,\mathrm{sign}\left(r_{{nn}}\right)\right)`. Then the product :math:`U = DH_1H_2\ldots H_{{n-1}}` is a random orthogonal matrix distributed according to the Haar measure over the set of orthogonal matrices of :math:`n`. See Theorem 3.3 in Stewart (1980). One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``matrix_orthog``. .. _g05px-py2-py-references: **References** Stewart, G W, 1980, `The efficient generation of random orthogonal matrices with an application to condition estimates`, SIAM J. Numer. Anal. (17), 403--409 """ raise NotImplementedError
[docs]def matrix_corr(d, statecomm, eps=0.00001): r""" ``matrix_corr`` generates a random correlation matrix with given eigenvalues. .. _g05py-py2-py-doc: For full information please refer to the NAG Library document for g05py https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05pyf.html .. _g05py-py2-py-parameters: **Parameters** **d** : float, array-like, shape :math:`\left(n\right)` The :math:`n` eigenvalues, :math:`\lambda_{\textit{i}}`, for :math:`\textit{i} = 1,2,\ldots,n`. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **eps** : float, optional The maximum acceptable error in the diagonal elements. **Returns** **c** : float, ndarray, shape :math:`\left(n, n\right)` A random correlation matrix, :math:`C`, of dimension :math:`n`. .. _g05py-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`n = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`n\geq 1`. (`errno` :math:`2`) On entry, an eigenvalue is negative. (`errno` :math:`2`) On entry, the eigenvalues do not sum to :math:`\textit{n}`. (`errno` :math:`3`) On entry, :math:`\mathrm{eps} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{eps}\geq n\times \text{machine precision}`. (`errno` :math:`4`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. (`errno` :math:`5`) The diagonals of the returned matrix are not unity, try increasing the value of :math:`\mathrm{eps}`, or rerun the code using a different seed. .. _g05py-py2-py-notes: **Notes** Given :math:`n` eigenvalues, :math:`\lambda_1,\lambda_2,\ldots,\lambda_n`, such that .. math:: \sum_{{i = 1}}^n\lambda_i = n and .. math:: \lambda_i\geq 0\text{, }\quad i = 1,2,\ldots,n\text{,} ``matrix_corr`` will generate a random correlation matrix, :math:`C`, of dimension :math:`n`, with eigenvalues :math:`\lambda_1,\lambda_2,\ldots,\lambda_n`. The method used is based on that described by Lin and Bendel (1985). Let :math:`D` be the diagonal matrix with values :math:`\lambda_1,\lambda_2,\ldots,\lambda_n` and let :math:`A` be a random orthogonal matrix generated by :meth:`matrix_orthog` then the matrix :math:`C_0 = ADA^\mathrm{T}` is a random covariance matrix with eigenvalues :math:`\lambda_1,\lambda_2,\ldots,\lambda_n`. The matrix :math:`C_0` is transformed into a correlation matrix by means of :math:`n-1` elementary rotation matrices :math:`P_i` such that :math:`C = P_{{n-1}}P_{{n-2}}\ldots P_1C_0 P_1^\mathrm{T}\ldots P_{{n-2}}^\mathrm{T} P_{{n-1}}^\mathrm{T}`. The restriction on the sum of eigenvalues implies that for any diagonal element of :math:`C_0 > 1`, there is another diagonal element :math:`\text{} < 1`. The :math:`P_i` are constructed from such pairs, chosen at random, to produce a unit diagonal element corresponding to the first element. This is repeated until all diagonal elements are :math:`1` to within a given tolerance :math:`\epsilon`. The randomness of :math:`C` should be interpreted only to the extent that :math:`A` is a random orthogonal matrix and :math:`C` is computed from :math:`A` using the :math:`P_i` which are chosen as arbitrarily as possible. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``matrix_corr``. .. _g05py-py2-py-references: **References** Lin, S P and Bendel, R B, 1985, `Algorithm AS 213: Generation of population correlation on matrices with specified eigenvalues`, Appl. Statist. (34), 193--198 """ raise NotImplementedError
[docs]def matrix_2waytable(mode, totr, totc, comm, statecomm): r""" ``matrix_2waytable`` generates a random two-way table. .. _g05pz-py2-py-doc: For full information please refer to the NAG Library document for g05pz https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05pzf.html .. _g05pz-py2-py-parameters: **Parameters** **mode** : int A code for selecting the operation to be performed by the function. :math:`\mathrm{mode} = 0` Set up reference vector only. :math:`\mathrm{mode} = 1` Generate two-way table using reference vector set up in a prior call to ``matrix_2waytable``. :math:`\mathrm{mode} = 2` Set up reference vector and generate two-way table. **totr** : int, array-like, shape :math:`\left(\textit{nrow}\right)` The :math:`m` row totals, :math:`R_{\textit{i}}`, for :math:`\textit{i} = 1,2,\ldots,m`. **totc** : int, array-like, shape :math:`\left(\textit{ncol}\right)` The :math:`n` column totals, :math:`C_{\textit{j}}`, for :math:`\textit{j} = 1,2,\ldots,n`. **comm** : dict, communication object, modified in place Communication structure for the reference vector. If :math:`\mathrm{mode} = 1`, this argument must have been initialized by a prior call to ``matrix_2waytable``. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : None or int, ndarray, shape :math:`\left(\textit{nrow}, \textit{ncol}\right)` If :math:`\mathrm{mode} = 1` or :math:`2`, a pseudorandom two-way :math:`m\times n` table, :math:`X`, with element :math:`\mathrm{x}[i-1,j-1]` containing the :math:`\left(i, j\right)`\ th entry in the table such that :math:`\sum_{1}^{m}\mathrm{x}[i-1,j-1] = \mathrm{totc}[j-1]` and :math:`\sum_{1}^{n}\mathrm{x}[i-1,j-1] = \mathrm{totr}[i-1]` .. _g05pz-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{mode} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{mode} = 0`, :math:`1` or :math:`2`. (`errno` :math:`2`) On entry, :math:`\textit{nrow} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\textit{nrow}\geq 2`. (`errno` :math:`3`) On entry, :math:`\textit{ncol} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\textit{ncol}\geq 2`. (`errno` :math:`4`) On entry, at least one element of :math:`\mathrm{totr}` is negative or :math:`\mathrm{totr}` sums to zero. (`errno` :math:`5`) On entry, :math:`\mathrm{totc}` has at least one negative element. (`errno` :math:`6`) :math:`\textit{nrow}` or :math:`\textit{ncol}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call. Previous value of :math:`\textit{nrow} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\textit{nrow} = \langle\mathit{\boldsymbol{value}}\rangle`. Previous value of :math:`\textit{ncol} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\textit{ncol} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`8`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. (`errno` :math:`15`) On entry, the arrays :math:`\mathrm{totr}` and :math:`\mathrm{totc}` do not sum to the same total: :math:`\mathrm{totr}` array total is :math:`\langle\mathit{\boldsymbol{value}}\rangle`, :math:`\mathrm{totc}` array total is :math:`\langle\mathit{\boldsymbol{value}}\rangle`. .. _g05pz-py2-py-notes: **Notes** Given :math:`m` row totals :math:`R_i` and :math:`n` column totals :math:`C_j` (with :math:`\sum_{{i = 1}}^mR_i = \sum_{{j = 1}}^nC_j = T`, say), ``matrix_2waytable`` will generate a pseudorandom two-way table of integers such that the row and column totals are satisfied. The method used is based on that described by Patefield (1981) which is most efficient when :math:`T` is large relative to the number of table entries :math:`m\times n` (i.e., :math:`T > 2mn`). Entries are generated one row at a time and one entry at a time within a row. Each entry is generated using the conditional probability distribution for that entry given the entries in the previous rows and the previous entries in the same row. A reference vector is used to store computed values that can be reused in the generation of new tables with the same row and column totals. ``matrix_2waytable`` can be called to simply set up the reference vector, or to generate a two-way table using a reference vector set up in a previous call, or it can combine both functions in a single call. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``matrix_2waytable``. .. _g05pz-py2-py-references: **References** Patefield, W M, 1981, `An efficient method of generating` :math:`R\times C` `tables with given row and column totals`, Appl. Stats. (30), 91--97 """ raise NotImplementedError
[docs]def copula_students_t(mode, n, df, c, comm, statecomm): r""" ``copula_students_t`` sets up a reference vector and generates an array of pseudorandom numbers from a Student's :math:`t` copula with :math:`\nu` degrees of freedom and covariance matrix :math:`\frac{\nu }{{\nu -2}}C`. .. _g05rc-py2-py-doc: For full information please refer to the NAG Library document for g05rc https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05rcf.html .. _g05rc-py2-py-parameters: **Parameters** **mode** : int A code for selecting the operation to be performed by the function. :math:`\mathrm{mode} = 0` Set up reference vector only. :math:`\mathrm{mode} = 1` Generate variates using reference vector set up in a prior call to ``copula_students_t``. :math:`\mathrm{mode} = 2` Set up reference vector and generate variates. **n** : int :math:`n`, the number of random variates required. **df** : int :math:`\nu`, the number of degrees of freedom of the distribution. **c** : float, array-like, shape :math:`\left(m, m\right)` Matrix which, along with :math:`\mathrm{df}`, defines the covariance of the distribution. Only the upper triangle need be set. **comm** : dict, communication object, modified in place Communication structure for the reference vector. If :math:`\mathrm{mode} = 1`, this argument must have been initialized by a prior call to ``copula_students_t``. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : None or float, ndarray, shape :math:`\left(\mathrm{n}, :\right)` The array of values from a multivariate Student's :math:`t` copula, with :math:`\mathrm{x}[i-1,j-1]` holding the :math:`j`\ th dimension for the :math:`i`\ th variate. .. _g05rc-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{mode} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{mode} = 0`, :math:`1` or :math:`2`. (`errno` :math:`2`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{df} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{df}\geq 3`. (`errno` :math:`4`) On entry, :math:`m = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`m > 0`. (`errno` :math:`5`) On entry, the covariance matrix :math:`C` is not positive semidefinite to machine precision. (`errno` :math:`7`) :math:`\textit{m}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call. Previous value of :math:`m = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`m = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`9`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05rc-py2-py-notes: **Notes** The Student's :math:`t` copula, :math:`G`, is defined by .. math:: G\left(u_1,u_2,\ldots,u_m;C\right) = T_{{\nu,C}}^m\left(t_{{\nu,C_{11}}}^{-1}\left(u_1\right),t_{{\nu,C_{22}}}^{-1}\left(u_2\right),\ldots,t_{{\nu,C_{\textit{mm}}}}^{-1}\left(u_m\right)\right) where :math:`m` is the number of dimensions, :math:`T_{{\nu,C}}^m` is the multivariate Student's :math:`t` density function with :math:`\nu` degrees of freedom, mean zero and covariance matrix :math:`\frac{\nu }{{\nu -2}}C` and :math:`t_{{\nu,C_{\textit{ii}}}}^{-1}` is the inverse of the univariate Student's :math:`t` density function with :math:`\nu` degrees of freedom, zero mean and variance :math:`\frac{\nu }{{\nu -2}}C_{\textit{ii}}`. :meth:`multivar_students_t` is used to generate a vector from a multivariate Student's :math:`t` distribution and :meth:`stat.prob_students_t <naginterfaces.library.stat.prob_students_t>` is used to convert each element of that vector into a uniformly distributed value between zero and one. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``copula_students_t``. .. _g05rc-py2-py-references: **References** Nelsen, R B, 1998, `An Introduction to Copulas. Lecture Notes in Statistics 139`, Springer Sklar, A, 1973, `Random variables: joint distribution functions and copulas`, Kybernetika (9), 499--460 See Also -------- :meth:`naginterfaces.library.examples.rand.copula_students_t_ex.main` """ raise NotImplementedError
[docs]def copula_normal(mode, n, c, comm, statecomm): r""" ``copula_normal`` sets up a reference vector and generates an array of pseudorandom numbers from a Normal (Gaussian) copula with covariance matrix :math:`C`. .. _g05rd-py2-py-doc: For full information please refer to the NAG Library document for g05rd https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05rdf.html .. _g05rd-py2-py-parameters: **Parameters** **mode** : int A code for selecting the operation to be performed by the function. :math:`\mathrm{mode} = 0` Set up reference vector only. :math:`\mathrm{mode} = 1` Generate variates using reference vector set up in a prior call to ``copula_normal``. :math:`\mathrm{mode} = 2` Set up reference vector and generate variates. **n** : int :math:`n`, the number of random variates required. **c** : float, array-like, shape :math:`\left(m, m\right)` The covariance matrix of the distribution. Only the upper triangle need be set. **comm** : dict, communication object, modified in place Communication structure for the reference vector. If :math:`\mathrm{mode} = 1`, this argument must have been initialized by a prior call to ``copula_normal``. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : None or float, ndarray, shape :math:`\left(\mathrm{n}, :\right)` The array of values from a multivariate Gaussian copula, with :math:`\mathrm{x}[i-1,j-1]` holding the :math:`j`\ th dimension for the :math:`i`\ th variate. .. _g05rd-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{mode} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{mode} = 0`, :math:`1` or :math:`2`. (`errno` :math:`2`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`m = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`m > 0`. (`errno` :math:`4`) On entry, the covariance matrix :math:`C` is not positive semidefinite to machine precision. (`errno` :math:`6`) :math:`\textit{m}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call. Previous value of :math:`m = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`m = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`8`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05rd-py2-py-notes: **Notes** The Gaussian copula, :math:`G`, is defined by .. math:: G\left(u_1,u_2,\ldots,u_m;C\right) = \Phi_C\left(\phi_{C_{11}}^{-1}\left(u_1\right),\phi_{C_{22}}^{-1}\left(u_2\right),\ldots,\phi_{C_{\textit{mm}}}^{-1}\left(u_m\right)\right) where :math:`m` is the number of dimensions, :math:`\Phi_C` is the multivariate Normal density function with mean zero and covariance matrix :math:`C` and :math:`\phi_{C_{\textit{ii}}}^{-1}` is the inverse of the univariate Normal density function with mean zero and variance :math:`C_{\textit{ii}}`. :meth:`multivar_normal` is used to generate a vector from a multivariate Normal distribution and :meth:`stat.prob_normal <naginterfaces.library.stat.prob_normal>` is used to convert each element of that vector into a uniformly distributed value between zero and one. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``copula_normal``. .. _g05rd-py2-py-references: **References** Nelsen, R B, 1998, `An Introduction to Copulas. Lecture Notes in Statistics 139`, Springer Sklar, A, 1973, `Random variables: joint distribution functions and copulas`, Kybernetika (9), 499--460 """ raise NotImplementedError
[docs]def copula_clayton_bivar(n, theta, sorder, statecomm): r""" ``copula_clayton_bivar`` generates pseudorandom uniform bivariates with joint distribution of a Clayton/Cook--Johnson Archimedean copula. .. _g05re-py2-py-doc: For full information please refer to the NAG Library document for g05re https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05ref.html .. _g05re-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of bivariates to generate. **theta** : float :math:`\theta`, the copula parameter. **sorder** : int Determines the storage order of variates; the :math:`\left(\textit{i}, \textit{j}\right)`\ th variate is stored in :math:`\mathrm{x}[\textit{i}-1,\textit{j}-1]` if :math:`\mathrm{sorder} = 1`, and :math:`\mathrm{x}[\textit{j}-1,\textit{i}-1]` if :math:`\mathrm{sorder} = 2`, for :math:`\textit{j} = 1,2,\ldots,2`, for :math:`\textit{i} = 1,2,\ldots,n`. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(:, :\right)` The :math:`n` bivariate uniforms with joint distribution described by :math:`C_{\theta }`, with :math:`\mathrm{x}[i-1,j-1]` holding the :math:`i`\ th value for the :math:`j`\ th dimension if :math:`\mathrm{sorder} = 1` and the :math:`j`\ th value for the :math:`i`\ th dimension if :math:`\mathrm{sorder} = 2`. .. _g05re-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, corrupt :math:`\mathrm{statecomm}`\ ['state'] argument. (`errno` :math:`2`) On entry, invalid :math:`\mathrm{theta}`: :math:`\mathrm{theta} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{theta}\geq {-1.0}`. (`errno` :math:`3`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`4`) On entry, invalid :math:`\mathrm{sorder}`. Constraint: :math:`\mathrm{sorder} = 1` or :math:`2`. .. _g05re-py2-py-notes: **Notes** Generates pseudorandom uniform bivariates :math:`\left\{u_1, u_2\right\} \in \left(0, 1\right]^2` whose joint distribution is the Clayton/Cook--Johnson Archimedean copula :math:`C_{\theta }` with parameter :math:`\theta`, given by .. math:: C_{\theta } = \left[\mathrm{max}\left({u_1^{{-\theta }}+u_2^{{-\theta }}-1}, 0\right)\right]^{{-1/\theta }}\text{, }\quad \theta \in \left(-1, \infty \right)∖\left\{0\right\} with the special cases: :math:`C_{-1} = \mathrm{max}\left({u_1+u_2-1}, 0\right)`, the Fréchet--Hoeffding lower bound; :math:`C_0 = u_1u_2`, the product copula; :math:`C_{\infty } = \mathrm{min}\left(u_1, u_2\right)`, the Fréchet--Hoeffding upper bound. The generation method uses conditional sampling. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``copula_clayton_bivar``. .. _g05re-py2-py-references: **References** Nelsen, R B, 2006, `An Introduction to Copulas`, (2nd Edition), Springer Series in Statistics """ raise NotImplementedError
[docs]def copula_frank_bivar(n, theta, sorder, statecomm): r""" ``copula_frank_bivar`` generates pseudorandom uniform bivariates with joint distribution of a Frank Archimedean copula. .. _g05rf-py2-py-doc: For full information please refer to the NAG Library document for g05rf https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05rff.html .. _g05rf-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of bivariates to generate. **theta** : float :math:`\theta`, the copula parameter. **sorder** : int Determines the storage order of variates; the :math:`\left(\textit{i}, \textit{j}\right)`\ th variate is stored in :math:`\mathrm{x}[\textit{i}-1,\textit{j}-1]` if :math:`\mathrm{sorder} = 1`, and :math:`\mathrm{x}[\textit{j}-1,\textit{i}-1]` if :math:`\mathrm{sorder} = 2`, for :math:`\textit{j} = 1,2,\ldots,2`, for :math:`\textit{i} = 1,2,\ldots,n`. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(:, :\right)` The :math:`n` bivariate uniforms with joint distribution described by :math:`C_{\theta }`, with :math:`\mathrm{x}[i-1,j-1]` holding the :math:`i`\ th value for the :math:`j`\ th dimension if :math:`\mathrm{sorder} = 1` and the :math:`j`\ th value for the :math:`i`\ th dimension if :math:`\mathrm{sorder} = 2`. .. _g05rf-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, corrupt :math:`\mathrm{statecomm}`\ ['state'] argument. (`errno` :math:`3`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`4`) On entry, invalid :math:`\mathrm{sorder}`. Constraint: :math:`\mathrm{sorder} = 1` or :math:`2`. .. _g05rf-py2-py-notes: **Notes** Generates pseudorandom uniform bivariates :math:`\left\{u_1, u_2\right\} \in \left[0, 1\right]^2` whose joint distribution is the Frank Archimedean copula :math:`C_{\theta }` with parameter :math:`\theta`, given by .. math:: C_{\theta } = -\frac{1}{\theta }\mathrm{ln}\left[1+\frac{{\left(e^{{-\theta u_1}}-1\right)\left(e^{{-\theta u_2}}-1\right)}}{{e^{{-\theta }}-1}}\right]\text{, }\quad \theta \in \left({-\infty }, \infty \right)∖\left\{0\right\} with the special cases: :math:`C_{{-\infty }} = \mathrm{max}\left({u_1+u_2-1}, 0\right)`, the Fréchet--Hoeffding lower bound; :math:`C_0 = u_1u_2`, the product copula; :math:`C_{\infty } = \mathrm{min}\left(u_1, u_2\right)`, the Fréchet--Hoeffding upper bound. The generation method uses conditional sampling. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``copula_frank_bivar``. .. _g05rf-py2-py-references: **References** Nelsen, R B, 2006, `An Introduction to Copulas`, (2nd Edition), Springer Series in Statistics """ raise NotImplementedError
[docs]def copula_plackett_bivar(n, theta, sorder, statecomm): r""" ``copula_plackett_bivar`` generates pseudorandom uniform bivariates with joint distribution of a Plackett copula. .. _g05rg-py2-py-doc: For full information please refer to the NAG Library document for g05rg https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05rgf.html .. _g05rg-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of bivariates to generate. **theta** : float :math:`\theta`, the copula parameter. **sorder** : int Determines the storage order of variates; the :math:`\left(\textit{i}, \textit{j}\right)`\ th variate is stored in :math:`\mathrm{x}[\textit{i}-1,\textit{j}-1]` if :math:`\mathrm{sorder} = 1`, and :math:`\mathrm{x}[\textit{j}-1,\textit{i}-1]` if :math:`\mathrm{sorder} = 2`, for :math:`\textit{j} = 1,2,\ldots,2`, for :math:`\textit{i} = 1,2,\ldots,n`. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(:, :\right)` The :math:`n` bivariate uniforms with joint distribution described by :math:`C_{\theta }`, with :math:`\mathrm{x}[i-1,j-1]` holding the :math:`i`\ th value for the :math:`j`\ th dimension if :math:`\mathrm{sorder} = 1` and the :math:`j`\ th value for the :math:`i`\ th dimension if :math:`\mathrm{sorder} = 2`. .. _g05rg-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, corrupt :math:`\mathrm{statecomm}`\ ['state'] argument. (`errno` :math:`2`) On entry, invalid :math:`\mathrm{theta}`: :math:`\mathrm{theta} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{theta}\geq 0.0`. (`errno` :math:`3`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`4`) On entry, invalid :math:`\mathrm{sorder}`. Constraint: :math:`\mathrm{sorder} = 1` or :math:`2`. .. _g05rg-py2-py-notes: **Notes** Generates pseudorandom uniform bivariates :math:`\left\{u_1, u_2\right\} \in \left[0, 1\right]^2` whose joint distribution is the Plackett copula :math:`C_{\theta }` with parameter :math:`\theta`, given by .. math:: C_{\theta } = \frac{{\left[1+\left(\theta -1\right)\left(u_1+u_2\right)\right]-\sqrt{\left[1+\left(\theta -1\right)\left(u_1+u_2\right)\right]^2-4u_1u_2\theta \left(\theta -1\right)}}}{{2\left(\theta -1\right)}}\text{, }\quad \theta \in \left(0, \infty \right)∖\left\{1\right\} with the special cases: :math:`C_0 = \mathrm{max}\left({u_1+u_2-1}, 0\right)`, the Fréchet--Hoeffding lower bound; :math:`C_1 = u_1u_2`, the product copula; :math:`C_{\infty } = \mathrm{min}\left(u_1, u_2\right)`, the Fréchet--Hoeffding upper bound. The generation method uses conditional sampling. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``copula_plackett_bivar``. .. _g05rg-py2-py-references: **References** Nelsen, R B, 2006, `An Introduction to Copulas`, (2nd Edition), Springer Series in Statistics """ raise NotImplementedError
[docs]def copula_clayton(n, m, theta, sorder, statecomm): r""" ``copula_clayton`` generates pseudorandom uniform variates with joint distribution of a Clayton/Cook--Johnson Archimedean copula. .. _g05rh-py2-py-doc: For full information please refer to the NAG Library document for g05rh https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05rhf.html .. _g05rh-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom uniform variates to generate. **m** : int :math:`m`, the number of dimensions. **theta** : float :math:`\theta`, the copula parameter. **sorder** : int Determines the storage order of variates; the :math:`\left(\textit{i}, \textit{j}\right)`\ th variate is stored in :math:`\mathrm{x}[\textit{i}-1,\textit{j}-1]` if :math:`\mathrm{sorder} = 1`, and :math:`\mathrm{x}[\textit{j}-1,\textit{i}-1]` if :math:`\mathrm{sorder} = 2`, for :math:`\textit{j} = 1,2,\ldots,m`, for :math:`\textit{i} = 1,2,\ldots,n`. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(:, :\right)` The pseudorandom uniform variates with joint distribution described by :math:`C_{\theta }`, with :math:`\mathrm{x}[i-1,j-1]` holding the :math:`i`\ th value for the :math:`j`\ th dimension if :math:`\mathrm{sorder} = 1` and the :math:`j`\ th value for the :math:`i`\ th dimension of :math:`\mathrm{sorder} = 2`. .. _g05rh-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, corrupt :math:`\mathrm{statecomm}`\ ['state'] argument. (`errno` :math:`2`) On entry, invalid :math:`\mathrm{theta}`: :math:`\mathrm{theta} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{theta}\geq 1.0\times 10^{-6}`. (`errno` :math:`3`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`4`) On entry, :math:`\mathrm{m} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{m}\geq 2`. (`errno` :math:`5`) On entry, invalid :math:`\mathrm{sorder}`. Constraint: :math:`\mathrm{sorder} = 1` or :math:`2`. .. _g05rh-py2-py-notes: **Notes** Generates :math:`n` pseudorandom uniform :math:`m`-variates whose joint distribution is the Clayton/Cook--Johnson Archimedean copula :math:`C_{\theta }`, given by .. math:: C_{\theta } = \left(u_1^{{-\theta }}+u_2^{{-\theta }} + \cdots +u_m^{{-\theta }}-m+1\right)^{{-1/\theta }}\text{, }\quad \left\{\begin{array}{cc} \theta \in \left(0, \infty \right) \text{,} &\\ u_j \in \left(0, 1\right] \text{, }\quad j = 1, \ldots m \text{;} \end{array}\right. with the special case: :math:`C_{\infty } = \mathrm{min}\left(u_1, u_2, \ldots, u_m\right)`, the Fréchet--Hoeffding upper bound. The generation method uses mixture of powers. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``copula_clayton``. .. _g05rh-py2-py-references: **References** Marshall, A W and Olkin, I, 1988, `Families of multivariate distributions`, Journal of the American Statistical Association (83), 403 Nelsen, R B, 2006, `An Introduction to Copulas`, (2nd Edition), Springer Series in Statistics """ raise NotImplementedError
[docs]def copula_frank(n, m, theta, sorder, statecomm): r""" ``copula_frank`` generates pseudorandom uniform variates with joint distribution of a Frank Archimedean copula. .. _g05rj-py2-py-doc: For full information please refer to the NAG Library document for g05rj https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05rjf.html .. _g05rj-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom uniform variates to generate. **m** : int :math:`m`, the number of dimensions. **theta** : float :math:`\theta`, the copula parameter. **sorder** : int Determines the storage order of variates; the :math:`\left(\textit{i}, \textit{j}\right)`\ th variate is stored in :math:`\mathrm{x}[\textit{i}-1,\textit{j}-1]` if :math:`\mathrm{sorder} = 1`, and :math:`\mathrm{x}[\textit{j}-1,\textit{i}-1]` if :math:`\mathrm{sorder} = 2`, for :math:`\textit{j} = 1,2,\ldots,m`, for :math:`\textit{i} = 1,2,\ldots,n`. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(:, :\right)` The pseudorandom uniform variates with joint distribution described by :math:`C_{\theta }`, with :math:`\mathrm{x}[i-1,j-1]` holding the :math:`i`\ th value for the :math:`j`\ th dimension if :math:`\mathrm{sorder} = 1` and the :math:`j`\ th value for the :math:`i`\ th dimension of :math:`\mathrm{sorder} = 2`. .. _g05rj-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, corrupt :math:`\mathrm{statecomm}`\ ['state'] argument. (`errno` :math:`2`) On entry, invalid :math:`\mathrm{theta}`: :math:`\mathrm{theta} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{theta}\geq 1.0\times 10^{-6}`. (`errno` :math:`3`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`4`) On entry, :math:`\mathrm{m} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{m}\geq 2`. (`errno` :math:`5`) On entry, invalid :math:`\mathrm{sorder}`. Constraint: :math:`\mathrm{sorder} = 1` or :math:`2`. .. _g05rj-py2-py-notes: **Notes** Generates :math:`n` pseudorandom uniform :math:`m`-variates whose joint distribution is the Frank Archimedean copula :math:`C_{\theta }`, given by .. math:: C_{\theta } = -\frac{1}{\theta }\mathrm{ln}\left[1+\frac{{\left(e^{{-\theta u_1}}-1\right)\left(e^{{-\theta u_2}}-1\right) \cdots \left(e^{{-\theta u_m}}-1\right)}}{{\left(e^{{-\theta }}-1\right)^{{m-1}}}}\right]\text{, }\quad \left\{\begin{array}{cc} \theta \in \left(0, \infty \right) \text{,} &\\ u_j \in \left(0, 1\right] \text{, }\quad j = 1, \ldots m \text{;} \end{array}\right. with the special case: :math:`C_{\infty } = \mathrm{min}\left(u_1, u_2, \ldots, u_m\right)`, the Fréchet--Hoeffding upper bound. The generation method uses mixture of powers. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``copula_frank``. .. _g05rj-py2-py-references: **References** Marshall, A W and Olkin, I, 1988, `Families of multivariate distributions`, Journal of the American Statistical Association (83), 403 Nelsen, R B, 2006, `An Introduction to Copulas`, (2nd Edition), Springer Series in Statistics """ raise NotImplementedError
[docs]def copula_gumbel(n, m, theta, sorder, statecomm): r""" ``copula_gumbel`` generates pseudorandom uniform variates with joint distribution of a Gumbel--Hougaard Archimedean copula. .. _g05rk-py2-py-doc: For full information please refer to the NAG Library document for g05rk https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05rkf.html .. _g05rk-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom uniform variates to generate. **m** : int :math:`m`, the number of dimensions. **theta** : float :math:`\theta`, the copula parameter. **sorder** : int Determines the storage order of variates; the :math:`\left(\textit{i}, \textit{j}\right)`\ th variate is stored in :math:`\mathrm{x}[\textit{i}-1,\textit{j}-1]` if :math:`\mathrm{sorder} = 1`, and :math:`\mathrm{x}[\textit{j}-1,\textit{i}-1]` if :math:`\mathrm{sorder} = 2`, for :math:`\textit{j} = 1,2,\ldots,m`, for :math:`\textit{i} = 1,2,\ldots,n`. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(:, :\right)` The pseudorandom uniform variates with joint distribution described by :math:`C_{\theta }`, with :math:`\mathrm{x}[i-1,j-1]` holding the :math:`i`\ th value for the :math:`j`\ th dimension if :math:`\mathrm{sorder} = 1` and the :math:`j`\ th value for the :math:`i`\ th dimension of :math:`\mathrm{sorder} = 2`. .. _g05rk-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, corrupt :math:`\mathrm{statecomm}`\ ['state'] argument. (`errno` :math:`2`) On entry, invalid :math:`\mathrm{theta}`: :math:`\mathrm{theta} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{theta}\geq 1.0`. (`errno` :math:`3`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`4`) On entry, :math:`\mathrm{m} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{m}\geq 2`. (`errno` :math:`5`) On entry, invalid :math:`\mathrm{sorder}`. Constraint: :math:`\mathrm{sorder} = 1` or :math:`2`. .. _g05rk-py2-py-notes: **Notes** Generates :math:`n` pseudorandom uniform :math:`m`-variates whose joint distribution is the Gumbel--Hougaard Archimedean copula :math:`C_{\theta }`, given by .. math:: C_{\theta } = \mathrm{exp}\left\{-\left[\left(-\mathrm{ln}\left(u_1\right)\right)^{\theta }+\left(-\mathrm{ln}\left(u_2\right)\right)^{\theta } + \cdots +\left(-\mathrm{ln}\left(u_m\right)\right)^{\theta }\right]\right\}\text{, }\quad \left\{\begin{array}{cc} \theta \in \left(1, \infty \right) \text{,} &\\ u_j \in \left(0, 1\right] \text{, }\quad j = 1, 2, \ldots m \text{;} \end{array}\right. with the special cases: :math:`C_1 = u_1u_2 \cdots u_m`, the product copula; :math:`C_{\infty } = \mathrm{min}\left(u_1, u_2, \ldots, u_m\right)`, the Fréchet--Hoeffding upper bound. The generation method uses mixture of powers. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``copula_gumbel``. .. _g05rk-py2-py-references: **References** Marshall, A W and Olkin, I, 1988, `Families of multivariate distributions`, Journal of the American Statistical Association (83), 403 Nelsen, R B, 2006, `An Introduction to Copulas`, (2nd Edition), Springer Series in Statistics """ raise NotImplementedError
[docs]def multivar_students_t(mode, n, df, xmu, c, comm, statecomm): r""" ``multivar_students_t`` sets up a reference vector and generates an array of pseudorandom numbers from a multivariate Student's :math:`t` distribution with :math:`\nu` degrees of freedom, mean vector :math:`a` and covariance matrix :math:`\frac{\nu }{{\nu -2}}C`. .. _g05ry-py2-py-doc: For full information please refer to the NAG Library document for g05ry https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05ryf.html .. _g05ry-py2-py-parameters: **Parameters** **mode** : int A code for selecting the operation to be performed by the function. :math:`\mathrm{mode} = 0` Set up reference vector only. :math:`\mathrm{mode} = 1` Generate variates using reference vector set up in a prior call to ``multivar_students_t``. :math:`\mathrm{mode} = 2` Set up reference vector and generate variates. **n** : int :math:`n`, the number of random variates required. **df** : int :math:`\nu`, the number of degrees of freedom of the distribution. **xmu** : float, array-like, shape :math:`\left(m\right)` :math:`a`, the vector of means of the distribution. **c** : float, array-like, shape :math:`\left(m, m\right)` Matrix which, along with :math:`\mathrm{df}`, defines the covariance of the distribution. Only the upper triangle need be set. **comm** : dict, communication object, modified in place Communication structure for the reference vector. If :math:`\mathrm{mode} = 1`, this argument must have been initialized by a prior call to ``multivar_students_t``. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : None or float, ndarray, shape :math:`\left(\mathrm{n}, :\right)` The array of pseudorandom multivariate Student's :math:`t` vectors generated by the function, with :math:`\mathrm{x}[i-1,j-1]` holding the :math:`j`\ th dimension for the :math:`i`\ th variate. .. _g05ry-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{mode} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{mode} = 0`, :math:`1` or :math:`2`. (`errno` :math:`2`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{df} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{df}\geq 3`. (`errno` :math:`4`) On entry, :math:`m = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`m > 0`. (`errno` :math:`6`) On entry, the covariance matrix :math:`C` is not positive semidefinite to machine precision. (`errno` :math:`8`) :math:`\textit{m}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call. Previous value of :math:`m = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`m = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`10`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05ry-py2-py-notes: **Notes** When the covariance matrix is nonsingular (i.e., strictly positive definite), the distribution has probability density function .. math:: f\left(x\right) = \frac{{\Gamma \left(\frac{\left(\nu +m\right)}{2}\right)}}{{\left(\pi v\right)^{{m/2}}\Gamma \left(\nu /2\right)\left\lvert C\right\rvert^{\frac{1}{2}}}}\left[1+\frac{{\left(x-a\right)^\mathrm{T}C^{-1}\left(x-a\right)}}{\nu }\right]^{\frac{{-\left(\nu +m\right)}}{2}} where :math:`m` is the number of dimensions, :math:`\nu` is the degrees of freedom, :math:`a` is the vector of means, :math:`x` is the vector of positions and :math:`\frac{\nu }{{\nu -2}}C` is the covariance matrix. The function returns the value .. math:: x = a+\sqrt{\frac{\nu }{s}}z where :math:`z` is generated by :meth:`dist_normal` from a Normal distribution with mean zero and covariance matrix :math:`C` and :math:`s` is generated by :meth:`dist_chisq` from a :math:`\chi^2`-distribution with :math:`\nu` degrees of freedom. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``multivar_students_t``. .. _g05ry-py2-py-references: **References** Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley Wilkinson, J H, 1965, `The Algebraic Eigenvalue Problem`, Oxford University Press, Oxford """ raise NotImplementedError
[docs]def multivar_normal(sorder, mode12, n, xmu, c, comm, statecomm): r""" ``multivar_normal`` sets up a reference vector and generates an array of pseudorandom numbers from a multivariate Normal distribution with mean vector :math:`a` and covariance matrix :math:`C`. .. _g05rz-py2-py-doc: For full information please refer to the NAG Library document for g05rz https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05rzf.html .. _g05rz-py2-py-parameters: **Parameters** **sorder** : int Determines the storage order of variates; the :math:`\left(\textit{i}, \textit{j}\right)`\ th variate is stored in :math:`\mathrm{x}[\textit{i}-1,\textit{j}-1]` if :math:`\mathrm{sorder} = 1`, and :math:`\mathrm{x}[\textit{j}-1,\textit{i}-1]` if :math:`\mathrm{sorder} = 2`, for :math:`\textit{j} = 1,2,\ldots,m`, for :math:`\textit{i} = 1,2,\ldots,n`. **mode12** : int A code for selecting the operation to be performed by the function. :math:`\mathrm{mode12} = 0` Set up reference vector only. :math:`\mathrm{mode12} = 1` Generate variates using reference vector set up in a prior call to ``multivar_normal``. :math:`\mathrm{mode12} = 2` Set up reference vector and generate variates. **n** : int :math:`n`, the number of random variates required. **xmu** : float, array-like, shape :math:`\left(m\right)` :math:`a`, the vector of means of the distribution. **c** : float, array-like, shape :math:`\left(m, m\right)` The covariance matrix of the distribution. Only the upper triangle need be set. **comm** : dict, communication object, modified in place Communication structure for the reference vector. If :math:`\mathrm{mode12} = 1`, this argument must have been initialized by a prior call to ``multivar_normal``. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : None or float, ndarray, shape :math:`\left(:, :\right)` The array of pseudorandom multivariate Normal vectors generated by the function. Two possible storage orders are available. If :math:`\mathrm{sorder} = 1` then :math:`\mathrm{x}[i-1,j-1]` holds the :math:`j`\ th dimension for the :math:`i`\ th variate. If :math:`\mathrm{sorder} = 2` this ordering is reversed and :math:`\mathrm{x}[j-1,i-1]` holds the :math:`j`\ th dimension for the :math:`i`\ th variate. .. _g05rz-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{mode12} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{mode12} = 0`, :math:`1` or :math:`2`. (`errno` :math:`2`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`m = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`m > 0`. (`errno` :math:`5`) On entry, the covariance matrix :math:`C` is not positive semidefinite to machine precision. (`errno` :math:`7`) :math:`\textit{m}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call. Previous value of :math:`m = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`m = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`9`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05rz-py2-py-notes: **Notes** When the covariance matrix is nonsingular (i.e., strictly positive definite), the distribution has probability density function .. math:: f\left(x\right) = \sqrt{\frac{{\left\lvert C^{-1}\right\rvert }}{{\left(2\pi \right)^m}}}\mathrm{exp}\left(-\frac{1}{2}\left(x-a\right)^\mathrm{T}C^{-1}\left(x-a\right)\right) where :math:`m` is the number of dimensions, :math:`C` is the covariance matrix, :math:`a` is the vector of means and :math:`x` is the vector of positions. Covariance matrices are symmetric and positive semidefinite. Given such a matrix :math:`C`, there exists a lower triangular matrix :math:`L` such that :math:`LL^\mathrm{T} = C`. :math:`L` is not unique, if :math:`C` is singular. ``multivar_normal`` decomposes :math:`C` to find such an :math:`L`. It then stores :math:`m`, :math:`a` and :math:`L` in the reference vector :math:`r` which is used to generate a vector :math:`x` of independent standard Normal pseudorandom numbers. It then returns the vector :math:`a+Lx`, which has the required multivariate Normal distribution. It should be noted that this function will work with a singular covariance matrix :math:`C`, provided :math:`C` is positive semidefinite, despite the fact that the above formula for the probability density function is not valid in that case. Wilkinson (1965) should be consulted if further information is required. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``multivar_normal``. .. _g05rz-py2-py-references: **References** Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley Wilkinson, J H, 1965, `The Algebraic Eigenvalue Problem`, Oxford University Press, Oxford """ raise NotImplementedError
[docs]def dist_uniform01(n, statecomm): r""" ``dist_uniform01`` generates a vector of pseudorandom numbers taken from a uniform distribution between :math:`0` and :math:`1`. .. _g05sa-py2-py-doc: For full information please refer to the NAG Library document for g05sa https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05saf.html .. _g05sa-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from a uniform distribution over the half closed interval :math:`\left(0, 1\right]`. .. _g05sa-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`2`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05sa-py2-py-notes: **Notes** ``dist_uniform01`` generates :math:`n` values from a uniform distribution over the half closed interval :math:`\left(0, 1\right]`. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``dist_uniform01``. .. _g05sa-py2-py-references: **References** Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley See Also -------- :meth:`naginterfaces.library.examples.fit.dim2_spline_ts_sctr_ex.main` """ raise NotImplementedError
[docs]def dist_beta(n, a, b, statecomm): r""" ``dist_beta`` generates a vector of pseudorandom numbers taken from a beta distribution with parameters :math:`a` and :math:`b`. .. _g05sb-py2-py-doc: For full information please refer to the NAG Library document for g05sb https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05sbf.html .. _g05sb-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **a** : float :math:`a`, the parameter of the beta distribution. **b** : float :math:`b`, the parameter of the beta distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified beta distribution. .. _g05sb-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`2`) On entry, :math:`\mathrm{a} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{a} > 0.0`. (`errno` :math:`3`) On entry, :math:`\mathrm{b} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{b} > 0.0`. (`errno` :math:`4`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05sb-py2-py-notes: **Notes** The beta distribution has PDF (probability density function) .. math:: \begin{array}{ll} f\left(x\right) = \frac{{\Gamma \left(a+b\right)}}{{\Gamma \left(a\right)\Gamma \left(b\right)}} x^{{a-1}} \left(1-x\right)^{{b-1}} & \text{if } 0\leq x\leq 1 \text{; } a,b > 0 \text{,} \\\\f\left(x\right) = 0&\text{otherwise.}\end{array} One of four algorithms is used to generate the variates depending on the values of :math:`a` and :math:`b`. Let :math:`\alpha` be the maximum and :math:`\beta` be the minimum of :math:`a` and :math:`b`. Then the algorithms are as follows: (i) if :math:`\alpha < 0.5`, Johnk's algorithm is used, see for example Dagpunar (1988). This generates the beta variate as :math:`u_1^{{1/a}}/\begin{pmatrix}u_1^{{1/a}}+u_2^{{1/b}}\end{pmatrix}`, where :math:`u_1` and :math:`u_2` are uniformly distributed random variates; (#) if :math:`\beta > 1`, the algorithm BB given by Cheng (1978) is used. This involves the generation of an observation from a beta distribution of the second kind by the envelope rejection method using a log-logistic target distribution and then transforming it to a beta variate; (#) if :math:`\alpha > 1` and :math:`\beta < 1`, the switching algorithm given by Atkinson (1979) is used. The two target distributions used are :math:`f_1\left(x\right) = \beta x^{\beta }` and :math:`f_2\left(x\right) = \alpha \left(1-x\right)^{{\beta -1}}`, along with the approximation to the switching parameter of :math:`t = \left(1-\beta \right)/\left(\alpha +1-\beta \right)`; (#) in all other cases, Cheng's BC algorithm (see Cheng (1978)) is used with modifications suggested by Dagpunar (1988). This algorithm is similar to BB, used when :math:`\beta > 1`, but is tuned for small values of :math:`a` and :math:`b`. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``dist_beta``. .. _g05sb-py2-py-references: **References** Atkinson, A C, 1979, `A family of switching algorithms for the computer generation of beta random variates`, Biometrika (66), 141--5 Cheng, R C H, 1978, `Generating beta variates with nonintegral shape parameters`, Comm. ACM (21), 317--322 Dagpunar, J, 1988, `Principles of Random Variate Generation`, Oxford University Press Hastings, N A J and Peacock, J B, 1975, `Statistical Distributions`, Butterworth """ raise NotImplementedError
[docs]def dist_cauchy(n, xmed, semiqr, statecomm): r""" ``dist_cauchy`` generates a vector of pseudorandom numbers from a Cauchy distribution with median :math:`a` and semi-interquartile range :math:`b`. .. _g05sc-py2-py-doc: For full information please refer to the NAG Library document for g05sc https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05scf.html .. _g05sc-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **xmed** : float :math:`a`, the median of the distribution. **semiqr** : float :math:`b`, the semi-interquartile range of the distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified Cauchy distribution. .. _g05sc-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{semiqr} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{semiqr}\geq 0.0`. (`errno` :math:`4`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05sc-py2-py-notes: **Notes** The distribution has PDF (probability density function) .. math:: f\left(x\right) = \frac{1}{{\pi b\left(1+\left(\frac{{x-a}}{b}\right)^2\right)}}\text{.} ``dist_cauchy`` returns the value .. math:: a+b\frac{{2y_1-1}}{y_2}\text{,} where :math:`y_1` and :math:`y_2` are a pair of consecutive pseudorandom numbers from a uniform distribution over :math:`\left(0, 1\right)`, such that .. math:: \left(2y_1-1\right)^2+y_2^2\leq 1\text{.} One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``dist_cauchy``. .. _g05sc-py2-py-references: **References** Kendall, M G and Stuart, A, 1969, `The Advanced Theory of Statistics (Volume 1)`, (3rd Edition), Griffin Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def dist_chisq(n, df, statecomm): r""" ``dist_chisq`` generates a vector of pseudorandom numbers taken from a :math:`\chi^2`-distribution with :math:`\nu` degrees of freedom. .. _g05sd-py2-py-doc: For full information please refer to the NAG Library document for g05sd https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05sdf.html .. _g05sd-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **df** : int :math:`\nu`, the number of degrees of freedom of the distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified :math:`\chi^2`-distribution. .. _g05sd-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`2`) On entry, :math:`\mathrm{df} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{df}\geq 1`. (`errno` :math:`3`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05sd-py2-py-notes: **Notes** The distribution has PDF (probability density function) .. math:: \begin{array}{ll} f\left(x\right) = \frac{{x^{{{\nu /2}-1}}\times e^{{-x/2}}}}{{2^{{\nu /2}}\times \left({\nu /2}-1\right)!}} & \text{if } x > 0 \text{;} \\&\\f\left(x\right) = 0&\text{otherwise.}\end{array} This is the same as a gamma distribution with parameters :math:`\nu /2` and :math:`2`. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``dist_chisq``. .. _g05sd-py2-py-references: **References** Kendall, M G and Stuart, A, 1969, `The Advanced Theory of Statistics (Volume 1)`, (3rd Edition), Griffin Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def dist_dirichlet(n, a, statecomm): r""" ``dist_dirichlet`` generates a vector of pseudorandom numbers taken from a Dirichlet distribution. .. _g05se-py2-py-doc: For full information please refer to the NAG Library document for g05se https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05sef.html .. _g05se-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **a** : float, array-like, shape :math:`\left(m\right)` The parameter vector for the distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(\mathrm{n}, m\right)` The :math:`n` pseudorandom numbers from the specified Dirichlet distribution, with :math:`\mathrm{x}[i-1,j-1]` holding the :math:`j`\ th dimension for the :math:`i`\ th variate. .. _g05se-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`2`) On entry, :math:`m = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`m > 0`. (`errno` :math:`3`) On entry, at least one :math:`\mathrm{a}[i]\leq 0`. (`errno` :math:`4`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05se-py2-py-notes: **Notes** The distribution has PDF (probability density function) .. math:: \begin{array}{lll}f\left(x\right)& = & \frac{1}{{B\left(\alpha \right)}} \prod_{1}^{m}{x_i^{{\alpha_i-1}}\quad \text{and}} \\B\left(\alpha \right)& = & \frac{{\prod_{1}^{m}{\Gamma \left(\alpha_i\right)}}}{{\Gamma \left(\sum_{1}^{m}{\alpha_i}\right)}} \end{array} where :math:`x = \left\{x_1, x_2, \ldots, x_m\right\}` is a vector of dimension :math:`m`, such that :math:`x_i > 0` for all :math:`i` and :math:`\sum_{1}^{m}{x_i} = 1`. ``dist_dirichlet`` generates a draw from a Dirichlet distribution by first drawing :math:`m` independent samples, :math:`y_i\sim \mathrm{gamma}\left(\alpha_i, 1\right)`, i.e., independent draws from a gamma distribution with parameters :math:`\alpha_i > 0` and one, and then setting :math:`x_i = y_i/\sum_{1}^{m}{y_j}`. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``dist_dirichlet``. .. _g05se-py2-py-references: **References** Dagpunar, J, 1988, `Principles of Random Variate Generation`, Oxford University Press Hastings, N A J and Peacock, J B, 1975, `Statistical Distributions`, Butterworth """ raise NotImplementedError
[docs]def dist_exp(n, a, statecomm): r""" ``dist_exp`` generates a vector of pseudorandom numbers from a (negative) exponential distribution with mean :math:`a`. .. _g05sf-py2-py-doc: For full information please refer to the NAG Library document for g05sf https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05sff.html .. _g05sf-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **a** : float :math:`a`, the mean of the distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified exponential distribution. .. _g05sf-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`2`) On entry, :math:`\mathrm{a} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{a} > 0.0`. (`errno` :math:`3`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05sf-py2-py-notes: **Notes** The exponential distribution has PDF (probability density function): .. math:: \begin{array}{ll} f\left(x\right) = \frac{1}{a} e^{{-x/a}} & \text{if }x\geq 0\text{,} \\\\f\left(x\right) = 0&\text{otherwise.}\end{array} ``dist_exp`` returns the values .. math:: x_i = -a\mathrm{ln}\left(y_i\right) where :math:`y_i` are the next :math:`n` numbers generated by a uniform :math:`\left(0, 1\right]` generator. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``dist_exp``. .. _g05sf-py2-py-references: **References** Kendall, M G and Stuart, A, 1969, `The Advanced Theory of Statistics (Volume 1)`, (3rd Edition), Griffin Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def dist_expmix(n, a, wgt, statecomm): r""" ``dist_expmix`` generates a vector of pseudorandom numbers from an exponential mix distribution composed of :math:`m` exponential distributions each having a mean :math:`a_i` and weight :math:`w_i`. .. _g05sg-py2-py-doc: For full information please refer to the NAG Library document for g05sg https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05sgf.html .. _g05sg-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **a** : float, array-like, shape :math:`\left(\textit{nmix}\right)` The :math:`m` parameters :math:`a_i` for the :math:`m` exponential distributions in the mix. **wgt** : float, array-like, shape :math:`\left(\textit{nmix}\right)` The :math:`m` weights :math:`w_i` for the :math:`m` exponential distributions in the mix. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified exponential mix distribution. .. _g05sg-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`2`) On entry, :math:`\textit{nmix} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\textit{nmix}\geq 1`. (`errno` :math:`3`) On entry, :math:`\mathrm{a}[\langle\mathit{\boldsymbol{value}}\rangle] = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{a}[i-1] > 0.0`. (`errno` :math:`4`) On entry, :math:`\mathrm{wgt}[\langle\mathit{\boldsymbol{value}}\rangle] = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{wgt}[i-1]\geq 0.0`. (`errno` :math:`4`) On entry, sum of :math:`\mathrm{wgt} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: sum of :math:`\mathrm{wgt} = 1.0`. (`errno` :math:`5`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05sg-py2-py-notes: **Notes** The distribution has PDF (probability density function) .. math:: \begin{array}{ll} f\left(x\right) = \sum_{{i = 1}}^m \frac{1}{a_i} w_i e^{{-x/a_i}} &\text{if }x\geq 0\text{,}\\ f\left(x\right) = 0 &\text{otherwise,}\end{array} where :math:`\sum_{{i = 1}}^mw_i = 1` and :math:`a_i > 0`, :math:`w_i\geq 0`. ``dist_expmix`` returns the values :math:`x_i` by selecting, with probability :math:`w_j`, random variates from an exponential distribution with parameter :math:`a_j`. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``dist_expmix``. .. _g05sg-py2-py-references: **References** Kendall, M G and Stuart, A, 1969, `The Advanced Theory of Statistics (Volume 1)`, (3rd Edition), Griffin Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def dist_f(n, df1, df2, statecomm): r""" ``dist_f`` generates a vector of pseudorandom numbers taken from an :math:`F` (or Fisher's variance ratio) distribution with :math:`\mu` and :math:`\nu` degrees of freedom. .. _g05sh-py2-py-doc: For full information please refer to the NAG Library document for g05sh https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05shf.html .. _g05sh-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **df1** : int :math:`\mu`, the number of degrees of freedom of the distribution. **df2** : int :math:`\nu`, the number of degrees of freedom of the distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified :math:`F`-distribution. .. _g05sh-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`2`) On entry, :math:`\mathrm{df1} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{df1}\geq 1`. (`errno` :math:`3`) On entry, :math:`\mathrm{df2} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{df2}\geq 1`. (`errno` :math:`4`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05sh-py2-py-notes: **Notes** The distribution has PDF (probability density function) .. math:: \begin{array}{ll} f \left(x\right) = \frac{{\left(\frac{{\mu +\nu -2}}{2}\right)!x^{{\frac{1}{2}\mu -1}}}}{{\left(\frac{1}{2}\mu -1\right)!\left(\frac{1}{2}\nu -1\right)!\left(1+\frac{\mu }{\nu }x\right)^{{\frac{1}{2}\left(\mu +\nu \right)}}}} \times \left(\frac{\mu }{\nu }\right)^{{\frac{1}{2}\mu }} & \text{if } x > 0 \text{,} \\&\\f\left(x\right) = 0&\text{otherwise.}\end{array} ``dist_f`` calculates the values .. math:: \frac{{\nu y_i}}{{\mu z_i}}\text{, }\quad i = 1,2,\ldots,n\text{,} where :math:`y_i` and :math:`z_i` are generated by :meth:`dist_gamma` from gamma distributions with parameters :math:`\left({\frac{1}{2}\mu }, 2\right)` and :math:`\left({\frac{1}{2}\nu }, 2\right)` respectively (i.e., from :math:`\chi^2`-distributions with :math:`\mu` and :math:`\nu` degrees of freedom). One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``dist_f``. .. _g05sh-py2-py-references: **References** Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def dist_gamma(n, a, b, statecomm): r""" ``dist_gamma`` generates a vector of pseudorandom numbers taken from a gamma distribution with parameters :math:`a` and :math:`b`. .. _g05sj-py2-py-doc: For full information please refer to the NAG Library document for g05sj https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05sjf.html .. _g05sj-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **a** : float :math:`a`, the parameter of the gamma distribution. **b** : float :math:`b`, the parameter of the gamma distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified gamma distribution. .. _g05sj-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`2`) On entry, :math:`\mathrm{a} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{a} > 0.0`. (`errno` :math:`3`) On entry, :math:`\mathrm{b} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{b} > 0.0`. (`errno` :math:`4`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05sj-py2-py-notes: **Notes** The gamma distribution has PDF (probability density function) .. math:: \begin{array}{ll}f\left(x\right) = \frac{1}{{b^a\Gamma \left(a\right)}}x^{{a-1}}e^{{-x/b}}&\text{if }x\geq 0\text{; }\quad a,b > 0\\\\f\left(x\right) = 0&\text{otherwise.}\end{array} One of three algorithms is used to generate the variates depending upon the value of :math:`a`: (i) if :math:`a < 1`, a switching algorithm described by Dagpunar (1988) (called G6) is used. The target distributions are :math:`f_1\left(x\right) = cax^{{a-1}}/t^a` and :math:`f_2\left(x\right) = \left(1-c\right)e^{{-\left(x-t\right)}}`, where :math:`c = t/\left(t+ae^{{-t}}\right)`, and the switching parameter, :math:`t`, is taken as :math:`1-a`. This is similar to Ahrens and Dieter's GS algorithm (see Ahrens and Dieter (1974)) in which :math:`t = 1`; (#) if :math:`a = 1`, the gamma distribution reduces to the exponential distribution and the method based on the logarithmic transformation of a uniform random variate is used; (#) if :math:`a > 1`, the algorithm given by Best (1978) is used. This is based on using a Student's :math:`t`-distribution with two degrees of freedom as the target distribution in an envelope rejection method. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``dist_gamma``. .. _g05sj-py2-py-references: **References** Ahrens, J H and Dieter, U, 1974, `Computer methods for sampling from gamma, beta, Poisson and binomial distributions`, Computing (12), 223--46 Best, D J, 1978, `Letter to the Editor`, Appl. Statist. (27), 181 Dagpunar, J, 1988, `Principles of Random Variate Generation`, Oxford University Press Hastings, N A J and Peacock, J B, 1975, `Statistical Distributions`, Butterworth """ raise NotImplementedError
[docs]def dist_normal(n, xmu, var, statecomm): r""" ``dist_normal`` generates a vector of pseudorandom numbers taken from a Normal (Gaussian) distribution with mean :math:`\mu` and variance :math:`\sigma^2`. .. _g05sk-py2-py-doc: For full information please refer to the NAG Library document for g05sk https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05skf.html .. _g05sk-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **xmu** : float :math:`\mu`, the mean of the distribution. **var** : float :math:`\sigma^2`, the variance of the distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified Normal distribution. .. _g05sk-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{var} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{var}\geq 0.0`. (`errno` :math:`4`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05sk-py2-py-notes: **Notes** The distribution has PDF (probability distribution function) .. math:: f\left(x\right) = \frac{1}{{\sigma \sqrt{2\pi }}}\mathrm{exp}\left(-\frac{\left(x-\mu \right)^2}{{2\sigma^2}}\right)\text{.} ``dist_normal`` uses the algorithm of Wichura (1988). One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``dist_normal``. .. _g05sk-py2-py-references: **References** Kendall, M G and Stuart, A, 1969, `The Advanced Theory of Statistics (Volume 1)`, (3rd Edition), Griffin Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley Wichura, 1988, `Algorithm AS 241: the percentage points of the Normal distribution`, Appl. Statist. (37), 477--484 """ raise NotImplementedError
[docs]def dist_logistic(n, a, b, statecomm): r""" ``dist_logistic`` generates a vector of pseudorandom numbers from a logistic distribution with mean :math:`a` and spread :math:`b`. .. _g05sl-py2-py-doc: For full information please refer to the NAG Library document for g05sl https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05slf.html .. _g05sl-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **a** : float :math:`a`, the mean of the distribution. **b** : float :math:`b`, the spread of the distribution, where 'spread' is :math:`\frac{\sqrt{3}}{\pi }\times \text{}`\ standard deviation. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified logistic distribution. .. _g05sl-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{b} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{b}\geq 0.0`. (`errno` :math:`4`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05sl-py2-py-notes: **Notes** The distribution has PDF (probability density function) .. math:: f\left(x\right) = \frac{e^{{\left(x-a\right)/b}}}{{b\left(1+e^{{\left(x-a\right)/b}}\right)^2}}\text{.} ``dist_logistic`` returns the value .. math:: a+b\mathrm{ln}\left(\frac{y}{{1-y}}\right)\text{,} where :math:`y` is a pseudorandom number uniformly distributed over :math:`\left(0, 1\right)`. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``dist_logistic``. .. _g05sl-py2-py-references: **References** Kendall, M G and Stuart, A, 1969, `The Advanced Theory of Statistics (Volume 1)`, (3rd Edition), Griffin Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def dist_lognormal(n, xmu, var, statecomm): r""" ``dist_lognormal`` generates a vector of pseudorandom numbers from a log-normal distribution with parameters :math:`\mu` and :math:`\sigma^2`. .. _g05sm-py2-py-doc: For full information please refer to the NAG Library document for g05sm https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05smf.html .. _g05sm-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **xmu** : float :math:`\mu`, the mean of the distribution of :math:`\mathrm{ln}\left(x\right)`. **var** : float :math:`\sigma^2`, the variance of the distribution of :math:`\mathrm{ln}\left(x\right)`. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified log-normal distribution. .. _g05sm-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`2`) On entry, :math:`\mathrm{xmu}` is too large to take the exponential of :math:`\mathrm{xmu} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`3`) On entry, :math:`\mathrm{var} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{var}\geq 0.0`. (`errno` :math:`4`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05sm-py2-py-notes: **Notes** The distribution has PDF (probability density function) .. math:: \begin{array}{ll} f\left(x\right) = \frac{1}{{x\sigma \sqrt{2\pi }}} \mathrm{exp}\left(-\frac{\left(\mathrm{ln}\left(x\right)-\mu \right)^2}{{2\sigma^2}}\right) & \text{if } x > 0 \text{,} \\\\f\left(x\right) = 0&\text{otherwise,}\end{array} i.e., :math:`\mathrm{ln}\left(x\right)` is normally distributed with mean :math:`\mu` and variance :math:`\sigma^2`. ``dist_lognormal`` evaluates :math:`\mathrm{exp}\left(y_i\right)`, where the :math:`y_i` are generated by :meth:`dist_normal` from a Normal distribution with mean :math:`\mu` and variance :math:`\sigma^2`, for :math:`\textit{i} = 1,2,\ldots,n`. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``dist_lognormal``. .. _g05sm-py2-py-references: **References** Kendall, M G and Stuart, A, 1969, `The Advanced Theory of Statistics (Volume 1)`, (3rd Edition), Griffin Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def dist_students_t(n, df, statecomm): r""" ``dist_students_t`` generates a vector of pseudorandom numbers taken from a Student's :math:`t`-distribution with :math:`\nu` degrees of freedom. .. _g05sn-py2-py-doc: For full information please refer to the NAG Library document for g05sn https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05snf.html .. _g05sn-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **df** : int :math:`\nu`, the number of degrees of freedom of the distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified Student's :math:`t`-distribution. .. _g05sn-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`2`) On entry, :math:`\mathrm{df} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{df}\geq 1`. (`errno` :math:`3`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05sn-py2-py-notes: **Notes** The distribution has PDF (probability density function) .. math:: f\left(x\right) = \frac{{\left(\frac{{\nu -1}}{2}\right)!}}{{\left(\frac{1}{2}\nu -1\right)!\sqrt{\pi \nu }\left(1+\frac{x^2}{\nu }\right)^{{\frac{1}{2}\left(\nu +1\right)}}}}\text{.} ``dist_students_t`` calculates the values .. math:: y_i\sqrt{\frac{\nu }{z_i}}\text{, }\quad i = 1,\ldots,n where the :math:`y_i` are generated by :meth:`dist_normal` from a Normal distribution with mean :math:`0` and variance :math:`1.0`, and the :math:`z_i` are generated by :meth:`dist_gamma` from a gamma distribution with parameters :math:`\frac{1}{2}\nu` and :math:`2` (i.e., from a :math:`\chi^2`-distribution with :math:`\nu` degrees of freedom). One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``dist_students_t``. .. _g05sn-py2-py-references: **References** Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def dist_triangular(n, xmin, xmed, xmax, statecomm): r""" ``dist_triangular`` generates a vector of pseudorandom numbers from a triangular distribution with parameters :math:`x_{\mathrm{min}}`, :math:`x_{\mathrm{med}}` and :math:`x_{\mathrm{max}}`. .. _g05sp-py2-py-doc: For full information please refer to the NAG Library document for g05sp https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05spf.html .. _g05sp-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **xmin** : float The end point :math:`x_{\mathrm{min}}` of the triangular distribution. **xmed** : float The median of the distribution :math:`x_{\mathrm{med}}` (also the location of the vertex of the triangular distribution at which the PDF reaches a maximum). **xmax** : float The end point :math:`x_{\mathrm{max}}` of the triangular distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified triangular distribution. .. _g05sp-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{xmed} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{xmin} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{xmed}\geq \mathrm{xmin}`. (`errno` :math:`4`) On entry, :math:`\mathrm{xmax} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{xmed} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{xmax}\geq \mathrm{xmed}`. (`errno` :math:`5`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05sp-py2-py-notes: **Notes** The triangular distribution has a PDF (probability density function) that is triangular in profile. The base of the triangle ranges from :math:`x = x_{\mathrm{min}}` to :math:`x = x_{\mathrm{max}}` and the PDF has a maximum value of :math:`\frac{2}{{x_{\mathrm{max}}-x_{\mathrm{min}}}}` at :math:`x = x_{\mathrm{med}}`. If :math:`x_{\mathrm{min}} = x_{\mathrm{med}} = x_{\mathrm{max}}` then :math:`x = x_{\mathrm{med}}` with probability 1; otherwise the triangular distribution has PDF: .. math:: \begin{array}{ll} f\left(x\right) = \frac{{x-x_{\mathrm{min}}}}{{x_{\mathrm{med}}-x_{\mathrm{min}}}} \times \frac{2}{{x_{\mathrm{max}}-x_{\mathrm{min}}}} &\text{ if }x_{\mathrm{min}}\leq x\leq x_{\mathrm{med}}\text{,}\\\\\\f\left(x\right) = \frac{{x_{\mathrm{max}}-x}}{{x_{\mathrm{max}}-x_{\mathrm{med}}}}\times \frac{2}{{x_{\mathrm{max}}-x_{\mathrm{min}}}}&\text{ if }x_{\mathrm{med}} < x\leq x_{\mathrm{max}}\text{,}\\\\\\f\left(x\right) = 0&\text{ otherwise.}\end{array} One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``dist_triangular``. .. _g05sp-py2-py-references: **References** Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def dist_uniform(n, a, b, statecomm): r""" ``dist_uniform`` generates a vector of pseudorandom numbers uniformly distributed over the interval :math:`\left[a, b\right]`. .. _g05sq-py2-py-doc: For full information please refer to the NAG Library document for g05sq https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05sqf.html .. _g05sq-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **a** : float The end points :math:`a` and :math:`b` of the uniform distribution. **b** : float The end points :math:`a` and :math:`b` of the uniform distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified uniform distribution. .. _g05sq-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{a} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{b} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{b}\geq \mathrm{a}`. (`errno` :math:`4`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05sq-py2-py-notes: **Notes** If :math:`a = 0` and :math:`b = 1`, ``dist_uniform`` returns the next :math:`n` values :math:`y_i` from a uniform :math:`\left(0, 1\right]` generator (see :meth:`dist_uniform01` for details). For other values of :math:`a` and :math:`b`, ``dist_uniform`` applies the transformation .. math:: x_i = a+\left(b-a\right)y_i\text{.} The function ensures that the values :math:`x_i` lie in the closed interval :math:`\left[a, b\right]`. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``dist_uniform``. .. _g05sq-py2-py-references: **References** Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def dist_vonmises(n, vk, statecomm): r""" ``dist_vonmises`` generates a vector of pseudorandom numbers from a von Mises distribution with concentration parameter :math:`\kappa`. .. _g05sr-py2-py-doc: For full information please refer to the NAG Library document for g05sr https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05srf.html .. _g05sr-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **vk** : float :math:`\kappa`, the concentration parameter of the required von Mises distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified von Mises distribution. .. _g05sr-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`2`) On entry, :math:`\mathrm{vk}\leq 0.0` or :math:`\mathrm{vk}` too large: :math:`\mathrm{vk} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`3`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05sr-py2-py-notes: **Notes** The von Mises distribution is a symmetric distribution used in the analysis of circular data. The PDF (probability density function) of this distribution on the circle with mean direction :math:`\mu_0 = 0` and concentration parameter :math:`\kappa`, can be written as: .. math:: f\left(\theta \right) = \frac{{e^{{\kappa \cos\left(\theta \right)}}}}{{2\pi I_0\left(\kappa \right)}}\text{,} where :math:`\theta` is reduced modulo :math:`2\pi` so that :math:`{-\pi }\leq \theta < \pi` and :math:`\kappa \geq 0`. For very small :math:`\kappa` the distribution is almost the uniform distribution, whereas for :math:`\kappa →\infty` all the probability is concentrated at one point. The :math:`n` variates, :math:`\theta_1,\theta_2,\ldots,\theta_n`, are generated using an envelope rejection method with a wrapped Cauchy target distribution as proposed by Best and Fisher (1979) and described by Dagpunar (1988). One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``dist_vonmises``. .. _g05sr-py2-py-references: **References** Best, D J and Fisher, N I, 1979, `Efficient simulation of the von Mises distribution`, Appl. Statist. (28), 152--157 Dagpunar, J, 1988, `Principles of Random Variate Generation`, Oxford University Press Mardia, K V, 1972, `Statistics of Directional Data`, Academic Press """ raise NotImplementedError
[docs]def dist_weibull(n, a, b, statecomm): r""" ``dist_weibull`` generates a vector of pseudorandom numbers from a two parameter Weibull distribution with shape parameter :math:`a` and scale parameter :math:`b`. .. _g05ss-py2-py-doc: For full information please refer to the NAG Library document for g05ss https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05ssf.html .. _g05ss-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **a** : float :math:`a`, the shape parameter of the distribution. **b** : float :math:`b`, the scale parameter of the distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : float, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified Weibull distribution. .. _g05ss-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`2`) On entry, :math:`\mathrm{a} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{a} > 0.0`. (`errno` :math:`3`) On entry, :math:`\mathrm{b} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{b} > 0.0`. (`errno` :math:`4`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05ss-py2-py-notes: **Notes** The distribution has PDF (probability density function) .. math:: \begin{array}{ll} f\left(x\right) = \frac{a}{b} x^{{a-1}} e^{{-x^a/b}} &\text{if }x > 0\text{,}\\\\f\left(x\right) = 0&\text{otherwise.}\end{array} ``dist_weibull`` returns the value :math:`\left(-b\mathrm{ln}\left(y\right)\right)^{{1/a}}`, where :math:`y` is a pseudorandom number from a uniform distribution over :math:`\left(0, 1\right]`. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``dist_weibull``. .. _g05ss-py2-py-references: **References** Kendall, M G and Stuart, A, 1969, `The Advanced Theory of Statistics (Volume 1)`, (3rd Edition), Griffin Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def int_binomial(mode, n, m, p, statecomm, comm=None): r""" ``int_binomial`` generates a vector of pseudorandom integers from the discrete binomial distribution with parameters :math:`m` and :math:`p`. .. _g05ta-py2-py-doc: For full information please refer to the NAG Library document for g05ta https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05taf.html .. _g05ta-py2-py-parameters: **Parameters** **mode** : int A code for selecting the operation to be performed by the function. :math:`\mathrm{mode} = 0` Set up reference vector only. :math:`\mathrm{mode} = 1` Generate variates using reference vector set up in a prior call to ``int_binomial``. :math:`\mathrm{mode} = 2` Set up reference vector and generate variates. :math:`\mathrm{mode} = 3` Generate variates without using the reference vector. **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **m** : int :math:`m`, the number of trials of the distribution. **p** : float :math:`p`, the probability of success of the binomial distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **comm** : None or dict, communication object, optional, modified in place Communication structure for the reference vector. If :math:`\mathrm{mode} = 1`, this argument must have been initialized by a prior call to ``int_binomial``. If :math:`\mathrm{mode} = 3`, :math:`\mathrm{comm}` is not referenced and may be **None**. **Returns** **x** : None or int, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified binomial distribution. .. _g05ta-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{mode} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{mode} = 0`, :math:`1`, :math:`2` or :math:`3`. (`errno` :math:`2`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{m} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{m}\geq 0`. (`errno` :math:`4`) On entry, :math:`\mathrm{p} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`0.0\leq \mathrm{p}\leq 1.0`. (`errno` :math:`5`) :math:`\mathrm{p}` or :math:`\mathrm{m}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call. Previous value of :math:`\mathrm{p} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{p} = \langle\mathit{\boldsymbol{value}}\rangle`. Previous value of :math:`\mathrm{m} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{m} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`5`) On entry, some of the elements of the array :math:`\mathrm{comm}`\ ['r'] have been corrupted or have not been initialized. (`errno` :math:`7`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05ta-py2-py-notes: **Notes** ``int_binomial`` generates :math:`n` integers :math:`x_i` from a discrete binomial distribution, where the probability of :math:`x_i = I` is .. math:: P\left(x_i = I\right) = \frac{{m!}}{{I!\left(m-I\right)!}}p^I\times \left(1-p\right)^{{m-I}}\text{, }\quad I = 0,1,\ldots,m\text{,} where :math:`m\geq 0` and :math:`0\leq p\leq 1`. This represents the probability of achieving :math:`I` successes in :math:`m` trials when the probability of success at a single trial is :math:`p`. The variates can be generated with or without using a search table and index. If a search table is used then it is stored with the index in a reference vector and subsequent calls to ``int_binomial`` with the same parameter values can then use this reference vector to generate further variates. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``int_binomial``. .. _g05ta-py2-py-references: **References** Kendall, M G and Stuart, A, 1969, `The Advanced Theory of Statistics (Volume 1)`, (3rd Edition), Griffin Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def logical(n, p, statecomm): r""" ``logical`` generates a vector of pseudorandom logical values -- :math:`\mathbf{True}` with probability :math:`p` and :math:`\mathbf{False}` with probability :math:`\left(1-p\right)`. .. _g05tb-py2-py-doc: For full information please refer to the NAG Library document for g05tb https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05tbf.html .. _g05tb-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom logical values to be generated. **p** : float Must contain the probability of ``logical`` returning :math:`\mathbf{True}`. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : bool, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` logical values. .. _g05tb-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`2`) On entry, :math:`\mathrm{p} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`0.0\leq \mathrm{p}\leq 1.0`. (`errno` :math:`3`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05tb-py2-py-notes: **Notes** ``logical`` generates :math:`n` logical values :math:`x_i` from the relation .. math:: y_i < p where :math:`y_i` is a pseudorandom number from a uniform distribution over :math:`\left(0, 1\right]`, generated by :meth:`dist_uniform01` using the values of :math:`\mathrm{statecomm}`\ ['state'] as input to this function. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``logical``. .. _g05tb-py2-py-references: **References** Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def int_geom(mode, n, p, statecomm, comm=None): r""" ``int_geom`` generates a vector of pseudorandom integers from the discrete geometric distribution with probability :math:`p` of success at a trial. .. _g05tc-py2-py-doc: For full information please refer to the NAG Library document for g05tc https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05tcf.html .. _g05tc-py2-py-parameters: **Parameters** **mode** : int A code for selecting the operation to be performed by the function. :math:`\mathrm{mode} = 0` Set up reference vector only. :math:`\mathrm{mode} = 1` Generate variates using reference vector set up in a prior call to ``int_geom``. :math:`\mathrm{mode} = 2` Set up reference vector and generate variates. :math:`\mathrm{mode} = 3` Generate variates without using the reference vector. **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **p** : float The parameter :math:`p` of the geometric distribution representing the probability of success at a single trial. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **comm** : None or dict, communication object, optional, modified in place Communication structure for the reference vector. If :math:`\mathrm{mode} = 1`, this argument must have been initialized by a prior call to ``int_geom``. If :math:`\mathrm{mode} = 3`, :math:`\mathrm{comm}` is not referenced and may be **None**. **Returns** **x** : None or int, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified geometric distribution. .. _g05tc-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{mode} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{mode} = 0`, :math:`1`, :math:`2` or :math:`3`. (`errno` :math:`2`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{p} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\text{machine precision}\leq \mathrm{p}\leq 1.0`. (`errno` :math:`3`) :math:`\mathrm{p}` is so small that :math:`\textit{lr}` would have to be larger than the largest representable integer. Use :math:`\mathrm{mode} = 3` instead. :math:`\mathrm{p} = \langle\mathit{\boldsymbol{value}}\rangle` (`errno` :math:`4`) :math:`\mathrm{p}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call. Previous value of :math:`\mathrm{p} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{p} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`4`) On entry, some of the elements of the array :math:`\mathrm{comm}`\ ['r'] have been corrupted or have not been initialized. (`errno` :math:`6`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05tc-py2-py-notes: **Notes** ``int_geom`` generates :math:`n` integers :math:`x_i` from a discrete geometric distribution, where the probability of :math:`x_i = I` (a first success after :math:`I+1` trials) is .. math:: P\left(x_i = I\right) = p\times \left(1-p\right)^I\text{, }\quad I = 0,1,\ldots \text{.} The variates can be generated with or without using a search table and index. If a search table is used then it is stored with the index in a reference vector and subsequent calls to ``int_geom`` with the same parameter value can then use this reference vector to generate further variates. If the search table is not used (as recommended for small values of :math:`p`) then a direct transformation of uniform variates is used. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``int_geom``. .. _g05tc-py2-py-references: **References** Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def int_general(mode, n, p, ip1, itype, statecomm, comm=None): r""" ``int_general`` generates a vector of pseudorandom integers from a discrete distribution with a given PDF (probability density function) or CDF (cumulative distribution function) :math:`p`. .. _g05td-py2-py-doc: For full information please refer to the NAG Library document for g05td https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05tdf.html .. _g05td-py2-py-parameters: **Parameters** **mode** : int A code for selecting the operation to be performed by the function. :math:`\mathrm{mode} = 0` Set up reference vector only. :math:`\mathrm{mode} = 1` Generate variates using reference vector set up in a prior call to ``int_general``. :math:`\mathrm{mode} = 2` Set up reference vector and generate variates. :math:`\mathrm{mode} = 3` Generate variates without using the reference vector. **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **p** : float, array-like, shape :math:`\left(\textit{np}\right)` The PDF or CDF of the distribution. **ip1** : int The value of the variate, a whole number, to which the probability in :math:`\mathrm{p}[0]` corresponds. **itype** : int Indicates the type of information contained in :math:`\mathrm{p}`. :math:`\mathrm{itype} = 1` :math:`\mathrm{p}` contains a probability distribution function (PDF). :math:`\mathrm{itype} = 2` :math:`\mathrm{p}` contains a cumulative distribution function (CDF). **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **comm** : None or dict, communication object, optional, modified in place Communication structure for the reference vector. If :math:`\mathrm{mode} = 1`, this argument must have been initialized by a prior call to ``int_general``. If :math:`\mathrm{mode} = 3`, :math:`\mathrm{comm}` is not referenced and may be **None**. **Returns** **x** : None or int, ndarray, shape :math:`\left(\mathrm{n}\right)` Contains :math:`n` pseudorandom numbers from the specified discrete distribution. .. _g05td-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{mode} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{mode} = 0`, :math:`1` or :math:`2`. (`errno` :math:`2`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, at least one element of the vector :math:`\mathrm{p}` is less than :math:`0.0` or greater than :math:`1.0`. (`errno` :math:`3`) On entry, :math:`\mathrm{itype} = 1` and the sum of the elements of :math:`\mathrm{p}` do not equal one. (`errno` :math:`3`) On entry, :math:`\mathrm{itype} = 2` and the values of :math:`\mathrm{p}` are not all in stricly ascending order. (`errno` :math:`3`) On entry, :math:`\mathrm{p}[\textit{np}-1] = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: if :math:`\mathrm{itype} = 2`, :math:`\mathrm{p}[\textit{np}-1] = 1.0`. (`errno` :math:`4`) On entry, :math:`\textit{np} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\textit{np} > 0`. (`errno` :math:`6`) On entry, :math:`\mathrm{itype} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{itype} = 1` or :math:`2`. (`errno` :math:`7`) The value of :math:`\textit{np}` or :math:`\mathrm{ip1}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call. Previous value of :math:`\textit{np} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\textit{np} = \langle\mathit{\boldsymbol{value}}\rangle`. Previous value of :math:`\mathrm{ip1} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{ip1} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`7`) On entry, some of the elements of the array :math:`\mathrm{comm}`\ ['r'] have been corrupted or have not been initialized. (`errno` :math:`9`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05td-py2-py-notes: **Notes** ``int_general`` generates a sequence of :math:`n` integers :math:`x_i`, from a discrete distribution defined by information supplied in :math:`\mathrm{p}`. This may either be the PDF or CDF of the distribution. A reference vector is first set up to contain the CDF of the distribution in its higher elements, followed by an index. Setting up the reference vector and subsequent generation of variates can each be performed by separate calls to ``int_general`` or may be combined in a single call. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``int_general``. .. _g05td-py2-py-references: **References** Kendall, M G and Stuart, A, 1969, `The Advanced Theory of Statistics (Volume 1)`, (3rd Edition), Griffin Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def int_hypergeom(mode, n, ns, np, m, statecomm, comm=None): r""" ``int_hypergeom`` generates a vector of pseudorandom integers from the discrete hypergeometric distribution of the number of specified items in a sample of size :math:`l`, taken from a population of size :math:`k` with :math:`m` specified items in it. .. _g05te-py2-py-doc: For full information please refer to the NAG Library document for g05te https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05tef.html .. _g05te-py2-py-parameters: **Parameters** **mode** : int A code for selecting the operation to be performed by the function. :math:`\mathrm{mode} = 0` Set up reference vector only. :math:`\mathrm{mode} = 1` Generate variates using reference vector set up in a prior call to ``int_hypergeom``. :math:`\mathrm{mode} = 2` Set up reference vector and generate variates. :math:`\mathrm{mode} = 3` Generate variates without using the reference vector. **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **ns** : int :math:`l`, the sample size of the hypergeometric distribution. **np** : int :math:`k`, the population size of the hypergeometric distribution. **m** : int :math:`m`, the number of specified items of the hypergeometric distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **comm** : None or dict, communication object, optional, modified in place Communication structure for the reference vector. If :math:`\mathrm{mode} = 1`, this argument must have been initialized by a prior call to ``int_hypergeom``. If :math:`\mathrm{mode} = 3`, :math:`\mathrm{comm}` is not referenced and may be **None**. **Returns** **x** : None or int, ndarray, shape :math:`\left(\mathrm{n}\right)` The pseudorandom numbers from the specified hypergeometric distribution. .. _g05te-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{mode} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{mode} = 0`, :math:`1`, :math:`2` or :math:`3`. (`errno` :math:`2`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{ns} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{np} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`0\leq \mathrm{ns}\leq \mathrm{np}`. (`errno` :math:`4`) On entry, :math:`\mathrm{np} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{np}\geq 0`. (`errno` :math:`5`) On entry, :math:`\mathrm{m} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{np} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`0\leq \mathrm{m}\leq \mathrm{np}`. (`errno` :math:`6`) The value of :math:`\mathrm{ns}`, :math:`\mathrm{np}` or :math:`\mathrm{m}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call with :math:`\mathrm{mode} = 0` or :math:`2`. (`errno` :math:`6`) On entry, some of the elements of the array :math:`\mathrm{comm}`\ ['r'] have been corrupted or have not been initialized. (`errno` :math:`8`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05te-py2-py-notes: **Notes** ``int_hypergeom`` generates :math:`n` integers :math:`x_i` from a discrete hypergeometric distribution, where the probability of :math:`x_i = I` is .. math:: \begin{array}{cc}P\left(i = I\right) = \frac{{l!m!\left(k-l\right)!\left(k-m\right)!}}{{I!\left(l-I\right)!\left(m-I\right)!\left(k-m-l+I\right)!k!}}&\quad \text{ if } I = \mathrm{max}\left(0, {m+l-k}\right), \ldots, \mathrm{min}\left(l, m\right) \text{,} \\\\P\left(i = I\right) = 0&\quad \text{ otherwise.}\end{array} The variates can be generated with or without using a search table and index. If a search table is used then it is stored with the index in a reference vector and subsequent calls to ``int_hypergeom`` with the same parameter values can then use this reference vector to generate further variates. The reference array is generated by a recurrence relation if :math:`lm\left(k-l\right)\left(k-m\right) < 50k^3`, otherwise Stirling's approximation is used. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``int_hypergeom``. .. _g05te-py2-py-references: **References** Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def int_log(mode, n, a, statecomm, comm=None): r""" ``int_log`` generates a vector of pseudorandom integers from the discrete logarithmic distribution with parameter :math:`a`. .. _g05tf-py2-py-doc: For full information please refer to the NAG Library document for g05tf https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05tff.html .. _g05tf-py2-py-parameters: **Parameters** **mode** : int A code for selecting the operation to be performed by the function. :math:`\mathrm{mode} = 0` Set up reference vector only. :math:`\mathrm{mode} = 1` Generate variates using reference vector set up in a prior call to ``int_log``. :math:`\mathrm{mode} = 2` Set up reference vector and generate variates. :math:`\mathrm{mode} = 3` Generate variates without using the reference vector. **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **a** : float :math:`a`, the parameter of the logarithmic distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **comm** : None or dict, communication object, optional, modified in place Communication structure for the reference vector. If :math:`\mathrm{mode} = 1`, this argument must have been initialized by a prior call to ``int_log``. If :math:`\mathrm{mode} = 3`, :math:`\mathrm{comm}` is not referenced and may be **None**. **Returns** **x** : None or int, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified logarithmic distribution. .. _g05tf-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{mode} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{mode} = 0`, :math:`1`, :math:`2` or :math:`3`. (`errno` :math:`2`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{a} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`0.0 < \mathrm{a} < 1.0`. (`errno` :math:`4`) The value of :math:`\mathrm{a}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call. Previous value of :math:`\mathrm{a} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{a} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`4`) On entry, some of the elements of the array :math:`\mathrm{comm}`\ ['r'] have been corrupted or have not been initialized. (`errno` :math:`6`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05tf-py2-py-notes: **Notes** ``int_log`` generates :math:`n` integers :math:`x_i` from a discrete logarithmic distribution, where the probability of :math:`x_i = I` is .. math:: P\left(x_i = I\right) = -\frac{a^I}{{I\times \log\left(1-a\right)}}\text{, }\quad I = 1,2,\ldots \text{,} where :math:`0 < a < 1\text{.}` The variates can be generated with or without using a search table and index. If a search table is used then it is stored with the index in a reference vector and subsequent calls to ``int_log`` with the same parameter value can then use this reference vector to generate further variates. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``int_log``. .. _g05tf-py2-py-references: **References** Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def int_multinomial(mode, n, m, p, statecomm, comm=None): r""" ``int_multinomial`` generates a sequence of :math:`n` variates, each consisting of :math:`k` pseudorandom integers, from the discrete multinomial distribution with :math:`k` outcomes and :math:`m` trials, where the outcomes have probabilities :math:`p_1,p_2,\ldots,p_k` respectively. .. _g05tg-py2-py-doc: For full information please refer to the NAG Library document for g05tg https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05tgf.html .. _g05tg-py2-py-parameters: **Parameters** **mode** : int A code for selecting the operation to be performed by the function. :math:`\mathrm{mode} = 0` Set up reference vector only. :math:`\mathrm{mode} = 1` Generate variates using reference vector set up in a prior call to ``int_multinomial``. :math:`\mathrm{mode} = 2` Set up reference vector and generate variates. :math:`\mathrm{mode} = 3` Generate variates without using the reference vector. **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **m** : int :math:`m`, the number of trials of the multinomial distribution. **p** : float, array-like, shape :math:`\left(k\right)` Contains the probabilities :math:`p_{\textit{j}}`, for :math:`\textit{j} = 1,2,\ldots,k`, of the :math:`k` possible outcomes of the multinomial distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **comm** : None or dict, communication object, optional, modified in place Communication structure for the reference vector. If :math:`\mathrm{mode} = 1`, this argument must have been initialized by a prior call to ``int_multinomial``. If :math:`\mathrm{mode} = 3`, :math:`\mathrm{comm}` is not referenced and may be **None**. **Returns** **x** : None or int, ndarray, shape :math:`\left(\mathrm{n}, :\right)` The first :math:`n` rows of :math:`\mathrm{x}[i-1,j-1]` each contain :math:`k` pseudorandom numbers representing a :math:`k`-dimensional variate from the specified multinomial distribution. .. _g05tg-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{mode} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{mode} = 0`, :math:`1`, :math:`2` or :math:`3`. (`errno` :math:`2`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{m} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{m}\geq 0`. (`errno` :math:`4`) On entry, :math:`k = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`k\geq 2`. (`errno` :math:`5`) On entry, at least one element of the vector :math:`\mathrm{p}` is less than :math:`0.0` or greater than :math:`1.0`. (`errno` :math:`5`) On entry, the sum of the elements of :math:`\mathrm{p}` do not equal one. (`errno` :math:`6`) The value of :math:`\mathrm{m}` or :math:`\textit{k}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call. Previous value of :math:`\mathrm{m} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{m} = \langle\mathit{\boldsymbol{value}}\rangle`. Previous value of :math:`k = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`k = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`6`) On entry, some of the elements of the array :math:`\mathrm{comm}`\ ['r'] have been corrupted or have not been initialized. (`errno` :math:`8`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05tg-py2-py-notes: **Notes** ``int_multinomial`` generates a sequence of :math:`n` groups of :math:`k` integers :math:`x_{{\textit{i},\textit{j}}}`, for :math:`\textit{i} = 1,2,\ldots,n`, for :math:`\textit{j} = 1,2,\ldots,k`, from a multinomial distribution with :math:`m` trials and :math:`k` outcomes, where the probability of :math:`x_{{\textit{i},\textit{j}}} = I_j` for each :math:`j = 1,2,\ldots,k` is .. math:: P\left({i_1 = I_1}, \ldots, {i_k = I_k}\right) = \frac{{m!}}{{\prod_{{j = 1}}^kI_j!}}\prod_{{j = 1}}^kp_j^{I_j} = \frac{{m!}}{{I_1!I_2! \cdots I_k!}}p_1^{I_1}p_2^{I_2} \cdots p_k^{I_k}\text{,} where .. math:: \sum_{{j = 1}}^kp_j = 1\quad \text{ and }\quad \sum_{{j = 1}}^kI_j = m\text{.} A single trial can have several outcomes (:math:`k`) and the probability of achieving each outcome is known (:math:`p_j`). After :math:`m` trials each outcome will have occurred a certain number of times. The :math:`k` numbers representing the numbers of occurrences for each outcome after :math:`m` trials is then a single sample from the multinomial distribution defined by the parameters :math:`k`, :math:`m` and :math:`p_{\textit{j}}`, for :math:`\textit{j} = 1,2,\ldots,k`. This function returns :math:`n` such samples. When :math:`k = 2` this distribution is equivalent to the binomial distribution with parameters :math:`m` and :math:`p = p_1` (see :meth:`int_binomial`). The variates can be generated with or without using a search table and index. If a search table is used then it is stored with the index in a reference vector and subsequent calls to ``int_multinomial`` with the same parameter values can then use this reference vector to generate further variates. The reference array is generated only for the outcome with greatest probability. The number of successes for the outcome with greatest probability is calculated first as for the binomial distribution (see :meth:`int_binomial`); the number of successes for other outcomes are calculated in turn for the remaining reduced multinomial distribution; the number of successes for the final outcome is simply calculated to ensure that the total number of successes is :math:`m`. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``int_multinomial``. .. _g05tg-py2-py-references: **References** Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def int_negbin(mode, n, m, p, statecomm, comm=None): r""" ``int_negbin`` generates a vector of pseudorandom integers from the discrete negative binomial distribution with parameter :math:`m` and probability :math:`p` of success at a trial. .. _g05th-py2-py-doc: For full information please refer to the NAG Library document for g05th https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05thf.html .. _g05th-py2-py-parameters: **Parameters** **mode** : int A code for selecting the operation to be performed by the function. :math:`\mathrm{mode} = 0` Set up reference vector only. :math:`\mathrm{mode} = 1` Generate variates using reference vector set up in a prior call to ``int_negbin``. :math:`\mathrm{mode} = 2` Set up reference vector and generate variates. :math:`\mathrm{mode} = 3` Generate variates without using the reference vector. **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **m** : int :math:`m`, the number of failures of the distribution. **p** : float :math:`p`, the parameter of the negative binomial distribution representing the probability of success at a single trial. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **comm** : None or dict, communication object, optional, modified in place Communication structure for the reference vector. If :math:`\mathrm{mode} = 1`, this argument must have been initialized by a prior call to ``int_negbin``. If :math:`\mathrm{mode} = 3`, :math:`\mathrm{comm}` is not referenced and may be **None**. **Returns** **x** : None or int, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified negative binomial distribution. .. _g05th-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{mode} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{mode} = 0`, :math:`1`, :math:`2` or :math:`3`. (`errno` :math:`2`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{m} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{m}\geq 0`. (`errno` :math:`4`) On entry, :math:`\mathrm{p} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`0.0\leq \mathrm{p} < 1.0`. (`errno` :math:`5`) :math:`\mathrm{p}` or :math:`\mathrm{m}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call. Previous value of :math:`\mathrm{p} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{p} = \langle\mathit{\boldsymbol{value}}\rangle`. Previous value of :math:`\mathrm{m} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{m} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`5`) On entry, some of the elements of the array :math:`\mathrm{comm}`\ ['r'] have been corrupted or have not been initialized. (`errno` :math:`7`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05th-py2-py-notes: **Notes** ``int_negbin`` generates :math:`n` integers :math:`x_i` from a discrete negative binomial distribution, where the probability of :math:`x_i = I` (:math:`I` successes before :math:`m` failures) is .. math:: P\left(x_i = I\right) = \frac{{\left(m+I-1\right)!}}{{I!\left(m-1\right)!}}\times p^I\times \left(1-p\right)^m\text{, }\quad I = 0,1,\ldots \text{.} The variates can be generated with or without using a search table and index. If a search table is used then it is stored with the index in a reference vector and subsequent calls to ``int_negbin`` with the same parameter value can then use this reference vector to generate further variates. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``int_negbin``. .. _g05th-py2-py-references: **References** Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def int_poisson(mode, n, lamda, statecomm, comm=None): r""" ``int_poisson`` generates a vector of pseudorandom integers from the discrete Poisson distribution with mean :math:`\lambda`. .. _g05tj-py2-py-doc: For full information please refer to the NAG Library document for g05tj https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05tjf.html .. _g05tj-py2-py-parameters: **Parameters** **mode** : int A code for selecting the operation to be performed by the function. :math:`\mathrm{mode} = 0` Set up reference vector only. :math:`\mathrm{mode} = 1` Generate variates using reference vector set up in a prior call to ``int_poisson``. :math:`\mathrm{mode} = 2` Set up reference vector and generate variates. :math:`\mathrm{mode} = 3` Generate variates without using the reference vector. **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **lamda** : float :math:`\lambda`, the mean of the Poisson distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **comm** : None or dict, communication object, optional, modified in place Communication structure for the reference vector. If :math:`\mathrm{mode} = 1`, this argument must have been initialized by a prior call to ``int_poisson``. If :math:`\mathrm{mode} = 3`, :math:`\mathrm{comm}` is not referenced and may be **None**. **Returns** **x** : None or int, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified Poisson distribution. .. _g05tj-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{mode} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{mode} = 0`, :math:`1`, :math:`2` or :math:`3`. (`errno` :math:`2`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{lamda} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{lamda}\geq 0.0`. (`errno` :math:`3`) :math:`\mathrm{lamda}` is such that :math:`\textit{lr}` would have to be larger than the largest representable integer. Use :math:`\mathrm{mode} = 3` instead. :math:`\mathrm{lamda} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`4`) :math:`\mathrm{lamda}` is not the same as when :math:`\mathrm{comm}`\ ['r'] was set up in a previous call. Previous value of :math:`\mathrm{lamda} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{lamda} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`4`) On entry, some of the elements of the array :math:`\mathrm{comm}`\ ['r'] have been corrupted or have not been initialized. (`errno` :math:`6`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05tj-py2-py-notes: **Notes** ``int_poisson`` generates :math:`n` integers :math:`x_i` from a discrete Poisson distribution with mean :math:`\lambda`, where the probability of :math:`x_i = I` is .. math:: P\left(x_i = I\right) = \frac{{\lambda^I\times e^{{-\lambda }}}}{{I!}}\text{, }\quad I = 0,1,\ldots \text{,} where :math:`\lambda \geq 0`. The variates can be generated with or without using a search table and index. If a search table is used then it is stored with the index in a reference vector and subsequent calls to ``int_poisson`` with the same parameter values can then use this reference vector to generate further variates. The reference array is found using a recurrence relation if :math:`\lambda` is less than :math:`50` and by Stirling's formula otherwise. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``int_poisson``. .. _g05tj-py2-py-references: **References** Kendall, M G and Stuart, A, 1969, `The Advanced Theory of Statistics (Volume 1)`, (3rd Edition), Griffin Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def int_poisson_varmean(vlamda, statecomm): r""" ``int_poisson_varmean`` generates a vector of pseudorandom integers, each from a discrete Poisson distribution with differing parameter. .. _g05tk-py2-py-doc: For full information please refer to the NAG Library document for g05tk https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05tkf.html .. _g05tk-py2-py-parameters: **Parameters** **vlamda** : float, array-like, shape :math:`\left(m\right)` The means, :math:`\lambda_{\textit{j}}`, for :math:`\textit{j} = 1,2,\ldots,m`, of the Poisson distributions. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : int, ndarray, shape :math:`\left(m\right)` The :math:`m` pseudorandom numbers from the specified Poisson distributions. .. _g05tk-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`m = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`m\geq 1`. (`errno` :math:`2`) On entry, at least one element of :math:`\mathrm{vlamda}` is less than zero. (`errno` :math:`2`) On entry, at least one element of :math:`\mathrm{vlamda}` is too large. (`errno` :math:`3`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05tk-py2-py-notes: **Notes** ``int_poisson_varmean`` generates :math:`m` integers :math:`x_j`, each from a discrete Poisson distribution with mean :math:`\lambda_j`, where the probability of :math:`x_j = I` is .. math:: P\left(x_j = I\right) = \frac{{\lambda_j^I\times e^{{-\lambda_j}}}}{{I!}}\text{, }\quad I = 0,1,\ldots \text{,} where .. math:: \lambda_j\geq 0\text{, }\quad j = 1,2,\ldots,m\text{.} The methods used by this function have low set up times and are designed for efficient use when the value of the parameter :math:`\lambda` changes during the simulation. For large samples from a distribution with fixed :math:`\lambda` using :meth:`int_poisson` to set up and use a reference vector may be more efficient. When :math:`\lambda < 7.5` the product of uniforms method is used, see for example Dagpunar (1988). For larger values of :math:`\lambda` an envelope rejection method is used with a target distribution: .. math:: \begin{array}{cc}f\left(x\right) = \frac{1}{3}&\text{if }\left\lvert x\right\rvert \leq 1\text{,}\\\\f\left(x\right) = \frac{1}{3}\left\lvert x\right\rvert^{-3}&\text{otherwise.}\end{array} This distribution is generated using a ratio of uniforms method. A similar approach has also been suggested by Ahrens and Dieter (1989). The basic method is combined with quick acceptance and rejection tests given by Maclaren (1990). For values of :math:`\lambda \geq 87` Stirling's approximation is used in the computation of the Poisson distribution function, otherwise tables of factorials are used as suggested by Maclaren (1990). One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``int_poisson_varmean``. .. _g05tk-py2-py-references: **References** Ahrens, J H and Dieter, U, 1989, `A convenient sampling method with bounded computation times for Poisson distributions`, Amer. J. Math. Management Sci., 1--13 Dagpunar, J, 1988, `Principles of Random Variate Generation`, Oxford University Press Maclaren, N M, 1990, `A Poisson random number generator`, Personal Communication """ raise NotImplementedError
[docs]def int_uniform(n, a, b, statecomm): r""" ``int_uniform`` generates a vector of pseudorandom integers uniformly distributed over the interval :math:`\left[a, b\right]`. .. _g05tl-py2-py-doc: For full information please refer to the NAG Library document for g05tl https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05tlf.html .. _g05tl-py2-py-parameters: **Parameters** **n** : int :math:`n`, the number of pseudorandom numbers to be generated. **a** : int The end points :math:`a` and :math:`b` of the uniform distribution. **b** : int The end points :math:`a` and :math:`b` of the uniform distribution. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **x** : int, ndarray, shape :math:`\left(\mathrm{n}\right)` The :math:`n` pseudorandom numbers from the specified uniform distribution. .. _g05tl-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`\mathrm{a} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{b} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{b}\geq \mathrm{a}`. (`errno` :math:`4`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05tl-py2-py-notes: **Notes** ``int_uniform`` generates the next :math:`n` values :math:`y_i` from a uniform :math:`\left(0, 1\right]` generator (see :meth:`dist_uniform01` for details) and applies the transformation .. math:: x_i = a+\left\lfloor \left(b-a+1\right)y_i\right\rfloor \text{,} where :math:`\left\lfloor z\right\rfloor` is the integer part of the real value :math:`z`. The function ensures that the values :math:`x_i` lie in the closed interval :math:`\left[a, b\right]`. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``int_uniform``. .. _g05tl-py2-py-references: **References** Knuth, D E, 1981, `The Art of Computer Programming (Volume 2)`, (2nd Edition), Addison--Wesley """ raise NotImplementedError
[docs]def bb_init(t0, tend, times): r""" ``bb_init`` initializes the Brownian bridge generator :meth:`bb`. It must be called before any calls to :meth:`bb`. .. _g05xa-py2-py-doc: For full information please refer to the NAG Library document for g05xa https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05xaf.html .. _g05xa-py2-py-parameters: **Parameters** **t0** : float The starting value :math:`t_0` of the time interval. **tend** : float The end value :math:`T` of the time interval. **times** : float, array-like, shape :math:`\left(\textit{ntimes}\right)` The points in the time interval :math:`\left(t_0, T\right)` at which the Wiener process is to be constructed. The order in which points are listed in :math:`\mathrm{times}` determines the bridge construction order. The function :meth:`bb_make_bridge_order` can be used to create predefined bridge construction orders from a set of input times. **Returns** **comm** : dict, communication object Communication structure. .. _g05xa-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`-99`) An unexpected error occurred during execution of ``bb_init``. Please contact `NAG <https://www.nag.com>`__ with the following error message: error in :math:`\langle\mathit{\boldsymbol{value}}\rangle`, :math:`\text{ASSERT} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`1`) On entry, :math:`\mathrm{tend} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{t0} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{tend} > \mathrm{t0}`. (`errno` :math:`2`) On entry, :math:`\textit{ntimes} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\textit{ntimes}\geq 1`. (`errno` :math:`3`) On entry, :math:`\mathrm{times}[\langle\mathit{\boldsymbol{value}}\rangle] = \langle\mathit{\boldsymbol{value}}\rangle`, :math:`\mathrm{t0} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{tend} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{t0} < \mathrm{times}[i-1] < \mathrm{tend}` for all :math:`i`. (`errno` :math:`4`) On entry, :math:`\mathrm{times}[\langle\mathit{\boldsymbol{value}}\rangle]` and :math:`\mathrm{times}[\langle\mathit{\boldsymbol{value}}\rangle]` both equal :math:`\langle\mathit{\boldsymbol{value}}\rangle`. Constraint: all elements of :math:`\mathrm{times}` must be unique. .. _g05xa-py2-py-notes: **Notes** **Brownian Bridge Algorithm** Details on the Brownian bridge algorithm and the Brownian bridge process (sometimes also called a non-free Wiener process) can be found in `the G05 Introduction <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05intro.html#bb>`__. We briefly recall some notation and definitions. Fix two times :math:`t_0 < T` and let :math:`\left(t_i\right)_{{1\leq i\leq N}}` be any set of time points satisfying :math:`t_0 < t_1 < t_2<⋯<t_N < T`. Let :math:`\left(X_{{t_i}}\right)_{{1\leq i\leq N}}` denote a :math:`d`-dimensional Wiener sample path at these time points, and let :math:`C` be any :math:`d\times d` matrix such that :math:`CC^\mathrm{T}` is the desired covariance structure for the Wiener process. Each point :math:`X_{{t_i}}` of the sample path is constructed according to the Brownian bridge interpolation algorithm (see Glasserman (2004) or `the G05 Introduction <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05intro.html#bb>`__). We always start at some fixed point :math:`X_{t_0} = x \in \mathbb{R}^d`. If we set :math:`X_T = x+C\sqrt{T-t_0}Z` where :math:`Z` is any :math:`d`-dimensional standard Normal random variable, then :math:`X` will behave like a normal (free) Wiener process. However if we fix the terminal value :math:`X_T = w \in \mathbb{R}^d`, then :math:`X` will behave like a non-free Wiener process. **Implementation** Given the start and end points of the process, the order in which successive interpolation times :math:`t_j` are chosen is called the `bridge construction order`. The construction order is given by the array :math:`\mathrm{times}`. Further information on construction orders is given in `the G05 Introduction <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05intro.html#bb-algo>`__. For clarity we consider here the common scenario where the Brownian bridge algorithm is used with quasi-random points. If pseudorandom numbers are used instead, these details can be ignored. Suppose we require :math:`P` Wiener sample paths each of dimension :math:`d`. The main input to the Brownian bridge algorithm is then an array of quasi-random points :math:`Z^1,Z^2,…,Z^P` where each point :math:`Z^p = \left(Z_1^p, Z_2^p, \ldots, Z_D^p\right)` has dimension :math:`D = d\left(N+1\right)` or :math:`D = dN` respectively, depending on whether a free or non-free Wiener process is required. When :meth:`bb` is called, the :math:`p`\ th sample path for :math:`1\leq p\leq P` is constructed as follows: if a non-free Wiener process is required set :math:`X_T` equal to the terminal value :math:`w`, otherwise construct :math:`X_T` as .. math:: X_T = X_{{t_0}}+C\sqrt{T-t_0}\left[\begin{array}{c}Z_1^p\\ \vdots \\Z_d^p\end{array}\right] where :math:`C` is the matrix described in `Brownian Bridge Algorithm <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05xaf.html#background>`__. The array :math:`\mathrm{times}` holds the remaining time points :math:`t_1,t_2,…t_N` in the order in which the bridge is to be constructed. For each :math:`j = 1,…,N` set :math:`r = \mathrm{times}[j-1]`, find .. math:: q = \text{max}\left\{{t_0,\mathrm{times}[i-1]:1\leq i < j}, {\mathrm{times}[i-1] < r}\right\} and .. math:: s = \text{min}\left\{T, {\mathrm{times}[i-1]:1\leq i < j}, {\mathrm{times}[i-1] > r}\right\}\text{} and construct the point :math:`X_r` as .. math:: X_r = \frac{{X_q\left(s-r\right)+X_s\left(r-q\right)}}{{s-q}}+C\sqrt{\frac{{\left(s-r\right)\left(r-q\right)}}{{\left(s-q\right)}}}\left[\begin{array}{c}Z_{{jd-ad+1}}^p\\ \vdots \\Z_{{jd-ad+d}}^p\end{array}\right] where :math:`a = 0` or :math:`a = 1` respectively depending on whether a free or non-free Wiener process is required. Note that in our discussion :math:`j` is indexed from :math:`1`, and so :math:`X_r` is interpolated between the nearest (in time) Wiener points which have already been constructed. The function :meth:`bb_make_bridge_order` can be used to initialize the :math:`\mathrm{times}` array for several predefined bridge construction orders. .. _g05xa-py2-py-references: **References** Glasserman, P, 2004, `Monte Carlo Methods in Financial Engineering`, Springer """ raise NotImplementedError
[docs]def bb(npaths, start, term, z, c, comm, rcord=2, a=1): r""" ``bb`` uses a Brownian bridge algorithm to construct sample paths for a free or non-free Wiener process. The initialization function :meth:`bb_init` must be called prior to the first call to ``bb``. .. _g05xb-py2-py-doc: For full information please refer to the NAG Library document for g05xb https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05xbf.html .. _g05xb-py2-py-parameters: **Parameters** **npaths** : int The number of Wiener sample paths to create. **start** : float, array-like, shape :math:`\left(d\right)` The starting value of the Wiener process. **term** : float, array-like, shape :math:`\left(d\right)` The terminal value at which the non-free Wiener process should end. If :math:`\mathrm{a} = 0`, :math:`\mathrm{term}` is ignored. **z** : float, array-like, shape :math:`\left(:, :\right)` Note: the required extent for this argument in dimension 1 is determined as follows: if :math:`\mathrm{rcord}=1`: :math:`{ d \times \left(\textit{N}+1-\mathrm{a}\right) }`; if :math:`\mathrm{rcord}=2`: :math:`\mathrm{npaths}`; otherwise: :math:`0`. Note: the required extent for this argument in dimension 2 is determined as follows: if :math:`\mathrm{rcord}=1`: :math:`\mathrm{npaths}`; if :math:`\mathrm{rcord}=2`: :math:`{ d \times \left(\textit{N}+1-\mathrm{a}\right) }`; otherwise: :math:`0`. The Normal random numbers used to construct the sample paths. If quasi-random numbers are used, the :math:`d\times \left(\textit{N}+1-\mathrm{a}\right)`-dimensional quasi-random points should be stored in successive rows of :math:`Z`. **c** : float, array-like, shape :math:`\left(d, d\right)` The lower triangular Cholesky factorization :math:`C` such that :math:`CC^\mathrm{T}` gives the covariance matrix of the Wiener process. Elements of :math:`C` above the diagonal are not referenced. **comm** : dict, communication object Communication structure. This argument must have been initialized by a prior call to :meth:`bb_init`. **rcord** : int, optional The order in which Normal random numbers are stored in :math:`\mathrm{z}` and in which the generated values are returned in :math:`\mathrm{b}`. **a** : int, optional If :math:`\mathrm{a} = 0`, a free Wiener process is created beginning at :math:`\mathrm{start}` and :math:`\mathrm{term}` is ignored. If :math:`\mathrm{a} = 1`, a non-free Wiener process is created beginning at :math:`\mathrm{start}` and ending at :math:`\mathrm{term}`. **Returns** **z** : float, ndarray, shape :math:`\left(:, :\right)` The Normal random numbers premultiplied by :math:`C`. **b** : float, ndarray, shape :math:`\left(:, :\right)` The values of the Wiener sample paths. Let :math:`X_{{p,i}}^k` denote the :math:`k`\ th dimension of the :math:`i`\ th point of the :math:`p`\ th sample path where :math:`1\leq k\leq d`, :math:`1\leq i\leq \textit{N}+1` and :math:`1\leq p\leq \mathrm{npaths}`. The point :math:`X_{{p,i}}^k` is stored at :math:`B\left(p, {k+\left(i-1\right)\times d}\right)`. The starting value :math:`\mathrm{start}` is never stored, whereas the terminal value is always stored. .. _g05xb-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`-99`) An unexpected error occurred during execution of ``bb``. Please contact `NAG <https://www.nag.com>`__ with the following error message: error in :math:`\langle\mathit{\boldsymbol{value}}\rangle`, :math:`\text{ASSERT} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`1`) On entry, :math:`\mathrm{comm}`\ ['rcomm'] was not initialized or has been corrupted. (`errno` :math:`2`) On entry, :math:`\mathrm{npaths} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{npaths}\geq 1`. (`errno` :math:`3`) On entry, the value of :math:`\mathrm{rcord}` is invalid. (`errno` :math:`4`) On entry, :math:`d = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`d\geq 1`. (`errno` :math:`5`) On entry, :math:`\mathrm{a} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{a} = 0\text{ or }1`. (`errno` :math:`6`) On entry, :math:`\textit{ldz} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`d\times \left({\textit{ntimes}}+1-\mathrm{a}\right) = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\textit{ldz}\geq d\times \left({\textit{ntimes}}+1-\mathrm{a}\right)`. .. _g05xb-py2-py-notes: **Notes** For details on the Brownian bridge algorithm and the bridge construction order see `the G05 Introduction <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05intro.html#bb>`__ and :ref:`Notes for bb_init <g05xa-py2-py-notes>`. Recall that the terms Wiener process (or free Wiener process) and Brownian motion are often used interchangeably, while a non-free Wiener process (also known as a Brownian bridge process) refers to a process which is forced to terminate at a given point. .. _g05xb-py2-py-references: **References** Glasserman, P, 2004, `Monte Carlo Methods in Financial Engineering`, Springer """ raise NotImplementedError
[docs]def bb_inc_init(t0, tend, times): r""" ``bb_inc_init`` initializes the Brownian bridge increments generator :meth:`bb_inc`. It must be called before any calls to :meth:`bb_inc`. .. _g05xc-py2-py-doc: For full information please refer to the NAG Library document for g05xc https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05xcf.html .. _g05xc-py2-py-parameters: **Parameters** **t0** : float The starting value :math:`t_0` of the time interval. **tend** : float The end value :math:`T` of the time interval. **times** : float, array-like, shape :math:`\left(\textit{ntimes}\right)` The points in the time interval :math:`\left(t_0, T\right)` at which the Wiener process is to be constructed. The order in which points are listed in :math:`\mathrm{times}` determines the bridge construction order. The function :meth:`bb_make_bridge_order` can be used to create predefined bridge construction orders from a set of input times. **Returns** **comm** : dict, communication object Communication structure. .. _g05xc-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`-99`) An unexpected error occurred during execution of ``bb_inc_init``. Please contact `NAG <https://www.nag.com>`__ with the following error message: error in :math:`\langle\mathit{\boldsymbol{value}}\rangle`, :math:`\text{ASSERT} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`1`) On entry, :math:`\mathrm{tend} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{t0} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{tend} > \mathrm{t0}`. (`errno` :math:`2`) On entry, :math:`\textit{ntimes} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\textit{ntimes}\geq 1`. (`errno` :math:`3`) On entry, :math:`\mathrm{times}[\langle\mathit{\boldsymbol{value}}\rangle] = \langle\mathit{\boldsymbol{value}}\rangle`, :math:`\mathrm{t0} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{tend} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{t0} < \mathrm{times}[i-1] < \mathrm{tend}` for all :math:`i`. (`errno` :math:`4`) On entry, :math:`\mathrm{times}[i-1] = \mathrm{times}[j-1] = \langle\mathit{\boldsymbol{value}}\rangle`, for :math:`i = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`j = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: all elements of :math:`\mathrm{times}` must be unique. .. _g05xc-py2-py-notes: **Notes** **Brownian Bridge Algorithm** Details on the Brownian bridge algorithm and the Brownian bridge process (sometimes also called a non-free Wiener process) can be found in `the G05 Introduction <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05intro.html#bb>`__. We briefly recall some notation and definitions. Fix two times :math:`t_0 < T` and let :math:`\left(t_i\right)_{{1\leq i\leq N}}` be any set of time points satisfying :math:`t_0 < t_1 < t_2<⋯<t_N < T`. Let :math:`\left(X_{{t_i}}\right)_{{1\leq i\leq N}}` denote a :math:`d`-dimensional Wiener sample path at these time points, and let :math:`C` be any :math:`d\times d` matrix such that :math:`CC^\mathrm{T}` is the desired covariance structure for the Wiener process. Each point :math:`X_{{t_i}}` of the sample path is constructed according to the Brownian bridge interpolation algorithm (see Glasserman (2004) or `the G05 Introduction <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05intro.html#bb>`__). We always start at some fixed point :math:`X_{t_0} = x \in \mathbb{R}^d`. If we set :math:`X_T = x+C\sqrt{T-t_0}Z` where :math:`Z` is any :math:`d`-dimensional standard Normal random variable, then :math:`X` will behave like a normal (free) Wiener process. However if we fix the terminal value :math:`X_T = w \in \mathbb{R}^d`, then :math:`X` will behave like a non-free Wiener process. The Brownian bridge increments generator uses the Brownian bridge algorithm to construct sample paths for the (free or non-free) Wiener process :math:`X`, and then uses this to compute the `scaled Wiener increments` .. math:: \frac{{X_{{t_1}}-X_{{t_0}}}}{{t_1-t_0}},\frac{{X_{{t_2}}-X_{{t_1}}}}{{t_2-t_1}},\ldots,\frac{{X_{{t_{{N}}}}-X_{{t_{{N-1}}}}}}{{t_N-t_{{N-1}}}},\frac{{X_T-X_{{t_N}}}}{{T-t_N}}\text{.} Such increments can be useful in computing numerical solutions to stochastic differential equations driven by (free or non-free) Wiener processes. **Implementation** Conceptually, the output of the Wiener increments generator is the same as if :meth:`bb_init` and :meth:`bb` were called first, and the scaled increments then constructed from their output. The implementation adopts a much more efficient approach whereby the scaled increments are computed directly without first constructing the Wiener sample path. Given the start and end points of the process, the order in which successive interpolation times :math:`t_j` are chosen is called the `bridge construction order`. The construction order is given by the array :math:`\mathrm{times}`. Further information on construction orders is given in `the G05 Introduction <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05intro.html#bb-algo>`__. For clarity we consider here the common scenario where the Brownian bridge algorithm is used with quasi-random points. If pseudorandom numbers are used instead, these details can be ignored. Suppose we require the increments of :math:`P` Wiener sample paths each of dimension :math:`d`. The main input to the Brownian bridge increments generator is then an array of quasi-random points :math:`Z^1,Z^2,…,Z^P` where each point :math:`Z^p = \left(Z_1^p, Z_2^p, \ldots, Z_D^p\right)` has dimension :math:`D = d\left(N+1\right)` or :math:`D = dN` depending on whether a free or non-free Wiener process is required. When :meth:`bb_inc` is called, the :math:`p`\ th sample path for :math:`1\leq p\leq P` is constructed as follows: if a non-free Wiener process is required set :math:`X_T` equal to the terminal value :math:`w`, otherwise construct :math:`X_T` as .. math:: X_T = X_{{t_0}}+C\sqrt{T-t_0}\left[\begin{array}{c}Z_1^p\\ \vdots \\Z_d^p\end{array}\right] where :math:`C` is the matrix described in `Brownian Bridge Algorithm <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05xcf.html#background>`__. The array :math:`\mathrm{times}` holds the remaining time points :math:`t_1,t_2,…t_N` in the order in which the bridge is to be constructed. For each :math:`j = 1,…,N` set :math:`r = \mathrm{times}[j-1]`, find .. math:: q = \text{max}\left\{{t_0,\mathrm{times}[i-1]:1\leq i < j}, {\mathrm{times}[i-1] < r}\right\} and .. math:: s = \text{min}\left\{T, {\mathrm{times}[i-1]:1\leq i < j}, {\mathrm{times}[i-1] > r}\right\}\text{} and construct the point :math:`X_r` as .. math:: X_r = \frac{{X_q\left(s-r\right)+X_s\left(r-q\right)}}{{s-q}}+C\sqrt{\frac{{\left(s-r\right)\left(r-q\right)}}{{\left(s-q\right)}}}\left[\begin{array}{c}Z_{{jd-ad+1}}^p\\ \vdots \\Z_{{jd-ad+d}}^p\end{array}\right] where :math:`a = 0` or :math:`a = 1` depending on whether a free or non-free Wiener process is required. The function :meth:`bb_make_bridge_order` can be used to initialize the :math:`\mathrm{times}` array for several predefined bridge construction orders. Lastly, the scaled Wiener increments .. math:: \frac{{X_{{t_1}}-X_{{t_0}}}}{{t_1-t_0}},\frac{{X_{{t_2}}-X_{{t_1}}}}{{t_2-t_1}},…,\frac{{X_{{t_{{N}}}}-X_{{t_{{N-1}}}}}}{{t_N-t_{{N-1}}}},\frac{{X_T-X_{{t_N}}}}{{T-t_N}} are computed. .. _g05xc-py2-py-references: **References** Glasserman, P, 2004, `Monte Carlo Methods in Financial Engineering`, Springer See Also -------- :meth:`naginterfaces.library.examples.rand.bb_inc_ex.main` """ raise NotImplementedError
[docs]def bb_inc(npaths, diff, z, c, comm, rcord=2, a=1): r""" ``bb_inc`` computes scaled increments of sample paths of a free or non-free Wiener process, where the sample paths are constructed by a Brownian bridge algorithm. The initialization function :meth:`bb_inc_init` must be called prior to the first call to ``bb_inc``. .. _g05xd-py2-py-doc: For full information please refer to the NAG Library document for g05xd https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05xdf.html .. _g05xd-py2-py-parameters: **Parameters** **npaths** : int The number of Wiener sample paths. **diff** : float, array-like, shape :math:`\left(d\right)` The difference between the terminal value and starting value of the Wiener process. If :math:`\mathrm{a} = 0`, :math:`\mathrm{diff}` is ignored. **z** : float, array-like, shape :math:`\left(:, :\right)` Note: the required extent for this argument in dimension 1 is determined as follows: if :math:`\mathrm{rcord}=1`: :math:`{ d \times \left(\textit{N}+1-\mathrm{a}\right) }`; if :math:`\mathrm{rcord}=2`: :math:`\mathrm{npaths}`; otherwise: :math:`0`. Note: the required extent for this argument in dimension 2 is determined as follows: if :math:`\mathrm{rcord}=1`: :math:`\mathrm{npaths}`; if :math:`\mathrm{rcord}=2`: :math:`{ d \times \left(\textit{N}+1-\mathrm{a}\right) }`; otherwise: :math:`0`. The Normal random numbers used to construct the sample paths. If quasi-random numbers are used, the :math:`d\times \left(N+1-\mathrm{a}\right)`-dimensional quasi-random points should be stored in successive rows of :math:`Z`. **c** : float, array-like, shape :math:`\left(d, d\right)` The lower triangular Cholesky factorization :math:`C` such that :math:`CC^\mathrm{T}` gives the covariance matrix of the Wiener process. Elements of :math:`C` above the diagonal are not referenced. **comm** : dict, communication object Communication structure. This argument must have been initialized by a prior call to :meth:`bb_inc_init`. **rcord** : int, optional The order in which Normal random numbers are stored in :math:`\mathrm{z}` and in which the generated values are returned in :math:`\mathrm{b}`. **a** : int, optional If :math:`\mathrm{a} = 0`, a free Wiener process is created and :math:`\mathrm{diff}` is ignored. If :math:`\mathrm{a} = 1`, a non-free Wiener process is created where :math:`\mathrm{diff}` is the difference between the terminal value and the starting value of the process. **Returns** **z** : float, ndarray, shape :math:`\left(:, :\right)` The Normal random numbers premultiplied by :math:`\mathrm{c}`. **b** : float, ndarray, shape :math:`\left(:, :\right)` The scaled Wiener increments. Let :math:`X_{{p,i}}^k` denote the :math:`k`\ th dimension of the :math:`i`\ th point of the :math:`p`\ th sample path where :math:`1\leq k\leq d`, :math:`1\leq i\leq \textit{N}+1` and :math:`1\leq p\leq \mathrm{npaths}`. The increment :math:`\frac{\left(X_{{p,i}}^k-X_{{p,i-1}}^k\right)}{\left(t_i-t_{{i-1}}\right)}` is stored at :math:`B\left(p, {k+\left(i-1\right)\times d}\right)`. .. _g05xd-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`-99`) An unexpected error occurred during execution of ``bb_inc``. Please contact `NAG <https://www.nag.com>`__ with the following error message: error in :math:`\langle\mathit{\boldsymbol{value}}\rangle`, :math:`\text{ASSERT} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`1`) On entry, :math:`\mathrm{comm}`\ ['rcomm'] was not initialized or has been corrupted. (`errno` :math:`2`) On entry, :math:`\mathrm{npaths} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{npaths}\geq 1`. (`errno` :math:`3`) On entry, the value of :math:`\mathrm{rcord}` is invalid. (`errno` :math:`4`) On entry, :math:`d = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`d\geq 1`. (`errno` :math:`5`) On entry, :math:`\mathrm{a} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{a} = 0\text{ or }1`. (`errno` :math:`6`) On entry, :math:`\textit{ldz} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`d\times \left({\textit{ntimes}}+1-\mathrm{a}\right) = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\textit{ldz}\geq d\times \left({\textit{ntimes}}+1-\mathrm{a}\right)`. .. _g05xd-py2-py-notes: **Notes** For details on the Brownian bridge algorithm and the bridge construction order see `the G05 Introduction <https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05intro.html#bb>`__ and :ref:`Notes for bb_inc_init <g05xc-py2-py-notes>`. Recall that the terms Wiener process (or free Wiener process) and Brownian motion are often used interchangeably, while a non-free Wiener process (also known as a Brownian bridge process) refers to a process which is forced to terminate at a given point. Fix two times :math:`t_0 < T`, let :math:`\left(t_i\right)_{{1\leq i\leq N}}` be any set of time points satisfying :math:`t_0 < t_1 < t_2 < \cdots < t_N < T`, and let :math:`X_{{t_0}}`, :math:`\left(X_{{t_i}}\right)_{{1\leq i\leq N}}`, :math:`X_T` denote a :math:`d`-dimensional Wiener sample path at these time points. The Brownian bridge increments generator uses the Brownian bridge algorithm to construct sample paths for the (free or non-free) Wiener process :math:`X`, and then uses this to compute the `scaled Wiener increments` .. math:: \frac{{X_{{t_1}}-X_{{t_0}}}}{{t_1-t_0}},\frac{{X_{{t_2}}-X_{{t_1}}}}{{t_2-t_1}},\ldots,\frac{{X_{{t_{{N}}}}-X_{{t_{{N-1}}}}}}{{t_N-t_{{N-1}}}},\frac{{X_T-X_{{t_N}}}}{{T-t_N}} .. _g05xd-py2-py-references: **References** Glasserman, P, 2004, `Monte Carlo Methods in Financial Engineering`, Springer See Also -------- :meth:`naginterfaces.library.examples.rand.bb_inc_ex.main` """ raise NotImplementedError
[docs]def bb_make_bridge_order(t0, tend, intime, bgord=1, move=None): r""" ``bb_make_bridge_order`` takes a set of input times and permutes them to specify one of several predefined Brownian bridge construction orders. The permuted times can be passed to :meth:`bb_init` or :meth:`bb_inc_init` to initialize the Brownian bridge generators with the chosen bridge construction order. .. _g05xe-py2-py-doc: For full information please refer to the NAG Library document for g05xe https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05xef.html .. _g05xe-py2-py-parameters: **Parameters** **t0** : float :math:`t_0`, the start value of the time interval on which the Wiener process is to be constructed. **tend** : float :math:`T`, the largest time at which the Wiener process is to be constructed. **intime** : float, array-like, shape :math:`\left(\textit{ntimes}\right)` The time points, :math:`t_1,t_2,\ldots,t_N`, at which the Wiener process is to be constructed. Note that the final time :math:`T` is not included in this array. **bgord** : int, optional The bridge construction order to use. **move** : None or int, array-like, shape :math:`\left(\textit{nmove}\right)`, optional The indices of the entries in :math:`\mathrm{intime}` which should be moved to the front of the :math:`\mathrm{times}` array, with :math:`\mathrm{move}[j-1] = i` setting the :math:`j`\ th element of :math:`\mathrm{times}` to :math:`t_i`. Note that :math:`i` ranges from :math:`1` to :math:`\textit{ntimes}`. When :math:`\textit{nmove} = 0`, :math:`\mathrm{move}` is not referenced. **Returns** **times** : float, ndarray, shape :math:`\left(\textit{ntimes}\right)` The output bridge construction order. This should be passed to :meth:`bb_init` or :meth:`bb_inc_init`. .. _g05xe-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`-99`) An unexpected error occurred during execution of ``bb_make_bridge_order``. Please contact `NAG <https://www.nag.com>`__ with the following error message: error in :math:`\langle\mathit{\boldsymbol{value}}\rangle`, :math:`\text{ASSERT} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`1`) On entry, :math:`\mathrm{bgord} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{bgord} = 1`, :math:`2`, :math:`3` or :math:`4` (`errno` :math:`2`) On entry, :math:`\textit{ntimes} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\textit{ntimes}\geq 1`. (`errno` :math:`3`) On entry, :math:`\textit{nmove} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\textit{ntimes} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`0\leq \textit{nmove}\leq \textit{ntimes}`. (`errno` :math:`4`) On entry, :math:`\mathrm{intime}[0] = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{t0} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{intime}[0] > \mathrm{t0}`. (`errno` :math:`4`) On entry, :math:`\mathrm{intime}[\langle\mathit{\boldsymbol{value}}\rangle] = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{intime}[\langle\mathit{\boldsymbol{value}}\rangle] = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: the elements in :math:`\mathrm{intime}` must be in increasing order. (`errno` :math:`4`) On entry, :math:`\textit{ntimes} = \langle\mathit{\boldsymbol{value}}\rangle`, :math:`\mathrm{intime}[\textit{ntimes}-1] = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{tend} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{intime}[\textit{ntimes}-1] < \mathrm{tend}`. (`errno` :math:`5`) On entry, :math:`\mathrm{move}[\langle\mathit{\boldsymbol{value}}\rangle] = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{move}[i]\geq 1` for all :math:`i`. (`errno` :math:`5`) On entry, :math:`\mathrm{move}[\langle\mathit{\boldsymbol{value}}\rangle] = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\textit{ntimes} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{move}[i]\leq \textit{ntimes}` for all :math:`i`. (`errno` :math:`6`) On entry, :math:`\mathrm{move}[\langle\mathit{\boldsymbol{value}}\rangle]` and :math:`\mathrm{move}[\langle\mathit{\boldsymbol{value}}\rangle]` both equal :math:`\langle\mathit{\boldsymbol{value}}\rangle`. Constraint: all elements in :math:`\mathrm{move}` must be unique. .. _g05xe-py2-py-notes: **Notes** The Brownian bridge algorithm (see Glasserman (2004)) is a popular method for constructing a Wiener process at a set of discrete times, :math:`t_0 < t_1 < t_2 <,\ldots, < t_N < T`, for :math:`N\geq 1`. To ease notation we assume that :math:`T` has the index :math:`N+1` so that :math:`T = t_{{N+1}}`. Inherent in the algorithm is the notion of a `bridge construction order` which specifies the order in which the :math:`N+2` points of the Wiener process, :math:`X_{t_0},X_T` and :math:`X_{{t_i}}`, for :math:`\textit{i} = 1,2,\ldots,N`, are generated. The value of :math:`X_{{t_0}}` is always assumed known, and the first point to be generated is always the final time :math:`X_T`. Thereafter, successive points are generated iteratively by an interpolation formula, using points which were computed at previous iterations. In many cases the bridge construction order is not important, since any construction order will yield a correct process. However, in certain cases, for example when using quasi-random variates to construct the sample paths, the bridge construction order can be important. **Supported Bridge Construction Orders** ``bb_make_bridge_order`` accepts as input an array of time points :math:`t_1,t_2,\ldots,t_N,T` at which the Wiener process is to be sampled. These time points are then permuted to construct the bridge. In all of the supported construction orders the first construction point is :math:`T` which has index :math:`N+1`. The remaining points are constructed by iteratively bisecting (sub-intervals of) the `time indices` interval :math:`\left[0, {N+1}\right]`, as Figure [label omitted] illustrates: [figure omitted] The time indices interval is processed in levels :math:`L^{\textit{i}}`, for :math:`\textit{i} = 1,2,\ldots,`. Each level :math:`L^i` contains :math:`n_i` points :math:`L_1^i,\ldots,L_{n_i}^i` where :math:`n_i\leq 2^{{i-1}}`. The number of points at each level depends on the value of :math:`N`. The points :math:`L_j^i` for :math:`i\geq 1` and :math:`j = 1,2,\ldots n_i` are computed as follows: define :math:`L_0^0 = N+1` and set .. math:: \begin{array}{cc} L_j^i = J + \left(K-J\right)/2 &\text{where}\\ J = \mathrm{max}\left\{L_k^p:1\leq k\leq n_p\text{, }0\leq p < i\text{ and }L_k^p < L_j^i\right\} &\text{ and }\\ K = \mathrm{min}\left\{L_k^p:1\leq k\leq n_p\text{, }0\leq p < i\text{ and }L_k^p > L_j^i\right\} &\end{array} By convention the maximum of the empty set is taken to be to be zero. Figure [label omitted] illustrates the algorithm when :math:`N+1` is a power of two. When :math:`N+1` is not a power of two, one must decide how to round the divisions by :math:`2`. For example, if one rounds down to the nearest integer, then one could get the following: [figure omitted] From the series of bisections outlined above, two ways of ordering the time indices :math:`L_j^i` are supported. In both cases, levels are always processed from coarsest to finest (i.e., increasing :math:`i`). Within a level, the time indices can either be processed left to right (i.e., increasing :math:`j`) or right to left (i.e., decreasing :math:`j`). For example, when processing left to right, the sequence of time indices could be generated as: .. math:: \begin{array}{ccccccccc}N+1&L_1^1&L_1^2&L_2^2&L_1^3&L_2^3&L_3^3&L_4^3& \cdots \end{array} while when processing right to left, the same sequence would be generated as: .. math:: \begin{array}{ccccccccc}N+1&L_1^1&L_2^2&L_1^2&L_4^3&L_3^3&L_2^3&L_1^3& \cdots \end{array} ``bb_make_bridge_order``, therefore, offers four bridge construction methods; processing either left to right or right to left, with rounding either up or down. Which method is used is controlled by the :math:`\mathrm{bgord}` argument. For example, on the set of times .. math:: \begin{array}{ccccccccccccc}t_1&t_2&t_3&t_4&t_5&t_6&t_7&t_8&t_9&t_{10}&t_{11}&t_{12}&T\end{array} the Brownian bridge would be constructed in the following orders: :math:`\mathrm{bgord} = 1` (processing left to right, rounding down) .. math:: \begin{array}{ccccccccccccc}T&t_6&t_3&t_9&t_1&t_4&t_7&t_{11}&t_2&t_5&t_8&t_{10}&t_{12}\end{array} :math:`\mathrm{bgord} = 2` (processing left to right, rounding up) .. math:: \begin{array}{ccccccccccccc}T&t_7&t_4&t_{10}&t_2&t_6&t_9&t_{12}&t_1&t_3&t_5&t_8&t_{11}\end{array} :math:`\mathrm{bgord} = 3` (processing right to left, rounding down) .. math:: \begin{array}{ccccccccccccc}T&t_6&t_9&t_3&t_{11}&t_7&t_4&t_1&t_{12}&t_{10}&t_8&t_5&t_2\end{array} :math:`\mathrm{bgord} = 4` (processing right to left, rounding up) .. math:: \begin{array}{ccccccccccccc}T&t_7&t_{10}&t_4&t_{12}&t_9&t_6&t_2&t_{11}&t_8&t_5&t_3&t_1\end{array}\text{.} The four construction methods described above can be further modified through the use of the input array :math:`\mathrm{move}`. To see the effect of this argument, suppose that an array :math:`A` holds the output of ``bb_make_bridge_order`` when :math:`\textit{nmove} = 0` (i.e., the bridge construction order as specified by :math:`\mathrm{bgord}` only). Let .. math:: B = \left\{t_j:j = \mathrm{move}[i-1],i = 1,2,\ldots,\textit{nmove}\right\} be the array of all times identified by :math:`\mathrm{move}`, and let :math:`C` be the array :math:`A` with all the elements in :math:`B` removed, i.e., .. math:: C = \left\{A\left(i\right):A\left(i\right)\neq B\left(j\right),i = 1,2,\ldots,\textit{ntimes},j = 1,2,\ldots,\textit{nmove}\right\}\text{.} Then the output of ``bb_make_bridge_order`` when :math:`\textit{nmove} > 0` is given by .. math:: \begin{array}{cccccccc} B\left(1\right) & B\left(2\right) & \cdots & B\left(\textit{nmove}\right) & C\left(1\right) & C\left(2\right) & \cdots & C\left(\textit{ntimes}-\textit{nmove}\right) \end{array} When the Brownian bridge is used with quasi-random variates, this functionality can be used to allow specific sections of the bridge to be constructed using the lowest dimensions of the quasi-random points. .. _g05xe-py2-py-references: **References** Glasserman, P, 2004, `Monte Carlo Methods in Financial Engineering`, Springer See Also -------- :meth:`naginterfaces.library.examples.rand.bb_inc_ex.main` """ raise NotImplementedError
[docs]def quasi_normal(xmean, std, n, comm): r""" ``quasi_normal`` generates a quasi-random sequence from a Normal (Gaussian) distribution. It must be preceded by a call to one of the initialization functions :meth:`quasi_init` or :meth:`quasi_init_scrambled`. .. _g05yj-py2-py-doc: For full information please refer to the NAG Library document for g05yj https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05yjf.html .. _g05yj-py2-py-parameters: **Parameters** **xmean** : float, array-like, shape :math:`\left(\textit{idim}\right)` Specifies, for each dimension, the mean of the Normal distribution. **std** : float, array-like, shape :math:`\left(\textit{idim}\right)` Specifies, for each dimension, the standard deviation of the Normal distribution. **n** : int The number of quasi-random numbers required. **comm** : dict, communication object, modified in place Communication structure. This argument must have been initialized by a prior call to :meth:`quasi_init` or :meth:`quasi_init_scrambled`. **Returns** **quas** : float, ndarray, shape :math:`\left(\mathrm{n}, \textit{idim}\right)` Contains the :math:`\mathrm{n}` quasi-random numbers of dimension idim If :math:`\textit{sorder} = 2`, :math:`\mathrm{quas}[i-1,j-1]` holds the :math:`j`\ th value for the :math:`i`\ th dimension. If :math:`\textit{sorder} = 1`, :math:`\mathrm{quas}[i-1,j-1]` holds the :math:`i`\ th value for the :math:`j`\ th dimension. .. _g05yj-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{comm}`\ ['iref'] has either not been initialized or has been corrupted. (`errno` :math:`2`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`i = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{std}[i-1] = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{std}[i-1]\geq 0.0`. (`errno` :math:`4`) There have been too many calls to the generator. .. _g05yj-py2-py-notes: **Notes** ``quasi_normal`` generates a quasi-random sequence from a Normal distribution by first generating a uniform quasi-random sequence which is then transformed into a Normal sequence using the inverse of the Normal CDF. The type of uniform sequence used depends on the initialization function called and can include the low-discrepancy sequences proposed by Sobol, Faure or Niederreiter. If the initialization function :meth:`quasi_init_scrambled` was used then the underlying uniform sequence is first scrambled prior to being transformed (see :ref:`Notes for quasi_init_scrambled <g05yn-py2-py-notes>` for details). .. _g05yj-py2-py-references: **References** Bratley, P and Fox, B L, 1988, `Algorithm 659: implementing Sobol's quasirandom sequence generator`, ACM Trans. Math. Software (14(1)), 88--100 Fox, B L, 1986, `Algorithm 647: implementation and relative efficiency of quasirandom sequence generators`, ACM Trans. Math. Software (12(4)), 362--376 Wichura, 1988, `Algorithm AS 241: the percentage points of the Normal distribution`, Appl. Statist. (37), 477--484 See Also -------- :meth:`naginterfaces.library.examples.rand.bb_inc_ex.main` """ raise NotImplementedError
[docs]def quasi_lognormal(xmean, std, n, comm): r""" ``quasi_lognormal`` generates a quasi-random sequence from a log-normal distribution. It must be preceded by a call to one of the initialization functions :meth:`quasi_init` or :meth:`quasi_init_scrambled`. .. _g05yk-py2-py-doc: For full information please refer to the NAG Library document for g05yk https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05ykf.html .. _g05yk-py2-py-parameters: **Parameters** **xmean** : float, array-like, shape :math:`\left(\textit{idim}\right)` Specifies, for each dimension, the mean of the underlying Normal distribution. **std** : float, array-like, shape :math:`\left(\textit{idim}\right)` Specifies, for each dimension, the standard deviation of the underlying Normal distribution. **n** : int The number of quasi-random numbers required. **comm** : dict, communication object, modified in place Communication structure. This argument must have been initialized by a prior call to :meth:`quasi_init` or :meth:`quasi_init_scrambled`. **Returns** **quas** : float, ndarray, shape :math:`\left(\mathrm{n}, \textit{idim}\right)` Contains the :math:`\mathrm{n}` quasi-random numbers of dimension idim. If :math:`\textit{sorder} = 2`, :math:`\mathrm{quas}[i-1,j-1]` holds the :math:`j`\ th value for the :math:`i`\ th dimension. If :math:`\textit{sorder} = 1`, :math:`\mathrm{quas}[i-1,j-1]` holds the :math:`i`\ th value for the :math:`j`\ th dimension. .. _g05yk-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{comm}`\ ['iref'] has either not been initialized or has been corrupted. (`errno` :math:`2`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`3`) On entry, :math:`i = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{std}[i-1] = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{std}[i-1]\geq 0`. (`errno` :math:`4`) There have been too many calls to the generator. (`errno` :math:`5`) On entry, :math:`i = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{xmean}[i-1] = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\left\lvert \mathrm{xmean}[i-1]\right\rvert \leq \langle\mathit{\boldsymbol{value}}\rangle`. .. _g05yk-py2-py-notes: **Notes** ``quasi_lognormal`` generates a quasi-random sequence from a log-normal distribution by first generating a uniform quasi-random sequence which is then transformed into a log-normal sequence using the exponential of the inverse of the Normal CDF. The type of uniform sequence used depends on the initialization function called and can include the low-discrepancy sequences proposed by Sobol, Faure or Niederreiter. If the initialization function :meth:`quasi_init_scrambled` was used then the underlying uniform sequence is first scrambled prior to being transformed (see :ref:`Notes for quasi_init_scrambled <g05yn-py2-py-notes>` for details). .. _g05yk-py2-py-references: **References** Bratley, P and Fox, B L, 1988, `Algorithm 659: implementing Sobol's quasirandom sequence generator`, ACM Trans. Math. Software (14(1)), 88--100 Fox, B L, 1986, `Algorithm 647: implementation and relative efficiency of quasirandom sequence generators`, ACM Trans. Math. Software (12(4)), 362--376 Wichura, 1988, `Algorithm AS 241: the percentage points of the Normal distribution`, Appl. Statist. (37), 477--484 """ raise NotImplementedError
[docs]def quasi_init(genid, idim, iskip): r""" ``quasi_init`` initializes a quasi-random generator prior to calling :meth:`quasi_uniform`, :meth:`quasi_normal` or :meth:`quasi_lognormal`. .. _g05yl-py2-py-doc: For full information please refer to the NAG Library document for g05yl https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05ylf.html .. _g05yl-py2-py-parameters: **Parameters** **genid** : int Must identify the quasi-random generator to use. :math:`\mathrm{genid} = 1` Sobol generator. :math:`\mathrm{genid} = 2` Sobol (A659) generator. :math:`\mathrm{genid} = 3` Niederreiter generator. :math:`\mathrm{genid} = 4` Faure generator. **idim** : int The number of dimensions required. **iskip** : int The number of terms of the sequence to skip on initialization for the Sobol and Niederreiter generators. If :math:`\mathrm{genid} = 4`, :math:`\mathrm{iskip}` is ignored. **Returns** **comm** : dict, communication object Communication structure. .. _g05yl-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{genid} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{genid} = 1`, :math:`2`, :math:`3` or :math:`4`. (`errno` :math:`2`) On entry, :math:`\mathrm{idim} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`1\leq \mathrm{idim}\leq \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`5`) On entry, :math:`\mathrm{iskip} < 0` or :math:`\mathrm{iskip}` is too large: :math:`\mathrm{iskip} = \langle\mathit{\boldsymbol{value}}\rangle`, maximum value is :math:`\langle\mathit{\boldsymbol{value}}\rangle`. .. _g05yl-py2-py-notes: **Notes** ``quasi_init`` selects a quasi-random number generator through the input value of :math:`\mathrm{genid}` and initializes the :math:`\mathrm{comm}`\ ['iref'] communication array for use by the functions :meth:`quasi_uniform`, :meth:`quasi_normal` or :meth:`quasi_lognormal`. One of three types of quasi-random generator may be chosen, allowing the low-discrepancy sequences proposed by Sobol, Faure or Niederreiter to be generated. Two sets of Sobol sequences are supplied, the first, is based on the work of Joe and Kuo (2008). The second, referred to in the documentation as 'Sobol (A659)', is based on Algorithm 659 of Bratley and Fox (1988) with the extension to 1111 dimensions proposed by Joe and Kuo (2003). Both sets of Sobol sequences should satisfy the so-called Property A, up to :math:`1111` dimensions, but the first set should have better two-dimensional projections than those produced using Algorithm 659. .. _g05yl-py2-py-references: **References** Bratley, P and Fox, B L, 1988, `Algorithm 659: implementing Sobol's quasirandom sequence generator`, ACM Trans. Math. Software (14(1)), 88--100 Fox, B L, 1986, `Algorithm 647: implementation and relative efficiency of quasirandom sequence generators`, ACM Trans. Math. Software (12(4)), 362--376 Joe, S and Kuo, F Y, 2003, `Remark on Algorithm 659: implementing Sobol's quasirandom sequence generator`, ACM Trans. Math. Software (TOMS) (29), 49--57 Joe, S and Kuo, F Y, 2008, `Constructing Sobol sequences with better two-dimensional projections`, SIAM J. Sci. Comput. (30), 2635--2654 """ raise NotImplementedError
[docs]def quasi_uniform(n, comm, rcord=1): r""" ``quasi_uniform`` generates a uniformly distributed low-discrepancy sequence as proposed by Sobol, Faure or Niederreiter. It must be preceded by a call to one of the initialization functions :meth:`quasi_init` or :meth:`quasi_init_scrambled`. .. _g05ym-py2-py-doc: For full information please refer to the NAG Library document for g05ym https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05ymf.html .. _g05ym-py2-py-parameters: **Parameters** **n** : int The number of quasi-random numbers required. **comm** : dict, communication object, modified in place Communication structure. This argument must have been initialized by a prior call to :meth:`quasi_init` or :meth:`quasi_init_scrambled`. **rcord** : int, optional The order in which the generated values are returned. **Returns** **quas** : float, ndarray, shape :math:`\left(:, :\right)` Contains the :math:`\mathrm{n}` quasi-random numbers of dimension idim. If :math:`\mathrm{rcord} = 1`, :math:`\mathrm{quas}[i-1,j-1]` holds the :math:`j`\ th value for the :math:`i`\ th dimension. If :math:`\mathrm{rcord} = 2`, :math:`\mathrm{quas}[i-1,j-1]` holds the :math:`i`\ th value for the :math:`j`\ th dimension. .. _g05ym-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{n}\geq 0`. (`errno` :math:`1`) On entry, value of :math:`\mathrm{n}` would result in too many calls to the generator: :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`, generator has previously been called :math:`\langle\mathit{\boldsymbol{value}}\rangle` times. (`errno` :math:`2`) On entry, :math:`\mathrm{rcord} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{rcord} = 1` or :math:`2`. (`errno` :math:`4`) On entry, :math:`\textit{ldquas} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{n} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: if :math:`\mathrm{rcord} = 2`, :math:`\textit{ldquas}\geq \mathrm{n}`. (`errno` :math:`5`) On entry, :math:`\mathrm{comm}`\ ['iref'] has either not been initialized or has been corrupted. .. _g05ym-py2-py-notes: **Notes** Low discrepancy (quasi-random) sequences are used in numerical integration, simulation and optimization. Like pseudorandom numbers they are uniformly distributed but they are not statistically independent, rather they are designed to give more even distribution in multidimensional space (uniformity). Therefore, they are often more efficient than pseudorandom numbers in multidimensional Monte Carlo methods. ``quasi_uniform`` generates a set of points :math:`x^1,x^2,\ldots,x^N` with high uniformity in the :math:`S`-dimensional unit cube :math:`I^S = \left[0, 1\right]^S`. Let :math:`G` be a subset of :math:`I^S` and define the counting function :math:`S_N\left(G\right)` as the number of points :math:`x^i \in G`. For each :math:`x = \left(x_1, x_2, \ldots, x_S\right) \in I^S`, let :math:`G_x` be the rectangular :math:`S`-dimensional region .. math:: G_x = \left[0, x_1\right)\times \left[0, x_2\right)\times \cdots \times \left[0, x_S\right) with volume :math:`x_1,x_2,\ldots,x_S`. Then one measure of the uniformity of the points :math:`x^1,x^2,\ldots,x^N` is the discrepancy: .. math:: D_N^*\left(x^1, x^2, \ldots, x^N\right) = \mathrm{sup}_{{x \in I^S}}\left(\left\lvert S_N\left(G_x\right)-Nx_1,x_2,\ldots,x_S\right\rvert \right)\text{.} which has the form .. math:: D_N^*\left(x^1, x^2, \ldots, x^N\right)\leq C_S\left(\log\left(N\right)\right)^S+\mathrm{O}\left(\left(\log\left(N\right)\right)^{{S-1}}\right)\quad \text{ for all }\quad N\geq 2\text{.} The principal aim in the construction of low-discrepancy sequences is to find sequences of points in :math:`I^S` with a bound of this form where the constant :math:`C_S` is as small as possible. The type of low-discrepancy sequence generated by ``quasi_uniform`` depends on the initialization function called and can include those proposed by Sobol, Faure or Niederreiter. If the initialization function :meth:`quasi_init_scrambled` was used then the sequence will be scrambled (see :ref:`Notes for quasi_init_scrambled <g05yn-py2-py-notes>` for details). .. _g05ym-py2-py-references: **References** Bratley, P and Fox, B L, 1988, `Algorithm 659: implementing Sobol's quasirandom sequence generator`, ACM Trans. Math. Software (14(1)), 88--100 Fox, B L, 1986, `Algorithm 647: implementation and relative efficiency of quasirandom sequence generators`, ACM Trans. Math. Software (12(4)), 362--376 """ raise NotImplementedError
[docs]def quasi_init_scrambled(genid, stype, idim, iskip, nsdigi, statecomm): r""" ``quasi_init_scrambled`` initializes a scrambled quasi-random generator prior to calling :meth:`quasi_uniform`, :meth:`quasi_normal` or :meth:`quasi_lognormal`. It must be preceded by a call to one of the pseudorandom initialization functions :meth:`init_repeat` or :meth:`init_nonrepeat`. .. _g05yn-py2-py-doc: For full information please refer to the NAG Library document for g05yn https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05ynf.html .. _g05yn-py2-py-parameters: **Parameters** **genid** : int Must identify the quasi-random generator to use. :math:`\mathrm{genid} = 1` Sobol generator. :math:`\mathrm{genid} = 2` Sobol (A659) generator. :math:`\mathrm{genid} = 3` Niederreiter generator. **stype** : int Must identify the scrambling method to use. :math:`\mathrm{stype} = 0` No scrambling. This is equivalent to calling :meth:`quasi_init`. :math:`\mathrm{stype} = 1` Owen like scrambling. :math:`\mathrm{stype} = 2` Faure--Tezuka scrambling. :math:`\mathrm{stype} = 3` Owen and Faure--Tezuka scrambling. **idim** : int The number of dimensions required. **iskip** : int The number of terms of the sequence to skip on initialization for the Sobol and Niederreiter generators. **nsdigi** : int Controls the number of digits (bits) to scramble when :math:`\mathrm{genid} = 1` or :math:`2`, otherwise :math:`\mathrm{nsdigi}` is ignored. If :math:`\mathrm{nsdigi} < 1` or :math:`\mathrm{nsdigi} > 30` then all the digits are scrambled. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **comm** : dict, communication object Communication structure. .. _g05yn-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{genid} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`1\leq \mathrm{genid}\leq \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`2`) On entry, :math:`\mathrm{stype} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`0\leq \mathrm{stype}\leq 3`. (`errno` :math:`3`) On entry, :math:`\mathrm{idim} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`1\leq \mathrm{idim}\leq \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`6`) On entry, :math:`\mathrm{iskip} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`0\leq \mathrm{iskip}\leq 2^{30}`. (`errno` :math:`8`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05yn-py2-py-notes: **Notes** ``quasi_init_scrambled`` selects a quasi-random number generator through the input value of :math:`\mathrm{genid}`, a method of scrambling through the input value of :math:`\mathrm{stype}` and initializes the :math:`\mathrm{comm}`\ ['iref'] communication array for use in the functions :meth:`quasi_uniform`, :meth:`quasi_normal` or :meth:`quasi_lognormal`. Scrambled quasi-random sequences are an extension of standard quasi-random sequences that attempt to eliminate the bias inherent in a quasi-random sequence whilst retaining the low-discrepancy properties. The use of a scrambled sequence allows error estimation of Monte Carlo results by performing a number of iterates and computing the variance of the results. This implementation of scrambled quasi-random sequences is based on TOMS Algorithm 823 and details can be found in the accompanying paper, Hong and Hickernell (2003). Three methods of scrambling are supplied; the first a restricted form of Owen's scrambling (Owen (1995)), the second based on the method of Faure and Tezuka (2000) and the last method combines the first two. Scrambled versions of the Niederreiter sequence and two sets of Sobol sequences are provided. The first Sobol sequence is obtained using :math:`\mathrm{genid} = 1`. The first 10000 direction numbers for this sequence are based on the work of Joe and Kuo (2008). For dimensions greater than 10000 the direction numbers are randomly generated using the pseudorandom generator specified in :math:`\mathrm{statecomm}`\ ['state'] (see Jäckel (2002) for details). The second Sobol sequence is obtained using :math:`\mathrm{genid} = 2` and referred to in the documentation as 'Sobol (A659)'. The first 1111 direction numbers for this sequence are based on Algorithm 659 of Bratley and Fox (1988) with the extension proposed by Joe and Kuo (2003). For dimensions greater than 1111 the direction numbers are once again randomly generated. The Niederreiter sequence is obtained by setting :math:`\mathrm{genid} = 3`. .. _g05yn-py2-py-references: **References** Bratley, P and Fox, B L, 1988, `Algorithm 659: implementing Sobol's quasirandom sequence generator`, ACM Trans. Math. Software (14(1)), 88--100 Faure, H and Tezuka, S, 2000, `Another random scrambling of digital (t,s)-sequences`, Monte Carlo and Quasi-Monte Carlo Methods, Springer-Verlag, Berlin, Germany, (eds K T Fang, F J Hickernell and H Niederreiter) Hong, H S and Hickernell, F J, 2003, `Algorithm 823: implementing scrambled digital sequences`, ACM Trans. Math. Software (29:2), 95--109 Jäckel, P, 2002, `Monte Carlo Methods in Finance`, Wiley Finance Series, John Wiley and Sons, England Joe, S and Kuo, F Y, 2003, `Remark on Algorithm 659: implementing Sobol's quasirandom sequence generator`, ACM Trans. Math. Software (TOMS) (29), 49--57 Joe, S and Kuo, F Y, 2008, `Constructing Sobol sequences with better two-dimensional projections`, SIAM J. Sci. Comput. (30), 2635--2654 Niederreiter, H, 1988, `Low-discrepancy and low dispersion sequences`, Journal of Number Theory (30), 51--70 Owen, A B, 1995, `Randomly permuted (t,m,s)-nets and (t,s)-sequences`, Monte Carlo and Quasi-Monte Carlo Methods in Scientific Computing, Lecture Notes in Statistics (106), Springer-Verlag, New York, NY, 299--317, (eds H Niederreiter and P J-S Shiue) See Also -------- :meth:`naginterfaces.library.examples.rand.bb_inc_ex.main` """ raise NotImplementedError
[docs]def field_1d_user_setup(ns, xmin, xmax, var, cov1, maxm=None, pad=1, icorr=0, data=None): r""" ``field_1d_user_setup`` performs the setup required in order to simulate stationary Gaussian random fields in one dimension, for a user-defined variogram, using the `circulant embedding method`. Specifically, the eigenvalues of the extended covariance matrix (or embedding matrix) are calculated, and their square roots output, for use by :meth:`field_1d_generate`, which simulates the random field. .. _g05zm-py2-py-doc: For full information please refer to the NAG Library document for g05zm https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05zmf.html .. _g05zm-py2-py-parameters: **Parameters** **ns** : int The number of sample points to be generated in realizations of the random field. **xmin** : float The lower bound for the interval over which the random field is to be simulated. **xmax** : float The upper bound for the interval over which the random field is to be simulated. **var** : float The multiplicative factor :math:`\sigma^2` of the variogram :math:`\gamma \left(x\right)`. **cov1** : callable gamma = cov1(x, data=None) :math:`\mathrm{cov1}` must evaluate the variogram :math:`\gamma \left(x\right)`, without the multiplicative factor :math:`\sigma^2`, for all :math:`x\geq 0`. The value returned in :math:`\mathrm{gamma}` is multiplied internally by :math:`\mathrm{var}`. **Parameters** **x** : float The value :math:`x` at which the variogram :math:`\gamma \left(x\right)` is to be evaluated. **data** : arbitrary, optional, modifiable in place User-communication data for callback functions. **Returns** **gamma** : float The value of the variogram :math:`\frac{{\gamma \left(x\right)}}{{\sigma^2}}`. **maxm** : None or int, optional Note: if this argument is **None** then a default value will be used, determined as follows: :math:`2^{{3 + \mathrm{ceiling}\left(\log_2\left(\left(\mathrm{ns}-1\right) \right)\right) }}`. The maximum size of the circulant matrix to use. For example, if the embedding matrix is to be allowed to double in size three times before the approximation procedure is used, then choose :math:`\mathrm{maxm} = 2^{{k+2}}` where :math:`k = 1+\left\lceil \mathrm{log2}\left(\mathrm{ns}-1\right)\right\rceil`. **pad** : int, optional Determines whether the embedding matrix is padded with zeros, or padded with values of the variogram. The choice of padding may affect how big the embedding matrix must be in order to be positive semidefinite. :math:`\mathrm{pad} = 0` The embedding matrix is padded with zeros. :math:`\mathrm{pad} = 1` The embedding matrix is padded with values of the variogram. **icorr** : int, optional Determines which approximation to implement if required, as described in :ref:`Notes <g05zm-py2-py-notes>`. **data** : arbitrary, optional User-communication data for callback functions. **Returns** **lam** : float, ndarray, shape :math:`\left(\mathrm{maxm}\right)` Contains the square roots of the eigenvalues of the embedding matrix. **xx** : float, ndarray, shape :math:`\left(\mathrm{ns}\right)` The points at which values of the random field will be output. **m** : int The size of the embedding matrix. **approx** : int Indicates whether approximation was used. :math:`\mathrm{approx} = 0` No approximation was used. :math:`\mathrm{approx} = 1` Approximation was used. **rho** : float Indicates the scaling of the covariance matrix. :math:`\mathrm{rho} = 1.0` unless approximation was used with :math:`\mathrm{icorr} = 0` or :math:`1`. **icount** : int Indicates the number of negative eigenvalues in the embedding matrix which have had to be set to zero. **eig** : float, ndarray, shape :math:`\left(3\right)` Indicates information about the negative eigenvalues in the embedding matrix which have had to be set to zero. :math:`\mathrm{eig}[0]` contains the smallest eigenvalue, :math:`\mathrm{eig}[1]` contains the sum of the squares of the negative eigenvalues, and :math:`\mathrm{eig}[2]` contains the sum of the absolute values of the negative eigenvalues. .. _g05zm-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{ns} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{ns}\geq 1`. (`errno` :math:`2`) On entry, :math:`\mathrm{xmin} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{xmax} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{xmin} < \mathrm{xmax}`. (`errno` :math:`4`) On entry, :math:`\mathrm{maxm} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: the minimum calculated value for :math:`\mathrm{maxm}` is :math:`\langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`5`) On entry, :math:`\mathrm{var} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{var}\geq 0.0`. (`errno` :math:`7`) On entry, :math:`\mathrm{pad} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{pad} = 0` or :math:`1`. (`errno` :math:`8`) On entry, :math:`\mathrm{icorr} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{icorr} = 0`, :math:`1` or :math:`2`. .. _g05zm-py2-py-notes: **Notes** A one-dimensional random field :math:`Z\left(x\right)` in :math:`\mathbb{R}` is a function which is random at every point :math:`x \in \mathbb{R}`, so :math:`Z\left(x\right)` is a random variable for each :math:`x`. The random field has a mean function :math:`\mu \left(x\right) = 𝔼\left[Z\left(x\right)\right]` and a symmetric positive semidefinite covariance function :math:`C\left(x, y\right) = 𝔼\left[\left(Z\left(x\right)-\mu \left(x\right)\right)\left(Z\left(y\right)-\mu \left(y\right)\right)\right]`. :math:`Z\left(x\right)` is a Gaussian random field if for any choice of :math:`n \in ℕ` and :math:`x_1,\ldots,x_n \in \mathbb{R}`, the random vector :math:`\left[Z\left(x_1\right),\ldots,Z\left(x_n\right)\right]^\mathrm{T}` follows a multivariate Normal distribution, which would have a mean vector :math:`\tilde{\mu }` with entries :math:`\tilde{\mu }_i = \mu \left(x_i\right)` and a covariance matrix :math:`\tilde{C}` with entries :math:`\tilde{C}_{{ij}} = C\left(x_i, x_j\right)`. A Gaussian random field :math:`Z\left(x\right)` is stationary if :math:`\mu \left(x\right)` is constant for all :math:`x \in \mathbb{R}` and :math:`C\left(x, y\right) = C\left({x+a}, {y+a}\right)` for all :math:`\left. x, y, a\right. \in \mathbb{R}` and hence we can express the covariance function :math:`C\left(x, y\right)` as a function :math:`\gamma` of one variable: :math:`C\left(x, y\right) = \gamma \left(x-y\right)`. :math:`\gamma` is known as a variogram (or more correctly, a semivariogram) and includes the multiplicative factor :math:`\sigma^2` representing the variance such that :math:`\gamma \left(0\right) = \sigma^2`. The functions ``field_1d_user_setup`` and :meth:`field_1d_generate` are used to simulate a one-dimensional stationary Gaussian random field, with mean function zero and variogram :math:`\gamma \left(x\right)`, over an interval :math:`\left[x_{\textit{min}}, x_{\textit{max}}\right]`, using an equally spaced set of :math:`N` points on the interval. The problem reduces to sampling a Normal random vector :math:`\mathbf{X}` of size :math:`N`, with mean vector zero and a symmetric Toeplitz covariance matrix :math:`A`. Since :math:`A` is in general expensive to factorize, a technique known as the `circulant embedding method` is used. :math:`A` is embedded into a larger, symmetric circulant matrix :math:`B` of size :math:`M\geq 2\left(N-1\right)`, which can now be factorized as :math:`B = W\Lambda W^* = R^*R`, where :math:`W` is the Fourier matrix (:math:`W^*` is the complex conjugate of :math:`W`), :math:`\Lambda` is the diagonal matrix containing the eigenvalues of :math:`B` and :math:`R = \Lambda^{\frac{1}{2}}W^*`. :math:`B` is known as the embedding matrix. The eigenvalues can be calculated by performing a discrete Fourier transform of the first row (or column) of :math:`B` and multiplying by :math:`M`, and so only the first row (or column) of :math:`B` is needed -- the whole matrix does not need to be formed. As long as all of the values of :math:`\Lambda` are non-negative (i.e., :math:`B` is positive semidefinite), :math:`B` is a covariance matrix for a random vector :math:`\mathbf{Y}`, two samples of which can now be simulated from the real and imaginary parts of :math:`R^*\left(\mathbf{U}+i\mathbf{V}\right)`, where :math:`\mathbf{U}` and :math:`\mathbf{V}` have elements from the standard Normal distribution. Since :math:`R^*\left(\mathbf{U}+i\mathbf{V}\right) = W\Lambda^{\frac{1}{2}}\left(\mathbf{U}+i\mathbf{V}\right)`, this calculation can be done using a discrete Fourier transform of the vector :math:`\Lambda^{\frac{1}{2}}\left(\mathbf{U}+i\mathbf{V}\right)`. Two samples of the random vector :math:`\mathbf{X}` can now be recovered by taking the first :math:`N` elements of each sample of :math:`\mathbf{Y}` -- because the original covariance matrix :math:`A` is embedded in :math:`B`, :math:`\mathbf{X}` will have the correct distribution. If :math:`B` is not positive semidefinite, larger embedding matrices :math:`B` can be tried; however if the size of the matrix would have to be larger than :math:`\mathrm{maxm}`, an approximation procedure is used. We write :math:`\Lambda = \Lambda_++\Lambda_-`, where :math:`\Lambda_+` and :math:`\Lambda_-` contain the non-negative and negative eigenvalues of :math:`B` respectively. Then :math:`B` is replaced by :math:`\rho B_+` where :math:`B_+ = W\Lambda_+W^*` and :math:`\rho \in \left(0, 1\right]` is a scaling factor. The error :math:`\epsilon` in approximating the distribution of the random field is given by .. math:: \epsilon = \sqrt{\frac{{\left(1-\rho \right)^2\mathrm{trace}\left(\Lambda \right)+\rho^2\mathrm{trace}\left(\Lambda_-\right)}}{M}}\text{.} Three choices for :math:`\rho` are available, and are determined by the input argument :math:`\mathrm{icorr}`: setting :math:`\mathrm{icorr} = 0` sets .. math:: \rho = \frac{\mathrm{trace}\left(\Lambda \right)}{\mathrm{trace}\left(\Lambda_+\right)}\text{,} setting :math:`\mathrm{icorr} = 1` sets .. math:: \rho = \sqrt{\frac{\mathrm{trace}\left(\Lambda \right)}{\mathrm{trace}\left(\Lambda_+\right)}}\text{,} setting :math:`\mathrm{icorr} = 2` sets :math:`\rho = 1`. ``field_1d_user_setup`` finds a suitable positive semidefinite embedding matrix :math:`B` and outputs its size, :math:`\mathrm{m}`, and the square roots of its eigenvalues in :math:`\mathrm{lam}`. If approximation is used, information regarding the accuracy of the approximation is output. Note that only the first row (or column) of :math:`B` is actually formed and stored. .. _g05zm-py2-py-references: **References** Dietrich, C R and Newsam, G N, 1997, `Fast and exact simulation of stationary Gaussian processes through circulant embedding of the covariance matrix`, SIAM J. Sci. Comput. (18), 1088--1107 Schlather, M, 1999, `Introduction to positive definite functions and to unconditional simulation of random fields`, Technical Report ST 99--10, Lancaster University Wood, A T A and Chan, G, 1994, `Simulation of stationary Gaussian processes in` :math:`\left[0, 1\right]^d`, Journal of Computational and Graphical Statistics (3(4)), 409--432 """ raise NotImplementedError
[docs]def field_1d_predef_setup(ns, xmin, xmax, var, icov1, params, maxm=None, pad=1, icorr=0): r""" ``field_1d_predef_setup`` performs the setup required in order to simulate stationary Gaussian random fields in one dimension, for a preset variogram, using the `circulant embedding method`. Specifically, the eigenvalues of the extended covariance matrix (or embedding matrix) are calculated, and their square roots output, for use by :meth:`field_1d_generate`, which simulates the random field. .. _g05zn-py2-py-doc: For full information please refer to the NAG Library document for g05zn https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05znf.html .. _g05zn-py2-py-parameters: **Parameters** **ns** : int The number of sample points to be generated in realizations of the random field. **xmin** : float The lower bound for the interval over which the random field is to be simulated. Note that if :math:`\mathrm{icov1} = 14` (for simulating fractional Brownian motion), :math:`\mathrm{xmin}` is not referenced and the lower bound for the interval is set to zero. **xmax** : float The upper bound for the interval over which the random field is to be simulated. Note that if :math:`\mathrm{icov1} = 14` (for simulating fractional Brownian motion), the lower bound for the interval is set to zero and so :math:`\mathrm{xmax}` is required to be greater than zero. **var** : float The multiplicative factor :math:`\sigma^2` of the variogram :math:`\gamma \left(x\right)`. **icov1** : int Determines which of the preset variograms to use. The choices are given below. Note that :math:`x^{\prime } = \frac{\left\lvert x\right\rvert }{\ell }`, where :math:`\ell` is the correlation length and is a parameter for most of the variograms, and :math:`\sigma^2` is the variance specified by :math:`\mathrm{var}`. :math:`\mathrm{icov1} = 1` Symmetric stable variogram .. math:: \gamma \left(x\right) = \sigma^2\mathrm{exp}\left(-\left(x^{\prime }\right)^{\nu }\right)\text{,} where :math:`\ell = \mathrm{params}[0]`, :math:`\ell > 0`, :math:`\nu = \mathrm{params}[1]`, :math:`0\leq \nu \leq 2`. :math:`\mathrm{icov1} = 2` Cauchy variogram .. math:: \gamma \left(x\right) = \sigma^2\left(1+\left(x^{\prime }\right)^2\right)^{{-\nu }}\text{,} where :math:`\ell = \mathrm{params}[0]`, :math:`\ell > 0`, :math:`\nu = \mathrm{params}[1]`, :math:`\nu > 0`. :math:`\mathrm{icov1} = 3` Differential variogram with compact support .. math:: \gamma \left(x\right) = \left\{\begin{array}{cc} \sigma^2\left(1+8x^{\prime }+25\left(x^{\prime }\right)^2+32\left(x^{\prime }\right)^3\right)\left(1-x^{\prime }\right)^8\text{,} & x^{\prime } < 1\text{,} \\ 0\text{,} & x^{\prime }\geq 1\text{,} \end{array}\right. where :math:`\ell = \mathrm{params}[0]`, :math:`\ell > 0`. :math:`\mathrm{icov1} = 4` Exponential variogram .. math:: \gamma \left(x\right) = \sigma^2\mathrm{exp}\left(-x^{\prime }\right)\text{,} where :math:`\ell = \mathrm{params}[0]`, :math:`\ell > 0`. :math:`\mathrm{icov1} = 5` Gaussian variogram .. math:: \gamma \left(x\right) = \sigma^2\mathrm{exp}\left({-\left(x^{\prime }\right)}^2\right)\text{,} where :math:`\ell = \mathrm{params}[0]`, :math:`\ell > 0`. :math:`\mathrm{icov1} = 6` Nugget variogram .. math:: \gamma \left(x\right) = \left\{\begin{array}{cc} \sigma^2\text{,} & x = 0\text{,} \\ 0\text{,} & x\neq 0\text{.} \end{array}\right. No parameters need be set for this value of :math:`\mathrm{icov1}`. :math:`\mathrm{icov1} = 7` Spherical variogram .. math:: \gamma \left(x\right) = \left\{\begin{array}{cc} \sigma^2\left(1-1.5x^{\prime }+0.5\left(x^{\prime }\right)^3\right)\text{,} & x^{\prime } < 1\text{,} \\ 0\text{,} & x^{\prime }\geq 1\text{,} \end{array}\right. where :math:`\ell = \mathrm{params}[0]`, :math:`\ell > 0`. :math:`\mathrm{icov1} = 8` Bessel variogram .. math:: \gamma \left(x\right) = \sigma^2\frac{{2^{\nu }\Gamma \left(\nu +1\right)J_{\nu }\left(x^{\prime }\right)}}{\left(x^{\prime }\right)^{\nu }}\text{,} where :math:`J_{\nu }\left(·\right)` is the Bessel function of the first kind, :math:`\ell = \mathrm{params}[0]`, :math:`\ell > 0`, :math:`\nu = \mathrm{params}[1]`, :math:`\nu \geq {-0.5}`. :math:`\mathrm{icov1} = 9` Hole effect variogram .. math:: \gamma \left(x\right) = \sigma^2\frac{\sin\left(x^{\prime }\right)}{x^{\prime }}\text{,} where :math:`\ell = \mathrm{params}[0]`, :math:`\ell > 0`. :math:`\mathrm{icov1} = 10` Whittle-Matérn variogram .. math:: \gamma \left(x\right) = \sigma^2\frac{{2^{{1-\nu }}\left(x^{\prime }\right)^{\nu }K_{\nu }\left(x^{\prime }\right)}}{{\Gamma \left(\nu \right)}}\text{,} where :math:`K_{\nu }\left(·\right)` is the modified Bessel function of the second kind, :math:`\ell = \mathrm{params}[0]`, :math:`\ell > 0`, :math:`\nu = \mathrm{params}[1]`, :math:`\nu > 0`. :math:`\mathrm{icov1} = 11` Continuously parameterised variogram with compact support .. math:: \gamma \left(x\right) = \left\{\begin{array}{cc} \sigma^2\frac{{2^{{1-\nu }}\left(x^{\prime }\right)^{\nu }K_{\nu }\left(x^{\prime }\right)}}{{\Gamma \left(\nu \right)}}\left(1+8x^{{\prime \prime }}+25\left(x^{{\prime \prime }}\right)^2+32\left(x^{{\prime \prime }}\right)^3\right)\left(1-x^{{\prime \prime }}\right)^8\text{,} & x^{{\prime \prime }} < 1\text{,} \\ 0\text{,} & x^{{\prime \prime }}\geq 1\text{,} \end{array}\right. where :math:`x^{{\prime \prime }} = \frac{x^{\prime }}{s}`, :math:`K_{\nu }\left(·\right)` is the modified Bessel function of the second kind, :math:`\ell = \mathrm{params}[0]`, :math:`\ell > 0`, :math:`s = \mathrm{params}[1]`, :math:`s > 0` (second correlation length), :math:`\nu = \mathrm{params}[2]`, :math:`\nu > 0`. :math:`\mathrm{icov1} = 12` Generalized hyperbolic distribution variogram .. math:: \gamma \left(x\right) = \sigma^2\frac{\left(\delta^2+\left(x^{\prime }\right)^2\right)^{\frac{\lambda }{2}}}{{\delta^{\lambda }K_{\lambda }\left(\kappa \delta \right)}}K_{\lambda }\left(\kappa \left(\delta^2+\left(x^{\prime }\right)^2\right)^{\frac{1}{2}}\right)\text{,} where :math:`K_{\lambda }\left(·\right)` is the modified Bessel function of the second kind, :math:`\ell = \mathrm{params}[0]`, :math:`\ell > 0`, :math:`\lambda = \mathrm{params}[1]`, no constraint on :math:`\lambda` :math:`\delta = \mathrm{params}[2]`, :math:`\delta > 0`, :math:`\kappa = \mathrm{params}[3]`, :math:`\kappa > 0`. :math:`\mathrm{icov1} = 13` Cosine variogram .. math:: \gamma \left(x\right) = \sigma^2\cos\left(x^{\prime }\right)\text{,} where :math:`\ell = \mathrm{params}[0]`, :math:`\ell > 0`. :math:`\mathrm{icov1} = 14` Used for simulating fractional Brownian motion :math:`B^H\left(t\right)`. Fractional Brownian motion itself is not a stationary Gaussian random field, but its increments :math:`\tilde{X}\left(i\right) = B^H\left(t_i\right)-B^H\left(t_{{i-1}}\right)` can be simulated in the same way as a stationary random field. The variogram for the so-called 'increment process' is .. math:: C\left(\tilde{X}\left(t_i\right),\tilde{X}\left(t_j\right)\right) = \tilde{\gamma }\left(x\right) = \frac{\delta^{{2H}}}{2}\left(\left\lvert \frac{x}{\delta }-1\right\rvert^{{2H}}+\left\lvert \frac{x}{\delta }+1\right\rvert^{{2H}}-2\left\lvert \frac{x}{\delta }\right\rvert^{{2H}}\right)\text{,} where :math:`x = t_j-t_i`, :math:`H = \mathrm{params}[0]`, :math:`0 < H < 1`, :math:`H` is the Hurst parameter, :math:`\delta = \mathrm{params}[1]`, :math:`\delta > 0`, normally :math:`\delta = t_i-t_{{i-1}}` is the (fixed) step size. We scale the increments to set :math:`\gamma \left(0\right) = 1`; let :math:`X\left(i\right) = \frac{{\tilde{X}\left(i\right)}}{\delta^{{-H}}}`, then .. math:: C\left(X\left(t_i\right),X\left(t_j\right)\right) = \gamma \left(x\right) = \frac{1}{2}\left(\left\lvert \frac{x}{\delta }-1\right\rvert^{{2H}}+\left\lvert \frac{x}{\delta }+1\right\rvert^{{2H}}-2\left\lvert \frac{x}{\delta }\right\rvert^{{2H}}\right)\text{.} The increments :math:`X\left(i\right)` can then be simulated using :meth:`field_1d_generate`, then multiplied by :math:`\delta^H` to obtain the original increments :math:`\tilde{X}\left(i\right)` for the fractional Brownian motion. **params** : float, array-like, shape :math:`\left(\textit{np}\right)` The parameters set for the variogram. **maxm** : None or int, optional Note: if this argument is **None** then a default value will be used, determined as follows: :math:`2^{{3 + \mathrm{ceiling}\left(\log_2\left(\left(\mathrm{ns}-1\right) \right)\right) }}`. The maximum size of the circulant matrix to use. For example, if the embedding matrix is to be allowed to double in size three times before the approximation procedure is used, then choose :math:`\mathrm{maxm} = 2^{{k+2}}` where :math:`k = 1+\left\lceil \mathrm{log2}\left(\mathrm{ns}-1\right)\right\rceil`. **pad** : int, optional Determines whether the embedding matrix is padded with zeros, or padded with values of the variogram. The choice of padding may affect how big the embedding matrix must be in order to be positive semidefinite. :math:`\mathrm{pad} = 0` The embedding matrix is padded with zeros. :math:`\mathrm{pad} = 1` The embedding matrix is padded with values of the variogram. **icorr** : int, optional Determines which approximation to implement if required, as described in :ref:`Notes <g05zn-py2-py-notes>`. **Returns** **lam** : float, ndarray, shape :math:`\left(\mathrm{maxm}\right)` Contains the square roots of the eigenvalues of the embedding matrix. **xx** : float, ndarray, shape :math:`\left(\mathrm{ns}\right)` The points at which values of the random field will be output. **m** : int The size of the embedding matrix. **approx** : int Indicates whether approximation was used. :math:`\mathrm{approx} = 0` No approximation was used. :math:`\mathrm{approx} = 1` Approximation was used. **rho** : float Indicates the scaling of the covariance matrix. :math:`\mathrm{rho} = 1.0` unless approximation was used with :math:`\mathrm{icorr} = 0` or :math:`1`. **icount** : int Indicates the number of negative eigenvalues in the embedding matrix which have had to be set to zero. **eig** : float, ndarray, shape :math:`\left(3\right)` Indicates information about the negative eigenvalues in the embedding matrix which have had to be set to zero. :math:`\mathrm{eig}[0]` contains the smallest eigenvalue, :math:`\mathrm{eig}[1]` contains the sum of the squares of the negative eigenvalues, and :math:`\mathrm{eig}[2]` contains the sum of the absolute values of the negative eigenvalues. .. _g05zn-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{ns} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{ns}\geq 1`. (`errno` :math:`2`) On entry, :math:`\mathrm{icov1} \neq 14`, :math:`\mathrm{xmin} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{xmax} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{xmin} < \mathrm{xmax}`. (`errno` :math:`3`) On entry, :math:`\mathrm{icov1} = 14` and :math:`\mathrm{xmax} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{xmax} > 0.0`. (`errno` :math:`4`) On entry, :math:`\mathrm{maxm} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: the minimum calculated value for :math:`\mathrm{maxm}` is :math:`\langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`5`) On entry, :math:`\mathrm{var} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{var}\geq 0.0`. (`errno` :math:`6`) On entry, :math:`\mathrm{icov1} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{icov1}\geq 1` and :math:`\mathrm{icov1}\leq 14`. (`errno` :math:`7`) On entry, :math:`\textit{np} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: for :math:`\mathrm{icov1} = \langle\mathit{\boldsymbol{value}}\rangle`, :math:`\textit{np} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`8`) On entry, :math:`\mathrm{params}[\langle\mathit{\boldsymbol{value}}\rangle] = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: dependent on :math:`\mathrm{icov1}`. (`errno` :math:`9`) On entry, :math:`\mathrm{pad} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{pad} = 0` or :math:`1`. (`errno` :math:`10`) On entry, :math:`\mathrm{icorr} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{icorr} = 0`, :math:`1` or :math:`2`. .. _g05zn-py2-py-notes: **Notes** A one-dimensional random field :math:`Z\left(x\right)` in :math:`\mathbb{R}` is a function which is random at every point :math:`x \in \mathbb{R}`, so :math:`Z\left(x\right)` is a random variable for each :math:`x`. The random field has a mean function :math:`\mu \left(x\right) = 𝔼\left[Z\left(x\right)\right]` and a symmetric positive semidefinite covariance function :math:`C\left(x, y\right) = 𝔼\left[\left(Z\left(x\right)-\mu \left(x\right)\right)\left(Z\left(y\right)-\mu \left(y\right)\right)\right]`. :math:`Z\left(x\right)` is a Gaussian random field if for any choice of :math:`n \in ℕ` and :math:`x_1,\ldots,x_n \in \mathbb{R}`, the random vector :math:`\left[Z\left(x_1\right),\ldots,Z\left(x_n\right)\right]^\mathrm{T}` follows a multivariate Normal distribution, which would have a mean vector :math:`\tilde{\mu }` with entries :math:`\tilde{\mu }_i = \mu \left(x_i\right)` and a covariance matrix :math:`\tilde{C}` with entries :math:`\tilde{C}_{{ij}} = C\left(x_i, x_j\right)`. A Gaussian random field :math:`Z\left(x\right)` is stationary if :math:`\mu \left(x\right)` is constant for all :math:`x \in \mathbb{R}` and :math:`C\left(x, y\right) = C\left({x+a}, {y+a}\right)` for all :math:`\left. x, y, a\right. \in \mathbb{R}` and hence we can express the covariance function :math:`C\left(x, y\right)` as a function :math:`\gamma` of one variable: :math:`C\left(x, y\right) = \gamma \left(x-y\right)`. :math:`\gamma` is known as a variogram (or more correctly, a semivariogram) and includes the multiplicative factor :math:`\sigma^2` representing the variance such that :math:`\gamma \left(0\right) = \sigma^2`. The functions ``field_1d_predef_setup`` and :meth:`field_1d_generate` are used to simulate a one-dimensional stationary Gaussian random field, with mean function zero and variogram :math:`\gamma \left(x\right)`, over an interval :math:`\left[x_{\textit{min}}, x_{\textit{max}}\right]`, using an equally spaced set of :math:`N` points. The problem reduces to sampling a Normal random vector :math:`\mathbf{X}` of size :math:`N`, with mean vector zero and a symmetric Toeplitz covariance matrix :math:`A`. Since :math:`A` is in general expensive to factorize, a technique known as the `circulant embedding method` is used. :math:`A` is embedded into a larger, symmetric circulant matrix :math:`B` of size :math:`M\geq 2\left(N-1\right)`, which can now be factorized as :math:`B = W\Lambda W^* = R^*R`, where :math:`W` is the Fourier matrix (:math:`W^*` is the complex conjugate of :math:`W`), :math:`\Lambda` is the diagonal matrix containing the eigenvalues of :math:`B` and :math:`R = \Lambda^{\frac{1}{2}}W^*`. :math:`B` is known as the embedding matrix. The eigenvalues can be calculated by performing a discrete Fourier transform of the first row (or column) of :math:`B` and multiplying by :math:`M`, and so only the first row (or column) of :math:`B` is needed -- the whole matrix does not need to be formed. As long as all of the values of :math:`\Lambda` are non-negative (i.e., :math:`B` is positive semidefinite), :math:`B` is a covariance matrix for a random vector :math:`\mathbf{Y}`, two samples of which can now be simulated from the real and imaginary parts of :math:`R^*\left(\mathbf{U}+i\mathbf{V}\right)`, where :math:`\mathbf{U}` and :math:`\mathbf{V}` have elements from the standard Normal distribution. Since :math:`R^*\left(\mathbf{U}+i\mathbf{V}\right) = W\Lambda^{\frac{1}{2}}\left(\mathbf{U}+i\mathbf{V}\right)`, this calculation can be done using a discrete Fourier transform of the vector :math:`\Lambda^{\frac{1}{2}}\left(\mathbf{U}+i\mathbf{V}\right)`. Two samples of the random vector :math:`\mathbf{X}` can now be recovered by taking the first :math:`N` elements of each sample of :math:`\mathbf{Y}` -- because the original covariance matrix :math:`A` is embedded in :math:`B`, :math:`\mathbf{X}` will have the correct distribution. If :math:`B` is not positive semidefinite, larger embedding matrices :math:`B` can be tried; however if the size of the matrix would have to be larger than :math:`\mathrm{maxm}`, an approximation procedure is used. We write :math:`\Lambda = \Lambda_++\Lambda_-`, where :math:`\Lambda_+` and :math:`\Lambda_-` contain the non-negative and negative eigenvalues of :math:`B` respectively. Then :math:`B` is replaced by :math:`\rho B_+` where :math:`B_+ = W\Lambda_+W^*` and :math:`\rho \in \left(0, 1\right]` is a scaling factor. The error :math:`\epsilon` in approximating the distribution of the random field is given by .. math:: \epsilon = \sqrt{\frac{{\left(1-\rho \right)^2\mathrm{trace}\left(\Lambda \right)+\rho^2\mathrm{trace}\left(\Lambda_-\right)}}{M}}\text{.} Three choices for :math:`\rho` are available, and are determined by the input argument :math:`\mathrm{icorr}`: setting :math:`\mathrm{icorr} = 0` sets .. math:: \rho = \frac{\mathrm{trace}\left(\Lambda \right)}{\mathrm{trace}\left(\Lambda_+\right)}\text{,} setting :math:`\mathrm{icorr} = 1` sets .. math:: \rho = \sqrt{\frac{\mathrm{trace}\left(\Lambda \right)}{\mathrm{trace}\left(\Lambda_+\right)}}\text{,} setting :math:`\mathrm{icorr} = 2` sets :math:`\rho = 1`. ``field_1d_predef_setup`` finds a suitable positive semidefinite embedding matrix :math:`B` and outputs its size, :math:`\mathrm{m}`, and the square roots of its eigenvalues in :math:`\mathrm{lam}`. If approximation is used, information regarding the accuracy of the approximation is output. Note that only the first row (or column) of :math:`B` is actually formed and stored. .. _g05zn-py2-py-references: **References** Dietrich, C R and Newsam, G N, 1997, `Fast and exact simulation of stationary Gaussian processes through circulant embedding of the covariance matrix`, SIAM J. Sci. Comput. (18), 1088--1107 Schlather, M, 1999, `Introduction to positive definite functions and to unconditional simulation of random fields`, Technical Report ST 99--10, Lancaster University Wood, A T A and Chan, G, 1997, `Algorithm AS 312: An Algorithm for Simulating Stationary Gaussian Random Fields`, Journal of the Royal Statistical Society, Series C (Applied Statistics) (Volume 46) (1), 171--181 """ raise NotImplementedError
[docs]def field_1d_generate(ns, s, lam, rho, statecomm): r""" ``field_1d_generate`` produces realizations of a stationary Gaussian random field in one dimension, using the circulant embedding method. The square roots of the eigenvalues of the extended covariance matrix (or embedding matrix) need to be input, and can be calculated using :meth:`field_1d_user_setup` or :meth:`field_1d_predef_setup`. .. _g05zp-py2-py-doc: For full information please refer to the NAG Library document for g05zp https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05zpf.html .. _g05zp-py2-py-parameters: **Parameters** **ns** : int The number of sample points to be generated in realizations of the random field. This must be the same value as supplied to :meth:`field_1d_predef_setup` or :meth:`field_1d_user_setup` when calculating the eigenvalues of the embedding matrix. **s** : int :math:`S`, the number of realizations of the random field to simulate. **lam** : float, array-like, shape :math:`\left(m\right)` Must contain the square roots of the eigenvalues of the embedding matrix, as returned by :meth:`field_1d_predef_setup` or :meth:`field_1d_user_setup`. **rho** : float Indicates the scaling of the covariance matrix, as returned by :meth:`field_1d_predef_setup` or :meth:`field_1d_user_setup`. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **z** : float, ndarray, shape :math:`\left(\mathrm{ns}, \mathrm{s}\right)` Contains the realizations of the random field. The :math:`j`\ th realization, for the :math:`\mathrm{ns}` sample points, is stored in :math:`\mathrm{z}[i-1,j-1]`, for :math:`i = 1,2,\ldots,\mathrm{ns}`. The sample points are as returned in :math:`{\textit{xx}}` by :meth:`field_1d_predef_setup` or :meth:`field_1d_user_setup`. .. _g05zp-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{ns} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{ns}\geq 1`. (`errno` :math:`2`) On entry, :math:`\mathrm{s} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{s}\geq 1`. (`errno` :math:`3`) On entry, :math:`m = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{ns} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`m\geq \mathrm{max}\left(1, {2\times \left(\mathrm{ns}-1\right)}\right)`. (`errno` :math:`4`) On entry, at least one element of :math:`\mathrm{lam}` was negative. Constraint: all elements of :math:`\mathrm{lam}` must be non-negative. (`errno` :math:`5`) On entry, :math:`\mathrm{rho} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`0.0\leq \mathrm{rho}\leq 1.0`. (`errno` :math:`6`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05zp-py2-py-notes: **Notes** A one-dimensional random field :math:`Z\left(x\right)` in :math:`\mathbb{R}` is a function which is random at every point :math:`x \in \mathbb{R}`, so :math:`Z\left(x\right)` is a random variable for each :math:`x`. The random field has a mean function :math:`\mu \left(x\right) = 𝔼\left[Z\left(x\right)\right]` and a symmetric non-negative definite covariance function :math:`C\left(x, y\right) = 𝔼\left[\left(Z\left(x\right)-\mu \left(x\right)\right)\left(Z\left(y\right)-\mu \left(y\right)\right)\right]`. :math:`Z\left(x\right)` is a Gaussian random field if for any choice of :math:`n \in ℕ` and :math:`x_1,\ldots,x_n \in \mathbb{R}`, the random vector :math:`\left[Z\left(x_1\right),\ldots,Z\left(x_n\right)\right]^\mathrm{T}` follows a multivariate Normal distribution, which would have a mean vector :math:`\tilde{\mu }` with entries :math:`\tilde{\mu }_i = \mu \left(x_i\right)` and a covariance matrix :math:`\tilde{C}` with entries :math:`\tilde{C}_{{ij}} = C\left(x_i, x_j\right)`. A Gaussian random field :math:`Z\left(x\right)` is stationary if :math:`\mu \left(x\right)` is constant for all :math:`x \in \mathbb{R}` and :math:`C\left(x, y\right) = C\left({x+a}, {y+a}\right)` for all :math:`\left. x, y, a\right. \in \mathbb{R}` and hence we can express the covariance function :math:`C\left(x, y\right)` as a function :math:`\gamma` of one variable: :math:`C\left(x, y\right) = \gamma \left(x-y\right)`. :math:`\gamma` is known as a variogram (or more correctly, a semivariogram) and includes the multiplicative factor :math:`\sigma^2` representing the variance such that :math:`\gamma \left(0\right) = \sigma^2`. The functions :meth:`field_1d_user_setup` or :meth:`field_1d_predef_setup`, along with ``field_1d_generate``, are used to simulate a one-dimensional stationary Gaussian random field, with mean function zero and variogram :math:`\gamma \left(x\right)`, over an interval :math:`\left[x_{\textit{min}}, x_{\textit{max}}\right]`, using an equally spaced set of :math:`N` points. The problem reduces to sampling a Normal random vector :math:`\mathbf{X}` of size :math:`N`, with mean vector zero and a symmetric Toeplitz covariance matrix :math:`A`. Since :math:`A` is in general expensive to factorize, a technique known as the `circulant embedding method` is used. :math:`A` is embedded into a larger, symmetric circulant matrix :math:`B` of size :math:`M\geq 2\left(N-1\right)`, which can now be factorized as :math:`B = W\Lambda W^* = R^*R`, where :math:`W` is the Fourier matrix (:math:`W^*` is the complex conjugate of :math:`W`), :math:`\Lambda` is the diagonal matrix containing the eigenvalues of :math:`B` and :math:`R = \Lambda^{\frac{1}{2}}W^*`. :math:`B` is known as the embedding matrix. The eigenvalues can be calculated by performing a discrete Fourier transform of the first row (or column) of :math:`B` and multiplying by :math:`M`, and so only the first row (or column) of :math:`B` is needed -- the whole matrix does not need to be formed. As long as all of the values of :math:`\Lambda` are non-negative (i.e., :math:`B` is non-negative definite), :math:`B` is a covariance matrix for a random vector :math:`\mathbf{Y}`, two samples of which can now be simulated from the real and imaginary parts of :math:`R^*\left(\mathbf{U}+i\mathbf{V}\right)`, where :math:`\mathbf{U}` and :math:`\mathbf{V}` have elements from the standard Normal distribution. Since :math:`R^*\left(\mathbf{U}+i\mathbf{V}\right) = W\Lambda^{\frac{1}{2}}\left(\mathbf{U}+i\mathbf{V}\right)`, this calculation can be done using a discrete Fourier transform of the vector :math:`\Lambda^{\frac{1}{2}}\left(\mathbf{U}+i\mathbf{V}\right)`. Two samples of the random vector :math:`\mathbf{X}` can now be recovered by taking the first :math:`N` elements of each sample of :math:`\mathbf{Y}` -- because the original covariance matrix :math:`A` is embedded in :math:`B`, :math:`\mathbf{X}` will have the correct distribution. If :math:`B` is not non-negative definite, larger embedding matrices :math:`B` can be tried; however if the size of the matrix would have to be larger than :math:`\textit{maxm}`, an approximation procedure is used. See the documentation of :meth:`field_1d_user_setup` or :meth:`field_1d_predef_setup` for details of the approximation procedure. ``field_1d_generate`` takes the square roots of the eigenvalues of the embedding matrix :math:`B`, and its size :math:`M`, as input and outputs :math:`S` realizations of the random field in :math:`Z`. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``field_1d_generate``. .. _g05zp-py2-py-references: **References** Dietrich, C R and Newsam, G N, 1997, `Fast and exact simulation of stationary Gaussian processes through circulant embedding of the covariance matrix`, SIAM J. Sci. Comput. (18), 1088--1107 Schlather, M, 1999, `Introduction to positive definite functions and to unconditional simulation of random fields`, Technical Report ST 99--10, Lancaster University Wood, A T A and Chan, G, 1994, `Simulation of stationary Gaussian processes in` :math:`\left[0, 1\right]^d`, Journal of Computational and Graphical Statistics (3(4)), 409--432 """ raise NotImplementedError
[docs]def field_2d_user_setup(ns, xmin, xmax, ymin, ymax, maxm, var, cov2, even, pad=1, icorr=0, data=None): r""" ``field_2d_user_setup`` performs the setup required in order to simulate stationary Gaussian random fields in two dimensions, for a user-defined variogram, using the `circulant embedding method`. Specifically, the eigenvalues of the extended covariance matrix (or embedding matrix) are calculated, and their square roots output, for use by :meth:`field_2d_generate`, which simulates the random field. .. _g05zq-py2-py-doc: For full information please refer to the NAG Library document for g05zq https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05zqf.html .. _g05zq-py2-py-parameters: **Parameters** **ns** : int, array-like, shape :math:`\left(2\right)` The number of sample points to use in each direction, with :math:`\mathrm{ns}[0]` sample points in the :math:`x`-direction, :math:`N_1` and :math:`\mathrm{ns}[1]` sample points in the :math:`y`-direction, :math:`N_2`. The total number of sample points on the grid is, therefore, :math:`\mathrm{ns}[0]\times \mathrm{ns}[1]`. **xmin** : float The lower bound for the :math:`x`-coordinate, for the region in which the random field is to be simulated. **xmax** : float The upper bound for the :math:`x`-coordinate, for the region in which the random field is to be simulated. **ymin** : float The lower bound for the :math:`y`-coordinate, for the region in which the random field is to be simulated. **ymax** : float The upper bound for the :math:`y`-coordinate, for the region in which the random field is to be simulated. **maxm** : int, array-like, shape :math:`\left(2\right)` Determines the maximum size of the circulant matrix to use -- a maximum of :math:`\mathrm{maxm}[0]` elements in the :math:`x`-direction, and a maximum of :math:`\mathrm{maxm}[1]` elements in the :math:`y`-direction. The maximum size of the circulant matrix is thus :math:`\mathrm{maxm}[0]`:math:`\times`:math:`\mathrm{maxm}[1]`. **var** : float The multiplicative factor :math:`\sigma^2` of the variogram :math:`\gamma \left(\mathbf{x}\right)`. **cov2** : callable gamma = cov2(x, y, data=None) :math:`\mathrm{cov2}` must evaluate the variogram :math:`\gamma \left(\mathbf{x}\right)` for all :math:`\mathbf{x}` if :math:`\mathrm{even} = 0`, and for all :math:`\mathbf{x}` with non-negative entries if :math:`\mathrm{even} = 1`. The value returned in :math:`\mathrm{gamma}` is multiplied internally by :math:`\mathrm{var}`. **Parameters** **x** : float The coordinate :math:`x` at which the variogram :math:`\gamma \left(\mathbf{x}\right)` is to be evaluated. **y** : float The coordinate :math:`y` at which the variogram :math:`\gamma \left(\mathbf{x}\right)` is to be evaluated. **data** : arbitrary, optional, modifiable in place User-communication data for callback functions. **Returns** **gamma** : float The value of the variogram :math:`\gamma \left(\mathbf{x}\right)`. **even** : int Indicates whether the covariance function supplied is even or uneven. :math:`\mathrm{even} = 0` The covariance function is uneven. :math:`\mathrm{even} = 1` The covariance function is even. **pad** : int, optional Determines whether the embedding matrix is padded with zeros, or padded with values of the variogram. The choice of padding may affect how big the embedding matrix must be in order to be positive semidefinite. :math:`\mathrm{pad} = 0` The embedding matrix is padded with zeros. :math:`\mathrm{pad} = 1` The embedding matrix is padded with values of the variogram. **icorr** : int, optional Determines which approximation to implement if required, as described in :ref:`Notes <g05zq-py2-py-notes>`. **data** : arbitrary, optional User-communication data for callback functions. **Returns** **lam** : float, ndarray, shape :math:`\left(:\right)` Contains the square roots of the eigenvalues of the embedding matrix. **xx** : float, ndarray, shape :math:`\left(:\right)` The points of the :math:`x`-coordinates at which values of the random field will be output. **yy** : float, ndarray, shape :math:`\left(:\right)` The points of the :math:`y`-coordinates at which values of the random field will be output. **m** : int, ndarray, shape :math:`\left(2\right)` :math:`\mathrm{m}[0]` contains :math:`M_1`, the size of the circulant blocks and :math:`\mathrm{m}[1]` contains :math:`M_2`, the number of blocks, resulting in a final square matrix of size :math:`M_1\times M_2`. **approx** : int Indicates whether approximation was used. :math:`\mathrm{approx} = 0` No approximation was used. :math:`\mathrm{approx} = 1` Approximation was used. **rho** : float Indicates the scaling of the covariance matrix. :math:`\mathrm{rho} = 1.0` unless approximation was used with :math:`\mathrm{icorr} = 0` or :math:`1`. **icount** : int Indicates the number of negative eigenvalues in the embedding matrix which have had to be set to zero. **eig** : float, ndarray, shape :math:`\left(3\right)` Indicates information about the negative eigenvalues in the embedding matrix which have had to be set to zero. :math:`\mathrm{eig}[0]` contains the smallest eigenvalue, :math:`\mathrm{eig}[1]` contains the sum of the squares of the negative eigenvalues, and :math:`\mathrm{eig}[2]` contains the sum of the absolute values of the negative eigenvalues. .. _g05zq-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{ns} = \left[\langle\mathit{\boldsymbol{value}}\rangle, \langle\mathit{\boldsymbol{value}}\rangle\right]`. Constraint: :math:`\mathrm{ns}[0]\geq 1`, :math:`\mathrm{ns}[1]\geq 1`. (`errno` :math:`2`) On entry, :math:`\mathrm{xmin} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{xmax} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{xmin} < \mathrm{xmax}`. (`errno` :math:`4`) On entry, :math:`\mathrm{ymin} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{ymax} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{ymin} < \mathrm{ymax}`. (`errno` :math:`6`) On entry, :math:`\mathrm{maxm} = \left[\langle\mathit{\boldsymbol{value}}\rangle, \langle\mathit{\boldsymbol{value}}\rangle\right]`. Constraint: the minima for :math:`\mathrm{maxm}` are :math:`\left[\langle\mathit{\boldsymbol{value}}\rangle, \langle\mathit{\boldsymbol{value}}\rangle\right]`. (`errno` :math:`7`) On entry, :math:`\mathrm{var} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{var}\geq 0.0`. (`errno` :math:`9`) On entry, :math:`\mathrm{even} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{even} = 0` or :math:`1`. (`errno` :math:`10`) On entry, :math:`\mathrm{pad} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{pad} = 0` or :math:`1`. (`errno` :math:`11`) On entry, :math:`\mathrm{icorr} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{icorr} = 0`, :math:`1` or :math:`2`. .. _g05zq-py2-py-notes: **Notes** A two-dimensional random field :math:`Z\left(\mathbf{x}\right)` in :math:`\mathbb{R}^2` is a function which is random at every point :math:`\mathbf{x} \in \mathbb{R}^2`, so :math:`Z\left(\mathbf{x}\right)` is a random variable for each :math:`\mathbf{x}`. The random field has a mean function :math:`\mu \left(\mathbf{x}\right) = 𝔼\left[Z\left(\mathbf{x}\right)\right]` and a symmetric positive semidefinite covariance function :math:`C\left(\mathbf{x}, \mathbf{y}\right) = 𝔼\left[\left(Z\left(\mathbf{x}\right)-\mu \left(\mathbf{x}\right)\right)\left(Z\left(\mathbf{y}\right)-\mu \left(\mathbf{y}\right)\right)\right]`. :math:`Z\left(\mathbf{x}\right)` is a Gaussian random field if for any choice of :math:`n \in ℕ` and :math:`\mathbf{x}_1,\ldots,\mathbf{x}_n \in \mathbb{R}^2`, the random vector :math:`\left[Z\left(\mathbf{x}_1\right),\ldots,Z\left(\mathbf{x}_n\right)\right]^\mathrm{T}` follows a multivariate Normal distribution, which would have a mean vector :math:`\tilde{\mu }` with entries :math:`\tilde{\mu }_i = \mu \left(\mathbf{x}_i\right)` and a covariance matrix :math:`\tilde{C}` with entries :math:`\tilde{C}_{{ij}} = C\left(\mathbf{x}_i, \mathbf{x}_j\right)`. A Gaussian random field :math:`Z\left(\mathbf{x}\right)` is stationary if :math:`\mu \left(\mathbf{x}\right)` is constant for all :math:`\mathbf{x} \in \mathbb{R}^2` and :math:`C\left(\mathbf{x}, \mathbf{y}\right) = C\left({\mathbf{x}+\mathbf{a}}, {\mathbf{y}+\mathbf{a}}\right)` for all :math:`\left. \mathbf{x}, \mathbf{y}, \mathbf{a}\right. \in \mathbb{R}^2` and hence we can express the covariance function :math:`C\left(\mathbf{x}, \mathbf{y}\right)` as a function :math:`\gamma` of one variable: :math:`C\left(\mathbf{x}, \mathbf{y}\right) = \gamma \left(\mathbf{x}-\mathbf{y}\right)`. :math:`\gamma` is known as a variogram (or more correctly, a semivariogram) and includes the multiplicative factor :math:`\sigma^2` representing the variance such that :math:`\gamma \left(0\right) = \sigma^2`. The functions ``field_2d_user_setup`` and :meth:`field_2d_generate` are used to simulate a two-dimensional stationary Gaussian random field, with mean function zero and variogram :math:`\gamma \left(\mathbf{x}\right)`, over a domain :math:`\left[x_{\textit{min}}, x_{\textit{max}}\right]\times \left[y_{\textit{min}}, y_{\textit{max}}\right]`, using an equally spaced set of :math:`N_1\times N_2` points; :math:`N_1` points in the :math:`x`-direction and :math:`N_2` points in the :math:`y`-direction. The problem reduces to sampling a Normal random vector :math:`\mathbf{X}` of size :math:`N_1\times N_2`, with mean vector zero and a symmetric covariance matrix :math:`A`, which is an :math:`N_2\times N_2` block Toeplitz matrix with Toeplitz blocks of size :math:`N_1\times N_1`. Since :math:`A` is in general expensive to factorize, a technique known as the `circulant embedding method` is used. :math:`A` is embedded into a larger, symmetric matrix :math:`B`, which is an :math:`M_2\times M_2` block circulant matrix with circulant blocks of size :math:`M_1\times M_1`, where :math:`M_1\geq 2\left(N_1-1\right)` and :math:`M_2\geq 2\left(N_2-1\right)`. :math:`B` can now be factorized as :math:`B = W\Lambda W^* = R^*R`, where :math:`W` is the two-dimensional Fourier matrix (:math:`W^*` is the complex conjugate of :math:`W`), :math:`\Lambda` is the diagonal matrix containing the eigenvalues of :math:`B` and :math:`R = \Lambda^{\frac{1}{2}}W^*`. :math:`B` is known as the embedding matrix. The eigenvalues can be calculated by performing a discrete Fourier transform of the first row (or column) of :math:`B` and multiplying by :math:`M_1\times M_2`, and so only the first row (or column) of :math:`B` is needed -- the whole matrix does not need to be formed. The symmetry of :math:`A` as a block matrix, and the symmetry of each block of :math:`A`, depends on whether the variogram :math:`\gamma` is even or not. :math:`\gamma` is even in its first coordinate if :math:`\gamma \left(\left[{-x}_1, x_2\right]^\mathrm{T}\right) = \gamma \left(\left[x_1, x_2\right]^\mathrm{T}\right)`, even in its second coordinate if :math:`\gamma \left(\left[x_1, {-x}_2\right]^\mathrm{T}\right) = \gamma \left(\left[x_1, x_2\right]^\mathrm{T}\right)`, and even if it is even in both coordinates (in two dimensions it is impossible for :math:`\gamma` to be even in one coordinate and uneven in the other). If :math:`\gamma` is even then :math:`A` is a symmetric block matrix and has symmetric blocks; if :math:`\gamma` is uneven then :math:`A` is not a symmetric block matrix and has non-symmetric blocks. In the uneven case, :math:`M_1` and :math:`M_2` are set to be odd in order to guarantee symmetry in :math:`B`. As long as all of the values of :math:`\Lambda` are non-negative (i.e., :math:`B` is positive semidefinite), :math:`B` is a covariance matrix for a random vector :math:`\mathbf{Y}` which has :math:`M_2` blocks of size :math:`M_1`. Two samples of :math:`\mathbf{Y}` can now be simulated from the real and imaginary parts of :math:`R^*\left(\mathbf{U}+i\mathbf{V}\right)`, where :math:`\mathbf{U}` and :math:`\mathbf{V}` have elements from the standard Normal distribution. Since :math:`R^*\left(\mathbf{U}+i\mathbf{V}\right) = W\Lambda^{\frac{1}{2}}\left(\mathbf{U}+i\mathbf{V}\right)`, this calculation can be done using a discrete Fourier transform of the vector :math:`\Lambda^{\frac{1}{2}}\left(\mathbf{U}+i\mathbf{V}\right)`. Two samples of the random vector :math:`\mathbf{X}` can now be recovered by taking the first :math:`N_1` elements of the first :math:`N_2` blocks of each sample of :math:`\mathbf{Y}` -- because the original covariance matrix :math:`A` is embedded in :math:`B`, :math:`\mathbf{X}` will have the correct distribution. If :math:`B` is not positive semidefinite, larger embedding matrices :math:`B` can be tried; however if the size of the matrix would have to be larger than :math:`\mathrm{maxm}`, an approximation procedure is used. We write :math:`\Lambda = \Lambda_++\Lambda_-`, where :math:`\Lambda_+` and :math:`\Lambda_-` contain the non-negative and negative eigenvalues of :math:`B` respectively. Then :math:`B` is replaced by :math:`\rho B_+` where :math:`B_+ = W\Lambda_+W^*` and :math:`\rho \in \left(0, 1\right]` is a scaling factor. The error :math:`\epsilon` in approximating the distribution of the random field is given by .. math:: \epsilon = \sqrt{\frac{{\left(1-\rho \right)^2\mathrm{trace}\left(\Lambda \right)+\rho^2\mathrm{trace}\left(\Lambda_-\right)}}{M}}\text{.} Three choices for :math:`\rho` are available, and are determined by the input argument :math:`\mathrm{icorr}`: setting :math:`\mathrm{icorr} = 0` sets .. math:: \rho = \frac{\mathrm{trace}\left(\Lambda \right)}{\mathrm{trace}\left(\Lambda_+\right)}\text{,} setting :math:`\mathrm{icorr} = 1` sets .. math:: \rho = \sqrt{\frac{\mathrm{trace}\left(\Lambda \right)}{\mathrm{trace}\left(\Lambda_+\right)}}\text{,} setting :math:`\mathrm{icorr} = 2` sets :math:`\rho = 1`. ``field_2d_user_setup`` finds a suitable positive semidefinite embedding matrix :math:`B` and outputs its sizes in the vector :math:`\mathrm{m}` and the square roots of its eigenvalues in :math:`\mathrm{lam}`. If approximation is used, information regarding the accuracy of the approximation is output. Note that only the first row (or column) of :math:`B` is actually formed and stored. .. _g05zq-py2-py-references: **References** Dietrich, C R and Newsam, G N, 1997, `Fast and exact simulation of stationary Gaussian processes through circulant embedding of the covariance matrix`, SIAM J. Sci. Comput. (18), 1088--1107 Schlather, M, 1999, `Introduction to positive definite functions and to unconditional simulation of random fields`, Technical Report ST 99--10, Lancaster University Wood, A T A and Chan, G, 1994, `Simulation of stationary Gaussian processes in` :math:`\left[0, 1\right]^d`, Journal of Computational and Graphical Statistics (3(4)), 409--432 """ raise NotImplementedError
[docs]def field_2d_predef_setup(ns, xmin, xmax, ymin, ymax, maxm, var, icov2, params, norm=2, pad=1, icorr=0): r""" ``field_2d_predef_setup`` performs the setup required in order to simulate stationary Gaussian random fields in two dimensions, for a preset variogram, using the `circulant embedding method`. Specifically, the eigenvalues of the extended covariance matrix (or embedding matrix) are calculated, and their square roots output, for use by :meth:`field_2d_generate`, which simulates the random field. .. _g05zr-py2-py-doc: For full information please refer to the NAG Library document for g05zr https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05zrf.html .. _g05zr-py2-py-parameters: **Parameters** **ns** : int, array-like, shape :math:`\left(2\right)` The number of sample points to use in each direction, with :math:`\mathrm{ns}[0]` sample points in the :math:`x`-direction, :math:`N_1` and :math:`\mathrm{ns}[1]` sample points in the :math:`y`-direction, :math:`N_2`. The total number of sample points on the grid is, therefore, :math:`\mathrm{ns}[0]\times \mathrm{ns}[1]`. **xmin** : float The lower bound for the :math:`x`-coordinate, for the region in which the random field is to be simulated. **xmax** : float The upper bound for the :math:`x`-coordinate, for the region in which the random field is to be simulated. **ymin** : float The lower bound for the :math:`y`-coordinate, for the region in which the random field is to be simulated. **ymax** : float The upper bound for the :math:`y`-coordinate, for the region in which the random field is to be simulated. **maxm** : int, array-like, shape :math:`\left(2\right)` Determines the maximum size of the circulant matrix to use -- a maximum of :math:`\mathrm{maxm}[0]` elements in the :math:`x`-direction, and a maximum of :math:`\mathrm{maxm}[1]` elements in the :math:`y`-direction. The maximum size of the circulant matrix is thus :math:`\mathrm{maxm}[0]`:math:`\times`:math:`\mathrm{maxm}[1]`. **var** : float The multiplicative factor :math:`\sigma^2` of the variogram :math:`\gamma \left(\mathbf{x}\right)`. **icov2** : int Determines which of the preset variograms to use. The choices are given below. Note that :math:`x^{\prime } = \left\lVert \frac{x}{\ell_1},\frac{y}{\ell_2}\right\rVert`, where :math:`\ell_1` and :math:`\ell_2` are correlation lengths in the :math:`x` and :math:`y` directions respectively and are parameters for most of the variograms, and :math:`\sigma^2` is the variance specified by :math:`\mathrm{var}`. :math:`\mathrm{icov2} = 1` Symmetric stable variogram .. math:: \gamma \left(\mathbf{x}\right) = \sigma^2\mathrm{exp}\left(-\left(x^{\prime }\right)^{\nu }\right)\text{,} where :math:`\ell_1 = \mathrm{params}[0]`, :math:`\ell_1 > 0`, :math:`\ell_2 = \mathrm{params}[1]`, :math:`\ell_2 > 0`, :math:`\nu = \mathrm{params}[2]`, :math:`0 < \nu \leq 2`. :math:`\mathrm{icov2} = 2` Cauchy variogram .. math:: \gamma \left(\mathbf{x}\right) = \sigma^2\left(1+\left(x^{\prime }\right)^2\right)^{{-\nu }}\text{,} where :math:`\ell_1 = \mathrm{params}[0]`, :math:`\ell_1 > 0`, :math:`\ell_2 = \mathrm{params}[1]`, :math:`\ell_2 > 0`, :math:`\nu = \mathrm{params}[2]`, :math:`\nu > 0`. :math:`\mathrm{icov2} = 3` Differential variogram with compact support .. math:: \gamma \left(\mathbf{x}\right) = \left\{\begin{array}{cc} \sigma^2 \left(1+8x^{\prime }+25\left(x^{\prime }\right)^2+32\left(x^{\prime }\right)^3\right) \left(1-x^{\prime }\right)^8 \text{,} & x^{\prime } < 1 \text{,} \\ 0 \text{,} & x^{\prime } \geq 1 \text{,} \end{array}\right. where :math:`\ell_1 = \mathrm{params}[0]`, :math:`\ell_1 > 0`, :math:`\ell_2 = \mathrm{params}[1]`, :math:`\ell_2 > 0`. :math:`\mathrm{icov2} = 4` Exponential variogram .. math:: \gamma \left(\mathbf{x}\right) = \sigma^2\mathrm{exp}\left(-x^{\prime }\right)\text{,} where :math:`\ell_1 = \mathrm{params}[0]`, :math:`\ell_1 > 0`, :math:`\ell_2 = \mathrm{params}[1]`, :math:`\ell_2 > 0`. :math:`\mathrm{icov2} = 5` Gaussian variogram .. math:: \gamma \left(\mathbf{x}\right) = \sigma^2\mathrm{exp}\left({-\left(x^{\prime }\right)}^2\right)\text{,} where :math:`\ell_1 = \mathrm{params}[0]`, :math:`\ell_1 > 0`, :math:`\ell_2 = \mathrm{params}[1]`, :math:`\ell_2 > 0`. :math:`\mathrm{icov2} = 6` Nugget variogram .. math:: \gamma \left(\mathbf{x}\right) = \left\{\begin{array}{cc}\sigma^2\text{,}&\mathbf{x} = 0\text{,}\\0\text{,}&\mathbf{x}\neq 0\text{.}\end{array}\right. No parameters need be set for this value of :math:`\mathrm{icov2}`. :math:`\mathrm{icov2} = 7` Spherical variogram .. math:: \gamma \left(\mathbf{x}\right) = \left\{\begin{array}{cc} \sigma^2 \left(1-1.5x^{\prime }+0.5\left(x^{\prime }\right)^3\right) \text{,} & x^{\prime } < 1 \text{,} \\0\text{,}& x^{\prime } \geq 1 \text{,} \end{array}\right. where :math:`\ell_1 = \mathrm{params}[0]`, :math:`\ell_1 > 0`, :math:`\ell_2 = \mathrm{params}[1]`, :math:`\ell_2 > 0`. :math:`\mathrm{icov2} = 8` Bessel variogram .. math:: \gamma \left(\mathbf{x}\right) = \sigma^2\frac{{2^{\nu }\Gamma \left(\nu +1\right)J_{\nu }\left(x^{\prime }\right)}}{\left(x^{\prime }\right)^{\nu }}\text{,} where :math:`J_{\nu }\left(·\right)` is the Bessel function of the first kind, :math:`\ell_1 = \mathrm{params}[0]`, :math:`\ell_1 > 0`, :math:`\ell_2 = \mathrm{params}[1]`, :math:`\ell_2 > 0`, :math:`\nu = \mathrm{params}[2]`, :math:`\nu \geq 0`. :math:`\mathrm{icov2} = 9` Hole effect variogram .. math:: \gamma \left(\mathbf{x}\right) = \sigma^2\frac{\sin\left(x^{\prime }\right)}{x^{\prime }}\text{,} where :math:`\ell_1 = \mathrm{params}[0]`, :math:`\ell_1 > 0`, :math:`\ell_2 = \mathrm{params}[1]`, :math:`\ell_2 > 0`. :math:`\mathrm{icov2} = 10` Whittle-Matérn variogram .. math:: \gamma \left(\mathbf{x}\right) = \sigma^2\frac{{2^{{1-\nu }}\left(x^{\prime }\right)^{\nu }K_{\nu }\left(x^{\prime }\right)}}{{\Gamma \left(\nu \right)}}\text{,} where :math:`K_{\nu }\left(·\right)` is the modified Bessel function of the second kind, :math:`\ell_1 = \mathrm{params}[0]`, :math:`\ell_1 > 0`, :math:`\ell_2 = \mathrm{params}[1]`, :math:`\ell_2 > 0`, :math:`\nu = \mathrm{params}[2]`, :math:`\nu > 0`. :math:`\mathrm{icov2} = 11` Continuously parameterised variogram with compact support .. math:: \gamma \left(\mathbf{x}\right) = \left\{\begin{array}{cc} \sigma^2 \frac{{2^{{1-\nu }}\left(x^{\prime }\right)^{\nu }K_{\nu }\left(x^{\prime }\right)}}{{\Gamma \left(\nu \right)}} \left(1+8x^{{\prime \prime }}+25\left(x^{{\prime \prime }}\right)^2+32\left(x^{{\prime \prime }}\right)^3\right)\left(1-x^{{\prime \prime }}\right)^8\text{,}&x^{{\prime \prime }} < 1\text{,}\\0\text{,}&x^{{\prime \prime }}\geq 1\text{,} \end{array}\right. where :math:`x^{{\textit{′′}}} = \left\lVert \frac{x^{\prime }}{{\ell_1s_1}},\frac{y^{\prime }}{{\ell_2s_2}}\right\rVert`, :math:`K_{\nu }\left(·\right)` is the modified Bessel function of the second kind, :math:`\ell_1 = \mathrm{params}[0]`, :math:`\ell_1 > 0`, :math:`\ell_2 = \mathrm{params}[1]`, :math:`\ell_2 > 0`, :math:`s_1 = \mathrm{params}[2]`, :math:`s_1 > 0`, :math:`s_2 = \mathrm{params}[3]`, :math:`s_2 > 0`, :math:`\nu = \mathrm{params}[4]`, :math:`\nu > 0`. :math:`\mathrm{icov2} = 12` Generalized hyperbolic distribution variogram .. math:: \gamma \left(\mathbf{x}\right) = \sigma^2\frac{\left(\delta^2+\left(x^{\prime }\right)^2\right)^{\frac{\lambda }{2}}}{{\delta^{\lambda }K_{\lambda }\left(\kappa \delta \right)}}K_{\lambda }\left(\kappa \left(\delta^2+\left(x^{\prime }\right)^2\right)^{\frac{1}{2}}\right)\text{,} where :math:`K_{\lambda }\left(·\right)` is the modified Bessel function of the second kind, :math:`\ell_1 = \mathrm{params}[0]`, :math:`\ell_1 > 0`, :math:`\ell_2 = \mathrm{params}[1]`, :math:`\ell_2 > 0`, :math:`\lambda = \mathrm{params}[2]`, no constraint on :math:`\lambda`, :math:`\delta = \mathrm{params}[3]`, :math:`\delta > 0`, :math:`\kappa = \mathrm{params}[4]`, :math:`\kappa > 0`. **params** : float, array-like, shape :math:`\left(\textit{np}\right)` The parameters for the variogram as detailed in the description of :math:`\mathrm{icov2}`. **norm** : int, optional Determines which norm to use when calculating the variogram. :math:`\mathrm{norm} = 1` The 1-norm is used, i.e., :math:`\left\lVert x,y\right\rVert = \left\lvert x\right\rvert +\left\lvert y\right\rvert`. :math:`\mathrm{norm} = 2` The 2-norm (Euclidean norm) is used, i.e., :math:`\left\lVert x,y\right\rVert = \sqrt{x^2+y^2}`. **pad** : int, optional Determines whether the embedding matrix is padded with zeros, or padded with values of the variogram. The choice of padding may affect how big the embedding matrix must be in order to be positive semidefinite. :math:`\mathrm{pad} = 0` The embedding matrix is padded with zeros. :math:`\mathrm{pad} = 1` The embedding matrix is padded with values of the variogram. **icorr** : int, optional Determines which approximation to implement if required, as described in :ref:`Notes <g05zr-py2-py-notes>`. **Returns** **lam** : float, ndarray, shape :math:`\left(:\right)` Contains the square roots of the eigenvalues of the embedding matrix. **xx** : float, ndarray, shape :math:`\left(:\right)` The points of the :math:`x`-coordinates at which values of the random field will be output. **yy** : float, ndarray, shape :math:`\left(:\right)` The points of the :math:`y`-coordinates at which values of the random field will be output. **m** : int, ndarray, shape :math:`\left(2\right)` :math:`\mathrm{m}[0]` contains :math:`M_1`, the size of the circulant blocks and :math:`\mathrm{m}[1]` contains :math:`M_2`, the number of blocks, resulting in a final square matrix of size :math:`M_1\times M_2`. **approx** : int Indicates whether approximation was used. :math:`\mathrm{approx} = 0` No approximation was used. :math:`\mathrm{approx} = 1` Approximation was used. **rho** : float Indicates the scaling of the covariance matrix. :math:`\mathrm{rho} = 1.0` unless approximation was used with :math:`\mathrm{icorr} = 0` or :math:`1`. **icount** : int Indicates the number of negative eigenvalues in the embedding matrix which have had to be set to zero. **eig** : float, ndarray, shape :math:`\left(3\right)` Indicates information about the negative eigenvalues in the embedding matrix which have had to be set to zero. :math:`\mathrm{eig}[0]` contains the smallest eigenvalue, :math:`\mathrm{eig}[1]` contains the sum of the squares of the negative eigenvalues, and :math:`\mathrm{eig}[2]` contains the sum of the absolute values of the negative eigenvalues. .. _g05zr-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{ns} = \left[\langle\mathit{\boldsymbol{value}}\rangle, \langle\mathit{\boldsymbol{value}}\rangle\right]`. Constraint: :math:`\mathrm{ns}[0]\geq 1`, :math:`\mathrm{ns}[1]\geq 1`. (`errno` :math:`2`) On entry, :math:`\mathrm{xmin} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{xmax} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{xmin} < \mathrm{xmax}`. (`errno` :math:`4`) On entry, :math:`\mathrm{ymin} = \langle\mathit{\boldsymbol{value}}\rangle` and :math:`\mathrm{ymax} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{ymin} < \mathrm{ymax}`. (`errno` :math:`6`) On entry, :math:`\mathrm{maxm} = \left[\langle\mathit{\boldsymbol{value}}\rangle, \langle\mathit{\boldsymbol{value}}\rangle\right]`. Constraint: the minimum calculated value for :math:`\mathrm{maxm}` are :math:`\left[\langle\mathit{\boldsymbol{value}}\rangle, \langle\mathit{\boldsymbol{value}}\rangle\right]`. (`errno` :math:`7`) On entry, :math:`\mathrm{var} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{var}\geq 0.0`. (`errno` :math:`8`) On entry, :math:`\mathrm{icov2} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{icov2}\geq 1` and :math:`\mathrm{icov2}\leq 12`. (`errno` :math:`9`) On entry, :math:`\mathrm{norm} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{norm} = 1` or :math:`2`. (`errno` :math:`10`) On entry, :math:`\textit{np} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: for :math:`\mathrm{icov2} = \langle\mathit{\boldsymbol{value}}\rangle`, :math:`\textit{np} = \langle\mathit{\boldsymbol{value}}\rangle`. (`errno` :math:`11`) On entry, :math:`\mathrm{params}[\langle\mathit{\boldsymbol{value}}\rangle] = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: dependent on :math:`\mathrm{icov2}`, see documentation. (`errno` :math:`12`) On entry, :math:`\mathrm{pad} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{pad} = 0` or :math:`1`. (`errno` :math:`13`) On entry, :math:`\mathrm{icorr} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{icorr} = 0`, :math:`1` or :math:`2`. .. _g05zr-py2-py-notes: **Notes** A two-dimensional random field :math:`Z\left(\mathbf{x}\right)` in :math:`\mathbb{R}^2` is a function which is random at every point :math:`\mathbf{x} \in \mathbb{R}^2`, so :math:`Z\left(\mathbf{x}\right)` is a random variable for each :math:`\mathbf{x}`. The random field has a mean function :math:`\mu \left(\mathbf{x}\right) = 𝔼\left[Z\left(\mathbf{x}\right)\right]` and a symmetric positive semidefinite covariance function :math:`C\left(\mathbf{x}, \mathbf{y}\right) = 𝔼\left[\left(Z\left(\mathbf{x}\right)-\mu \left(\mathbf{x}\right)\right)\left(Z\left(\mathbf{y}\right)-\mu \left(\mathbf{y}\right)\right)\right]`. :math:`Z\left(\mathbf{x}\right)` is a Gaussian random field if for any choice of :math:`n \in ℕ` and :math:`\mathbf{x}_1,\ldots,\mathbf{x}_n \in \mathbb{R}^2`, the random vector :math:`\left[Z\left(\mathbf{x}_1\right),\ldots,Z\left(\mathbf{x}_n\right)\right]^\mathrm{T}` follows a multivariate Normal distribution, which would have a mean vector :math:`\tilde{\mu }` with entries :math:`\tilde{\mu }_i = \mu \left(\mathbf{x}_i\right)` and a covariance matrix :math:`\tilde{C}` with entries :math:`\tilde{C}_{{ij}} = C\left(\mathbf{x}_i, \mathbf{x}_j\right)`. A Gaussian random field :math:`Z\left(\mathbf{x}\right)` is stationary if :math:`\mu \left(\mathbf{x}\right)` is constant for all :math:`\mathbf{x} \in \mathbb{R}^2` and :math:`C\left(\mathbf{x}, \mathbf{y}\right) = C\left({\mathbf{x}+\mathbf{a}}, {\mathbf{y}+\mathbf{a}}\right)` for all :math:`\left. \mathbf{x}, \mathbf{y}, \mathbf{a}\right. \in \mathbb{R}^2` and hence we can express the covariance function :math:`C\left(\mathbf{x}, \mathbf{y}\right)` as a function :math:`\gamma` of one variable: :math:`C\left(\mathbf{x}, \mathbf{y}\right) = \gamma \left(\mathbf{x}-\mathbf{y}\right)`. :math:`\gamma` is known as a variogram (or more correctly, a semivariogram) and includes the multiplicative factor :math:`\sigma^2` representing the variance such that :math:`\gamma \left(0\right) = \sigma^2`. The functions ``field_2d_predef_setup`` and :meth:`field_2d_generate` are used to simulate a two-dimensional stationary Gaussian random field, with mean function zero and variogram :math:`\gamma \left(\mathbf{x}\right)`, over a domain :math:`\left[x_{\textit{min}}, x_{\textit{max}}\right]\times \left[y_{\textit{min}}, y_{\textit{max}}\right]`, using an equally spaced set of :math:`N_1\times N_2` points; :math:`N_1` points in the :math:`x`-direction and :math:`N_2` points in the :math:`y`-direction. The problem reduces to sampling a Gaussian random vector :math:`\mathbf{X}` of size :math:`N_1\times N_2`, with mean vector zero and a symmetric covariance matrix :math:`A`, which is an :math:`N_2\times N_2` block Toeplitz matrix with Toeplitz blocks of size :math:`N_1\times N_1`. Since :math:`A` is in general expensive to factorize, a technique known as the `circulant embedding method` is used. :math:`A` is embedded into a larger, symmetric matrix :math:`B`, which is an :math:`M_2\times M_2` block circulant matrix with circulant blocks of size :math:`M_1\times M_1`, where :math:`M_1\geq 2\left(N_1-1\right)` and :math:`M_2\geq 2\left(N_2-1\right)`. :math:`B` can now be factorized as :math:`B = W\Lambda W^* = R^*R`, where :math:`W` is the two-dimensional Fourier matrix (:math:`W^*` is the complex conjugate of :math:`W`), :math:`\Lambda` is the diagonal matrix containing the eigenvalues of :math:`B` and :math:`R = \Lambda^{\frac{1}{2}}W^*`. :math:`B` is known as the embedding matrix. The eigenvalues can be calculated by performing a discrete Fourier transform of the first row (or column) of :math:`B` and multiplying by :math:`M_1\times M_2`, and so only the first row (or column) of :math:`B` is needed -- the whole matrix does not need to be formed. As long as all of the values of :math:`\Lambda` are non-negative (i.e., :math:`B` is positive semidefinite), :math:`B` is a covariance matrix for a random vector :math:`\mathbf{Y}` which has :math:`M_2` blocks of size :math:`M_1`. Two samples of :math:`\mathbf{Y}` can now be simulated from the real and imaginary parts of :math:`R^*\left(\mathbf{U}+i\mathbf{V}\right)`, where :math:`\mathbf{U}` and :math:`\mathbf{V}` have elements from the standard Normal distribution. Since :math:`R^*\left(\mathbf{U}+i\mathbf{V}\right) = W\Lambda^{\frac{1}{2}}\left(\mathbf{U}+i\mathbf{V}\right)`, this calculation can be done using a discrete Fourier transform of the vector :math:`\Lambda^{\frac{1}{2}}\left(\mathbf{U}+i\mathbf{V}\right)`. Two samples of the random vector :math:`\mathbf{X}` can now be recovered by taking the first :math:`N_1` elements of the first :math:`N_2` blocks of each sample of :math:`\mathbf{Y}` -- because the original covariance matrix :math:`A` is embedded in :math:`B`, :math:`\mathbf{X}` will have the correct distribution. If :math:`B` is not positive semidefinite, larger embedding matrices :math:`B` can be tried; however if the size of the matrix would have to be larger than :math:`\mathrm{maxm}`, an approximation procedure is used. We write :math:`\Lambda = \Lambda_++\Lambda_-`, where :math:`\Lambda_+` and :math:`\Lambda_-` contain the non-negative and negative eigenvalues of :math:`B` respectively. Then :math:`B` is replaced by :math:`\rho B_+` where :math:`B_+ = W\Lambda_+W^*` and :math:`\rho \in \left(0, 1\right]` is a scaling factor. The error :math:`\epsilon` in approximating the distribution of the random field is given by .. math:: \epsilon = \sqrt{\frac{{\left(1-\rho \right)^2\mathrm{trace}\left(\Lambda \right)+\rho^2\mathrm{trace}\left(\Lambda_-\right)}}{M}}\text{.} Three choices for :math:`\rho` are available, and are determined by the input argument :math:`\mathrm{icorr}`: setting :math:`\mathrm{icorr} = 0` sets .. math:: \rho = \frac{\mathrm{trace}\left(\Lambda \right)}{\mathrm{trace}\left(\Lambda_+\right)}\text{,} setting :math:`\mathrm{icorr} = 1` sets .. math:: \rho = \sqrt{\frac{\mathrm{trace}\left(\Lambda \right)}{\mathrm{trace}\left(\Lambda_+\right)}}\text{,} setting :math:`\mathrm{icorr} = 2` sets :math:`\rho = 1`. ``field_2d_predef_setup`` finds a suitable positive semidefinite embedding matrix :math:`B` and outputs its sizes in the vector :math:`\mathrm{m}` and the square roots of its eigenvalues in :math:`\mathrm{lam}`. If approximation is used, information regarding the accuracy of the approximation is output. Note that only the first row (or column) of :math:`B` is actually formed and stored. .. _g05zr-py2-py-references: **References** Dietrich, C R and Newsam, G N, 1997, `Fast and exact simulation of stationary Gaussian processes through circulant embedding of the covariance matrix`, SIAM J. Sci. Comput. (18), 1088--1107 Schlather, M, 1999, `Introduction to positive definite functions and to unconditional simulation of random fields`, Technical Report ST 99--10, Lancaster University Wood, A T A and Chan, G, 1997, `Algorithm AS 312: An Algorithm for Simulating Stationary Gaussian Random Fields`, Journal of the Royal Statistical Society, Series C (Applied Statistics) (Volume 46) (1), 171--181 """ raise NotImplementedError
[docs]def field_2d_generate(ns, s, m, lam, rho, statecomm): r""" ``field_2d_generate`` produces realizations of a stationary Gaussian random field in two dimensions, using the circulant embedding method. The square roots of the eigenvalues of the extended covariance matrix (or embedding matrix) need to be input, and can be calculated using :meth:`field_2d_user_setup` or :meth:`field_2d_predef_setup`. .. _g05zs-py2-py-doc: For full information please refer to the NAG Library document for g05zs https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05zsf.html .. _g05zs-py2-py-parameters: **Parameters** **ns** : int, array-like, shape :math:`\left(2\right)` The number of sample points to use in each direction, with :math:`\mathrm{ns}[0]` sample points in the :math:`x`-direction and :math:`\mathrm{ns}[1]` sample points in the :math:`y`-direction. The total number of sample points on the grid is, therefore, :math:`\mathrm{ns}[0]\times \mathrm{ns}[1]`. This must be the same value as supplied to :meth:`field_2d_user_setup` or :meth:`field_2d_predef_setup` when calculating the eigenvalues of the embedding matrix. **s** : int :math:`S`, the number of realizations of the random field to simulate. **m** : int, array-like, shape :math:`\left(2\right)` Indicates the size, :math:`M`, of the embedding matrix as returned by :meth:`field_2d_user_setup` or :meth:`field_2d_predef_setup`. The embedding matrix is a block circulant matrix with circulant blocks. :math:`\mathrm{m}[0]` is the size of each block, and :math:`\mathrm{m}[1]` is the number of blocks. **lam** : float, array-like, shape :math:`\left(\mathrm{m}[0]\times \mathrm{m}[1]\right)` Contains the square roots of the eigenvalues of the embedding matrix, as returned by :meth:`field_2d_user_setup` or :meth:`field_2d_predef_setup`. **rho** : float Indicates the scaling of the covariance matrix, as returned by :meth:`field_2d_user_setup` or :meth:`field_2d_predef_setup`. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **z** : float, ndarray, shape :math:`\left(:, \mathrm{s}\right)` Contains the realizations of the random field. The :math:`k`\ th realization (where :math:`k = 1,2,\ldots,\mathrm{s}`) of the random field on the two-dimensional grid :math:`\left(x_i, y_j\right)` is stored in :math:`\mathrm{z}[ \left(j-1\right)\times \mathrm{ns}[0] +i -1,k-1]`, for :math:`i = 1,2,\ldots,\mathrm{ns}[0]` and for :math:`j = 1,2,\ldots,\mathrm{ns}[1]`. The points are returned in :math:`\textit{xx}` and :math:`\textit{yy}` by :meth:`field_2d_user_setup` or :meth:`field_2d_predef_setup`. .. _g05zs-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{ns} = \left[\langle\mathit{\boldsymbol{value}}\rangle, \langle\mathit{\boldsymbol{value}}\rangle\right]`. Constraint: :math:`\mathrm{ns}[0]\geq 1`, :math:`\mathrm{ns}[1]\geq 1`. (`errno` :math:`2`) On entry, :math:`\mathrm{s} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{s}\geq 1`. (`errno` :math:`3`) On entry, :math:`\mathrm{m} = \left[\langle\mathit{\boldsymbol{value}}\rangle, \langle\mathit{\boldsymbol{value}}\rangle\right]`, and :math:`\mathrm{ns} = \left[\langle\mathit{\boldsymbol{value}}\rangle, \langle\mathit{\boldsymbol{value}}\rangle\right]`. Constraints: :math:`\mathrm{m}[i-1]\geq \mathrm{max}\left(1, {2\left(\mathrm{ns}[i-1]\right)-1}\right)`, for :math:`i = 1,2`. (`errno` :math:`4`) On entry, at least one element of :math:`\mathrm{lam}` was negative. Constraint: all elements of :math:`\mathrm{lam}` must be non-negative. (`errno` :math:`5`) On entry, :math:`\mathrm{rho} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`0.0 < \mathrm{rho}\leq 1.0`. (`errno` :math:`6`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05zs-py2-py-notes: **Notes** A two-dimensional random field :math:`Z\left(\mathbf{x}\right)` in :math:`\mathbb{R}^2` is a function which is random at every point :math:`\mathbf{x} \in \mathbb{R}^2`, so :math:`Z\left(\mathbf{x}\right)` is a random variable for each :math:`\mathbf{x}`. The random field has a mean function :math:`\mu \left(\mathbf{x}\right) = 𝔼\left[Z\left(\mathbf{x}\right)\right]` and a symmetric positive semidefinite covariance function :math:`C\left(\mathbf{x}, \mathbf{y}\right) = 𝔼\left[\left(Z\left(\mathbf{x}\right)-\mu \left(\mathbf{x}\right)\right)\left(Z\left(\mathbf{y}\right)-\mu \left(\mathbf{y}\right)\right)\right]`. :math:`Z\left(\mathbf{x}\right)` is a Gaussian random field if for any choice of :math:`n \in ℕ` and :math:`\mathbf{x}_1,\ldots,\mathbf{x}_n \in \mathbb{R}^2`, the random vector :math:`\left[Z\left(\mathbf{x}_1\right),\ldots,Z\left(\mathbf{x}_n\right)\right]^\mathrm{T}` follows a multivariate Normal distribution, which would have a mean vector :math:`\tilde{\mu }` with entries :math:`\tilde{\mu }_i = \mu \left(\mathbf{x}_i\right)` and a covariance matrix :math:`\tilde{C}` with entries :math:`\tilde{C}_{{ij}} = C\left(\mathbf{x}_i, \mathbf{x}_j\right)`. A Gaussian random field :math:`Z\left(\mathbf{x}\right)` is stationary if :math:`\mu \left(\mathbf{x}\right)` is constant for all :math:`\mathbf{x} \in \mathbb{R}^2` and :math:`C\left(\mathbf{x}, \mathbf{y}\right) = C\left({\mathbf{x}+\mathbf{a}}, {\mathbf{y}+\mathbf{a}}\right)` for all :math:`\left. \mathbf{x}, \mathbf{y}, \mathbf{a}\right. \in \mathbb{R}^2` and hence we can express the covariance function :math:`C\left(\mathbf{x}, \mathbf{y}\right)` as a function :math:`\gamma` of one variable: :math:`C\left(\mathbf{x}, \mathbf{y}\right) = \gamma \left(\mathbf{x}-\mathbf{y}\right)`. :math:`\gamma` is known as a variogram (or more correctly, a semivariogram) and includes the multiplicative factor :math:`\sigma^2` representing the variance such that :math:`\gamma \left(0\right) = \sigma^2`. The functions :meth:`field_2d_user_setup` or :meth:`field_2d_predef_setup` along with ``field_2d_generate`` are used to simulate a two-dimensional stationary Gaussian random field, with mean function zero and variogram :math:`\gamma \left(\mathbf{x}\right)`, over a domain :math:`\left[x_{\textit{min}}, x_{\textit{max}}\right]\times \left[y_{\textit{min}}, y_{\textit{max}}\right]`, using an equally spaced set of :math:`N_1\times N_2` points; :math:`N_1` points in the :math:`x`-direction and :math:`N_2` points in the :math:`y`-direction. The problem reduces to sampling a Gaussian random vector :math:`\mathbf{X}` of size :math:`N_1\times N_2`, with mean vector zero and a symmetric covariance matrix :math:`A`, which is an :math:`N_2\times N_2` block Toeplitz matrix with Toeplitz blocks of size :math:`N_1\times N_1`. Since :math:`A` is in general expensive to factorize, a technique known as the `circulant embedding method` is used. :math:`A` is embedded into a larger, symmetric matrix :math:`B`, which is an :math:`M_2\times M_2` block circulant matrix with circulant bocks of size :math:`M_1\times M_1`, where :math:`M_1\geq 2\left(N_1-1\right)` and :math:`M_2\geq 2\left(N_2-1\right)`. :math:`B` can now be factorized as :math:`B = W\Lambda W^* = R^*R`, where :math:`W` is the two-dimensional Fourier matrix (:math:`W^*` is the complex conjugate of :math:`W`), :math:`\Lambda` is the diagonal matrix containing the eigenvalues of :math:`B` and :math:`R = \Lambda^{\frac{1}{2}}W^*`. :math:`B` is known as the embedding matrix. The eigenvalues can be calculated by performing a discrete Fourier transform of the first row (or column) of :math:`B` and multiplying by :math:`M_1\times M_2`, and so only the first row (or column) of :math:`B` is needed -- the whole matrix does not need to be formed. The symmetry of :math:`A` as a block matrix, and the symmetry of each block of :math:`A`, depends on whether the covariance function :math:`\gamma` is even or not. :math:`\gamma` is even if :math:`\gamma \left(\mathbf{x}\right) = \gamma \left(-\mathbf{x}\right)` for all :math:`\mathbf{x} \in \mathbb{R}^2`, and uneven otherwise (in higher dimensions, :math:`\gamma` can be even in some coordinates and uneven in others, but in two dimensions :math:`\gamma` is either even in both coordinates or uneven in both coordinates). If :math:`\gamma` is even then :math:`A` is a symmetric block matrix and has symmetric blocks; if :math:`\gamma` is uneven then :math:`A` is not a symmetric block matrix and has non-symmetric blocks. In the uneven case, :math:`M_1` and :math:`M_2` are set to be odd in order to guarantee symmetry in :math:`B`. As long as all of the values of :math:`\Lambda` are non-negative (i.e., :math:`B` is positive semidefinite), :math:`B` is a covariance matrix for a random vector :math:`\mathbf{Y}` which has :math:`M_2` 'blocks' of size :math:`M_1`. Two samples of :math:`\mathbf{Y}` can now be simulated from the real and imaginary parts of :math:`R^*\left(\mathbf{U}+i\mathbf{V}\right)`, where :math:`\mathbf{U}` and :math:`\mathbf{V}` have elements from the standard Normal distribution. Since :math:`R^*\left(\mathbf{U}+i\mathbf{V}\right) = W\Lambda^{\frac{1}{2}}\left(\mathbf{U}+i\mathbf{V}\right)`, this calculation can be done using a discrete Fourier transform of the vector :math:`\Lambda^{\frac{1}{2}}\left(\mathbf{U}+i\mathbf{V}\right)`. Two samples of the random vector :math:`\mathbf{X}` can now be recovered by taking the first :math:`N_1` elements of the first :math:`N_2` blocks of each sample of :math:`Y` -- because the original covariance matrix :math:`A` is embedded in :math:`B`, :math:`\mathbf{X}` will have the correct distribution. If :math:`B` is not positive semidefinite, larger embedding matrices :math:`B` can be tried; however if the size of the matrix would have to be larger than :math:`\textit{maxm}`, an approximation procedure is used. See the documentation of :meth:`field_2d_user_setup` or :meth:`field_2d_predef_setup` for details of the approximation procedure. ``field_2d_generate`` takes the square roots of the eigenvalues of the embedding matrix :math:`B`, and its size vector :math:`M`, as input and outputs :math:`S` realizations of the random field in :math:`Z`. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``field_2d_generate``. .. _g05zs-py2-py-references: **References** Dietrich, C R and Newsam, G N, 1997, `Fast and exact simulation of stationary Gaussian processes through circulant embedding of the covariance matrix`, SIAM J. Sci. Comput. (18), 1088--1107 Schlather, M, 1999, `Introduction to positive definite functions and to unconditional simulation of random fields`, Technical Report ST 99--10, Lancaster University Wood, A T A and Chan, G, 1994, `Simulation of stationary Gaussian processes in` :math:`\left[0, 1\right]^d`, Journal of Computational and Graphical Statistics (3(4)), 409--432 """ raise NotImplementedError
[docs]def field_fracbm_generate(ns, s, xmax, h, lam, rho, statecomm): r""" ``field_fracbm_generate`` produces realizations of a fractional Brownian motion, using the circulant embedding method. The square roots of the eigenvalues of the extended covariance matrix (or embedding matrix) need to be input, and can be calculated using :meth:`field_1d_predef_setup`. .. _g05zt-py2-py-doc: For full information please refer to the NAG Library document for g05zt https://www.nag.com/numeric/nl/nagdoc_27.3/flhtml/g05/g05ztf.html .. _g05zt-py2-py-parameters: **Parameters** **ns** : int The number of steps (points) to be generated in realizations of the increments of the fractional Brownian motion. This must be the same value as supplied to :meth:`field_1d_predef_setup` when calculating the eigenvalues of the embedding matrix. Note: in the context of fractional Brownian motion, :math:`\mathrm{ns}` represents the number of `steps` from a zero starting state. Realizations returned in :math:`\mathrm{z}` include this starting state and so :math:`\mathrm{ns}+1` values are returned for each realization. **s** : int :math:`S`, the number of realizations of the fractional Brownian motion to simulate. **xmax** : float The upper bound for the interval over which the fractional Brownian motion is to be simulated, as input to :meth:`field_1d_user_setup` or :meth:`field_1d_predef_setup`. **h** : float The Hurst parameter, :math:`H`, for the fractional Brownian motion. This must be the same value as supplied to :meth:`field_1d_predef_setup` in :math:`{\textit{params}}[0]`, when the eigenvalues of the embedding matrix were calculated. **lam** : float, array-like, shape :math:`\left(m\right)` Contains the square roots of the eigenvalues of the embedding matrix, as returned by :meth:`field_1d_user_setup` or :meth:`field_1d_predef_setup`. **rho** : float Indicates the scaling of the covariance matrix, as returned by :meth:`field_1d_user_setup` or :meth:`field_1d_predef_setup`. **statecomm** : dict, RNG communication object, modified in place RNG communication structure. This argument must have been initialized by a prior call to :meth:`init_repeat` or :meth:`init_nonrepeat`. **Returns** **z** : float, ndarray, shape :math:`\left(\mathrm{ns}+1, \mathrm{s}\right)` Contains the realizations of the fractional Brownian motion, :math:`Z`. The :math:`\textit{j}`\ th realization, for the :math:`\textit{i}`\ th point :math:`\mathrm{xx}[\textit{i}-1]`, is stored in :math:`\mathrm{z}[\textit{i}-1,\textit{j}-1]`, for :math:`\textit{i} = 1,2,\ldots,\mathrm{ns}+1`, for :math:`\textit{j} = 1,2,\ldots,\mathrm{s}`. **xx** : float, ndarray, shape :math:`\left(\mathrm{ns}+1\right)` The points at which values of the fractional Brownian motion are output. The first point is always zero, and the subsequent :math:`\mathrm{ns}` points represent the equispaced steps towards the last point, :math:`\mathrm{xmax}`. Note that in :meth:`field_1d_user_setup` and :meth:`field_1d_predef_setup`, the returned :math:`\textit{ns}` sample points are the mid-points of the grid returned in :math:`\mathrm{xx}` here. .. _g05zt-py2-py-errors: **Raises** **NagValueError** (`errno` :math:`1`) On entry, :math:`\mathrm{ns} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{ns}\geq 1`. (`errno` :math:`2`) On entry, :math:`\mathrm{s} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{s}\geq 1`. (`errno` :math:`3`) On entry, :math:`m = \langle\mathit{\boldsymbol{value}}\rangle`, and :math:`\mathrm{ns} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`m\geq \mathrm{max}\left(1, {2\left(\mathrm{ns}-1\right)}\right)`. (`errno` :math:`4`) On entry, :math:`\mathrm{xmax} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`\mathrm{xmax} > 0.0`. (`errno` :math:`5`) On entry, :math:`\mathrm{h} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`0.0 < \mathrm{h} < 1.0`. (`errno` :math:`6`) On entry, at least one element of :math:`\mathrm{lam}` was negative. Constraint: all elements of :math:`\mathrm{lam}` must be non-negative. (`errno` :math:`7`) On entry, :math:`\mathrm{rho} = \langle\mathit{\boldsymbol{value}}\rangle`. Constraint: :math:`0.0 < \mathrm{rho}\leq 1.0`. (`errno` :math:`8`) On entry, :math:`\mathrm{statecomm}`\ ['state'] vector has been corrupted or not initialized. .. _g05zt-py2-py-notes: **Notes** The functions :meth:`field_1d_predef_setup` and ``field_fracbm_generate`` are used to simulate a fractional Brownian motion process with Hurst parameter :math:`H` over an interval :math:`\left[0, x_{\textit{max}}\right]`, using a set of equally spaced points. Fractional Brownian motion itself cannot be simulated directly using this method, since it is not a stationary Gaussian random field; however its increments can be simulated like a stationary Gaussian random field. The circulant embedding method is described in the documentation for :meth:`field_1d_predef_setup`. ``field_fracbm_generate`` takes the square roots of the eigenvalues of the embedding matrix as returned by :meth:`field_1d_predef_setup` when :math:`{\textit{icov1}} = 14`, and its size :math:`M`, as input and outputs :math:`S` realizations of the fractional Brownian motion in :math:`Z`. One of the initialization functions :meth:`init_repeat` (for a repeatable sequence if computed sequentially) or :meth:`init_nonrepeat` (for a non-repeatable sequence) must be called prior to the first call to ``field_fracbm_generate``. .. _g05zt-py2-py-references: **References** Dietrich, C R and Newsam, G N, 1997, `Fast and exact simulation of stationary Gaussian processes through circulant embedding of the covariance matrix`, SIAM J. Sci. Comput. (18), 1088--1107 Schlather, M, 1999, `Introduction to positive definite functions and to unconditional simulation of random fields`, Technical Report ST 99--10, Lancaster University Wood, A T A and Chan, G, 1994, `Simulation of stationary Gaussian processes in` :math:`\left[0, 1\right]^d`, Journal of Computational and Graphical Statistics (3(4)), 409--432 """ raise NotImplementedError