# This file was automatically generated by SWIG (https://www.swig.org).
# Version 4.4.1
#
# Do not make changes to this file unless you know what you are doing - modify
# the SWIG interface file instead.

"""Meta-modelling."""

from sys import version_info as _swig_python_version_info
# Import the low-level C/C++ module
if getattr(globals().get("__spec__"), "parent", None) or __package__ or "." in __name__:
    from . import _metamodel
else:
    import _metamodel

try:
    import builtins as __builtin__
except ImportError:
    import __builtin__

def _swig_repr(self):
    try:
        strthis = "proxy of " + self.this.__repr__()
    except __builtin__.Exception:
        strthis = ""
    return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)


def _swig_setattr_nondynamic_instance_variable(set):
    def set_instance_attr(self, name, value):
        if name == "this":
            set(self, name, value)
        elif name == "thisown":
            self.this.own(value)
        elif hasattr(self, name) and isinstance(getattr(type(self), name), property):
            set(self, name, value)
        else:
            raise AttributeError("You cannot add instance attributes to %s" % self)
    return set_instance_attr


def _swig_setattr_nondynamic_class_variable(set):
    def set_class_attr(cls, name, value):
        if hasattr(cls, name) and not isinstance(getattr(cls, name), property):
            set(cls, name, value)
        else:
            raise AttributeError("You cannot add class attributes to %s" % cls)
    return set_class_attr


def _swig_add_metaclass(metaclass):
    """Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass"""
    def wrapper(cls):
        return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy())
    return wrapper


class _SwigNonDynamicMeta(type):
    """Meta class to enforce nondynamic attributes (no new attributes) for a class"""
    __setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__)


import openturns.base
import openturns.common
import openturns.typ
import openturns.statistics
import openturns.graph
import openturns.func
import openturns.geom
import openturns.iterative_statistics
import openturns.func2
import openturns.diff
import openturns.optim
import openturns.experiment
import openturns.solver
import openturns.algo
import openturns.model_copula
import openturns.weightedexperiment
import openturns.orthogonalbasis
import openturns.randomvector
import openturns.model_process
import openturns.dist_bundle1
import openturns.dist_bundle2
import openturns.dist_bundle3
class MetaModelResult(openturns.common.PersistentObject):
    r"""
    Data structure containing a metamodel.

    Parameters
    ----------
    sampleX, sampleY : 2-d sequence of float
        Input/output samples
    metaModel : :class:`~openturns.Function`
        Definition of the response surface(s) of the model's output(s).

    Notes
    -----
    Structure created by the method run() of :class:`~openturns.GaussianProcessRegression`
    or :class:`~openturns.FunctionalChaosAlgorithm` and obtained thanks to the
    method getResult() of these classes.

    See also
    --------
    openturns.LinearModelResult, openturns.FunctionalChaosResult, openturns.GaussianProcessRegressionResult
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.MetaModelResult_getClassName(self)

    def setInputSample(self, sampleX):
        r"""
        Accessor to the input sample.

        Parameters
        ----------
        inputSample : :class:`~openturns.Sample`
            The input sample.
        """
        return _metamodel.MetaModelResult_setInputSample(self, sampleX)

    def getInputSample(self):
        r"""
        Accessor to the input sample.

        Returns
        -------
        inputSample : :class:`~openturns.Sample`
            The input sample.
        """
        return _metamodel.MetaModelResult_getInputSample(self)

    def setOutputSample(self, sampleY):
        r"""
        Accessor to the output sample.

        Parameters
        ----------
        outputSample : :class:`~openturns.Sample`
            The output sample.
        """
        return _metamodel.MetaModelResult_setOutputSample(self, sampleY)

    def getOutputSample(self):
        r"""
        Accessor to the output sample.

        Returns
        -------
        outputSample : :class:`~openturns.Sample`
            The output sample.
        """
        return _metamodel.MetaModelResult_getOutputSample(self)

    def setMetaModel(self, metaModel):
        r"""
        Accessor to the metamodel.

        Parameters
        ----------
        metaModel : :class:`~openturns.Function`
            Metamodel.
        """
        return _metamodel.MetaModelResult_setMetaModel(self, metaModel)

    def getMetaModel(self):
        r"""
        Accessor to the metamodel.

        Returns
        -------
        metaModel : :class:`~openturns.Function`
            Metamodel.
        """
        return _metamodel.MetaModelResult_getMetaModel(self)

    def __repr__(self):
        return _metamodel.MetaModelResult___repr__(self)

    def __init__(self, *args):
        _metamodel.MetaModelResult_swiginit(self, _metamodel.new_MetaModelResult(*args))
    __swig_destroy__ = _metamodel.delete_MetaModelResult

# Register MetaModelResult in _metamodel:
_metamodel.MetaModelResult_swigregister(MetaModelResult)
class KrigingResult(MetaModelResult):
    r"""
    Kriging result.

    Available constructors:
        KrigingResult(*inputSample, outputSample, metaModel, basis, trendCoefficients, covarianceModel, covarianceCoefficients*)

        KrigingResult(*inputSample, outputSample, metaModel, basis, trendCoefficients, covarianceModel, covarianceCoefficients, covarianceCholeskyFactor, covarianceHMatrix*)


    Parameters
    ----------
    inputSample, outputSample : 2-d sequence of float
        The samples :math:`(\vect{x}_k)_{1 \leq k \leq N} \in \Rset^d` and :math:`(\vect{y}_k)_{1 \leq k \leq N}\in \Rset^p`.
    metaModel : :class:`~openturns.Function`
        The meta model: :math:`\tilde{\cM}: \Rset^d \rightarrow \Rset^p`, defined in :eq:`metaModelKrigFinal`.
    basis :  :class:`~openturns.Basis`
        Functional basis of size :math:`b` : :math:`(\varphi^l: \Rset^d \rightarrow \Rset^p)` for each :math:`l \in [1, b]`.
        Its size should be equal to zero if the trend is not estimated.
    trendCoefficients :  :class:`~openturns.Point`
       The trend coefficients vectors  :math:`(\vect{\alpha}^1, \dots, \vect{\alpha}^p)` stored as a Point.
    covarianceModel : :class:`~openturns.CovarianceModel`
        Covariance function of the Gaussian process.
    covarianceCoefficients : 2-d sequence of float
        The :math:`\vect{\gamma}` defined in :eq:`gammaEq`.
    covarianceCholeskyFactor : :class:`~openturns.TriangularMatrix`
        The Cholesky factor :math:`\mat{L}` of :math:`\mat{C}`.
    covarianceHMatrix :  :class:`~openturns.HMatrix`
        The *hmat* implementation of :math:`\mat{L}`.


    Notes
    -----
    The Kriging meta model :math:`\tilde{\cM}` is defined by:

    .. math::
        :label: metaModelKrig

        \tilde{\cM}(\vect{x}) =  \vect{\mu}(\vect{x}) + \Expect{\vect{Y}(\omega, \vect{x})\,| \,\cC}

    where :math:`\cC` is the condition :math:`\vect{Y}(\omega, \vect{x}_k) = \vect{y}_k` for each :math:`k \in [1, N]`.

    Equation :eq:`metaModelKrig` writes:

    .. math::

        \tilde{\cM}(\vect{x}) = \vect{\mu}(\vect{x}) + \Cov{\vect{Y}(\omega, \vect{x}), (\vect{Y}(\omega,\vect{x}_1),\dots,\vect{Y}(\omega, \vect{x}_N))}\vect{\gamma}

    where 

    .. math::

        \Cov{\vect{Y}(\omega, \vect{x}), (\vect{Y}(\omega, \vect{x}_1),\dots,\vect{Y}(\omega, \vect{x}_N))} = \left(\mat{C}(\vect{x},\vect{x}_1)|\dots|\mat{C}(\vect{x},\vect{x}_N)\right)\in \cM_{p,NP}(\Rset)

    and 

    .. math::
        :label: gammaEq

        \vect{\gamma} = \mat{C}^{-1}(\vect{y}-\vect{m})

    At the end, the meta model writes:

    .. math::
        :label: metaModelKrigFinal

        \tilde{\cM}(\vect{x}) = \vect{\mu}(\vect{x}) + \sum_{i=1}^N \gamma_i  \mat{C}(\vect{x},\vect{x}_i)


    Examples
    --------
    Create the model :math:`\cM: \Rset \mapsto \Rset` and the samples:

    >>> import openturns as ot
    >>> f = ot.SymbolicFunction(['x'],  ['x * sin(x)'])
    >>> sampleX = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]]
    >>> sampleY = f(sampleX)

    Create the algorithm:

    >>> basis = ot.Basis([ot.SymbolicFunction(['x'], ['x']), ot.SymbolicFunction(['x'], ['x^2'])])
    >>> covarianceModel = ot.GeneralizedExponential([2.0], 2.0)
    >>> algoKriging = ot.KrigingAlgorithm(sampleX, sampleY, covarianceModel, basis)
    >>> algoKriging.run()

    Get the result:

    >>> resKriging = algoKriging.getResult()

    Get the meta model:

    >>> metaModel = resKriging.getMetaModel()

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.KrigingResult_getClassName(self)

    def __repr__(self):
        return _metamodel.KrigingResult___repr__(self)

    def __str__(self, *args):
        return _metamodel.KrigingResult___str__(self, *args)

    def getBasis(self):
        r"""
        Accessor to the functional basis.

        Returns
        -------
        basis : :class:`~openturns.Basis`
            Functional basis of size :math:`b` : :math:`(\varphi^l: \Rset^d \rightarrow \Rset^p)` for each :math:`l \in [1, b]`.

        Notes
        -----
        If the trend is not estimated, the collection is empty. 

        """
        return _metamodel.KrigingResult_getBasis(self)

    def getTrendCoefficients(self):
        r"""
        Accessor to the trend coefficients.

        Returns
        -------
        trendCoef : :class:`~openturns.Point`
            The trend coefficients vectors :math:`(\vect{\alpha}^1, \dots, \vect{\alpha}^p)` stored as a Point.

        """
        return _metamodel.KrigingResult_getTrendCoefficients(self)

    def getCovarianceModel(self):
        r"""
        Accessor to the covariance model.

        Returns
        -------
        covModel : :class:`~openturns.CovarianceModel`
            The covariance model of the Gaussian process *W* with its optimized parameters.

        """
        return _metamodel.KrigingResult_getCovarianceModel(self)

    def getCovarianceCoefficients(self):
        r"""
        Accessor to the covariance coefficients.

        Returns
        -------
        covCoeff : :class:`~openturns.Sample`
            The :math:`\vect{\gamma}` defined in :eq:`gammaEq`.

        """
        return _metamodel.KrigingResult_getCovarianceCoefficients(self)

    def getConditionalMean(self, *args):
        r"""
        Compute the conditional mean of the Gaussian process on a point or a sample of points.

        Available usages:
            getConditionalMean(x)

            getConditionalMean(sampleX)

        Parameters
        ----------
        x : sequence of float
            The point :math:`\vect{x}` where the conditional mean of the output has to be evaluated.
        sampleX : 2-d sequence of float
             The sample :math:`(\vect{\xi}_1, \dots, \vect{\xi}_M)` where the conditional mean of the output has to be evaluated (*M* can be equal to 1).

        Returns
        -------
        condMean : :class:`~openturns.Point`
            The conditional mean :math:`\Expect{\vect{Y}(\omega, \vect{x})\, | \,  \cC}` at point :math:`\vect{x}`.
            Or the conditional mean matrix at the sample :math:`(\vect{\xi}_1, \dots, \vect{\xi}_M)`:

            .. math::

                \left(
                  \begin{array}{l}
                    \Expect{\vect{Y}(\omega, \vect{\xi}_1)\, | \,  \cC}\\
                    \dots  \\
                    \Expect{\vect{Y}(\omega, \vect{\xi}_M)\, | \,  \cC}
                  \end{array}
                \right)


        """
        return _metamodel.KrigingResult_getConditionalMean(self, *args)

    def getConditionalCovariance(self, *args):
        r"""
        Compute the conditional covariance of the Gaussian process on a point (or several points).

        Available usages:
            getConditionalCovariance(x)

            getConditionalCovariance(sampleX)

        Parameters
        ----------
        x : sequence of float
            The point :math:`\vect{x}` where the conditional covariance of the output has to be evaluated.
        sampleX : 2-d sequence of float
             The sample :math:`(\vect{\xi}_1, \dots, \vect{\xi}_M)` where the conditional covariance of the output has to be evaluated (*M* can be equal to 1).

        Returns
        -------
        condCov : :class:`~openturns.CovarianceMatrix`
            The conditional covariance :math:`\Cov{\vect{Y}(\omega, \vect{x})\, | \,  \cC}` at point :math:`\vect{x}`.
            Or the conditional covariance matrix at the sample :math:`(\vect{\xi}_1, \dots, \vect{\xi}_M)`:

            .. math::

                \left(
                  \begin{array}{lcl}
                    \Sigma_{11} & \dots & \Sigma_{1M} \\
                    \dots  \\
                    \Sigma_{M1} & \dots & \Sigma_{MM}
                  \end{array}
                \right)

            where :math:`\Sigma_{ij} = \Cov{\vect{Y}(\omega, \vect{\xi}_i), \vect{Y}(\omega, \vect{\xi}_j)\, | \,  \cC}`.
        """
        return _metamodel.KrigingResult_getConditionalCovariance(self, *args)

    def getConditionalMarginalCovariance(self, *args):
        r"""
        Compute the conditional covariance of the Gaussian process on a point (or several points).


        Available usages:
            getConditionalMarginalCovariance(x)

            getConditionalMarginalCovariance(sampleX)

        Parameters
        ----------
        x : sequence of float
            The point :math:`\vect{x}` where the conditional marginal covariance of the output has to be evaluated.
        sampleX : 2-d sequence of float
             The sample :math:`(\vect{\xi}_1, \dots, \vect{\xi}_M)` where the conditional marginal covariance of the output has to be evaluated (*M* can be equal to 1).

        Returns
        -------
        condCov : :class:`~openturns.CovarianceMatrix`
            The conditional covariance :math:`\Cov{\vect{Y}(\omega, \vect{x})\, | \,  \cC}` at point :math:`\vect{x}`.

        condCov : :class:`~openturns.CovarianceMatrixCollection`
            The collection of conditional covariance matrices :math:`\Cov{\vect{Y}(\omega, \vect{\xi})\, | \,  \cC}` at
            each point of the sample :math:`(\vect{\xi}_1, \dots, \vect{\xi}_M)`:

        Notes
        -----
        In case input parameter is a of type :class:`~openturns.Sample`, each element of the collection corresponds to the conditional
        covariance with respect to the input learning set (pointwise evaluation of the getConditionalCovariance).
        """
        return _metamodel.KrigingResult_getConditionalMarginalCovariance(self, *args)

    def getConditionalMarginalVariance(self, *args):
        r"""
        Compute the conditional variance of the Gaussian process on a point (or several points).


        Available usages:
            getConditionalMarginalVariance(x, marginalIndex)

            getConditionalMarginalVariance(sampleX, marginalIndex)

            getConditionalMarginalVariance(x, marginalIndices)

            getConditionalMarginalVariance(sampleX, marginalIndices)

        Parameters
        ----------
        x : sequence of float
            The point :math:`\vect{x}` where the conditional variance of the output has to be evaluated.
        sampleX : 2-d sequence of float
             The sample :math:`(\vect{\xi}_1, \dots, \vect{\xi}_M)` where the conditional variance of the output has to be evaluated (*M* can be equal to 1).
        marginalIndex : int
            Marginal of interest (for multiple outputs).
            Default value is 0
        marginalIndices : sequence of int
            Marginals of interest (for multiple outputs).

        Returns
        -------
        var : float
              Variance of interest.
              float if one point (x) and one marginal of interest (x, marginalIndex)

        varPoint : sequence of float
            The marginal variances


        Notes
        -----
        In case of fourth usage, the sequence of float is given as the concatenation of marginal variances 
        for each point in sampleX.
        """
        return _metamodel.KrigingResult_getConditionalMarginalVariance(self, *args)

    def __call__(self, *args):
        return _metamodel.KrigingResult___call__(self, *args)

    def __init__(self, *args):
        _metamodel.KrigingResult_swiginit(self, _metamodel.new_KrigingResult(*args))
    __swig_destroy__ = _metamodel.delete_KrigingResult

# Register KrigingResult in _metamodel:
_metamodel.KrigingResult_swigregister(KrigingResult)
class LinearModelResult(MetaModelResult):
    r"""
    Result of a LinearModelAlgorithm.

    Parameters
    ----------
    inputSample : 2-d sequence of float
        The input sample of a model.
    basis : :class:`~openturns.Basis`
        Functional basis to estimate the trend.
    design : :class:`~openturns.Matrix`
        The design matrix :math:`\mat{\Psi}`.
    outputSample : 2-d sequence of float
       The output sample :math:`(Y_i)_{1 \leq i \leq \sampleSize}`.
    metaModel : :class:`~openturns.Function`
        The meta model.
    coefficients : sequence of float
        The estimated coefficients :math:`\vect{\hat{a}}`. 
    formula : str
         The formula description. 
    coefficientsNames : sequence of str
         The coefficients names of the basis.  
    sampleResiduals : 2-d sequence of float
        The residual errors  :math:`(\varepsilon_i)_{1 \leq i \leq \sampleSize}`.
    standardizedSampleResiduals : 2-d sequence of float
        The standardized residuals defined in :eq:`stdRes`.
    diagonalGramInverse : sequence of float
        The diagonal of the Gram inverse matrix.
    leverages : sequence of float
        The leverages :math:`(\ell_i)_{1 \leq i \leq \sampleSize}` defined in :eq:`leverageDef`.
    cookDistances : sequence of float
        Cook's distances defined in :eq:`cookDef`.
    residualsVariance : float
        The unbiased variance estimator of the residuals defined in :eq:`estimSigma2Noise`.

    See Also
    --------
    LinearModelAlgorithm

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.LinearModelResult_getClassName(self)

    def __repr__(self):
        return _metamodel.LinearModelResult___repr__(self)

    def __str__(self, *args):
        return _metamodel.LinearModelResult___str__(self, *args)

    def __repr_markdown__(self):
        return _metamodel.LinearModelResult___repr_markdown__(self)

    def getBasis(self):
        r"""
        Accessor to the basis.

        Returns
        -------
        basis : :class:`~openturns.Basis`
            The basis of the regression model.

        Notes
        -----
        If a functional basis has been provided in the constructor, then we get it back:
        :math:`(\phi_j)_{1 \leq j \leq p'}`. Its size is :math:`p'`.

        Otherwise, the functional basis is composed of the projections :math:`\phi_k : \Rset^p \rightarrow \Rset`
        such that :math:`\phi_k(\vect{x}) = x_k` for :math:`1 \leq k \leq p`, completed with the constant function:
        :math:`\phi_0 : \vect{x} \rightarrow 1`. Its size is :math:`p+1`.
        """
        return _metamodel.LinearModelResult_getBasis(self)

    def getFittedSample(self):
        r"""
        Accessor to the fitted sample.

        Returns
        -------
        outputSample : :class:`~openturns.Sample`

        Notes
        -----
        The fitted sample is :math:`(\hat{Y}_1, \dots, \hat{Y}_\sampleSize)` where
        :math:`\hat{Y}_i` is defined in :eq:`fittedValue` or :eq:`fittedValue2`.
        """
        return _metamodel.LinearModelResult_getFittedSample(self)

    def getDesign(self):
        r"""
        Accessor to the design matrix.

        Returns
        -------
        design: :class:`~openturns.Matrix`
            The design matrix :math:`\mat{\Psi}`.

        Notes
        -----
        If the linear model is defined by :eq:`modelNoBase`, the design matrix is:

        .. math::
           :label: designMatDef

           \mat{\Psi} = (\vect{1}, \vect{X}_1, \dots, \vect{X}_{p})

        where :math:`\vect{1} = \Tr{(1, \dots, 1)}` and :math:`\vect{X}_k = \Tr{(X_k^1, \dots, X_k^\sampleSize)}`
        is the values of the regressor :math:`k` in the :math:`\sampleSize` experiences. Thus, :math:`\mat{\Psi}` has :math:`\sampleSize` rows and  :math:`p+1` columns.

        If the linear model is defined by :eq:`modelWithBase`, the design matrix is:

        .. math::
           :label: designMatDef2

           \mat{\Psi} = (\vect{\phi}_1, \dots, \vect{\phi}_{p'})

        where :math:`\vect{\phi_j} = \Tr{(\phi_j(\vect{X}^1), \dots, \phi_j(\vect{X}^\sampleSize))}`
        is the values of the function :math:`\phi_j` at the :math:`\sampleSize` experiences. Thus, :math:`\mat{\Psi}` has :math:`\sampleSize` rows and  :math:`p'` columns.
        """
        return _metamodel.LinearModelResult_getDesign(self)

    def getCoefficients(self):
        r"""
        Accessor to the coefficients of the linear model.

        Returns
        -------
        coefficients : :class:`~openturns.Point`
            The estimated of the coefficients :math:`\hat{\vect{a}}`.
        """
        return _metamodel.LinearModelResult_getCoefficients(self)

    def getCoefficientsStandardErrors(self):
        r"""
        Accessor to the coefficients of standard error.

        Returns
        -------
        standardErrors : :class:`~openturns.Point`

        Notes
        -----
        The standard deviation :math:`\sigma(a_k)` of the estimator :math:`\hat{a}_k` is defined by:

        .. math::
            :label: std_dev_estim

            \sigma(a_k)^2 = \sigma^2 \left(\Tr{\mat{\Psi}}\mat{\Psi}\right)^{-1}_{k+1, k+1}

        where:

        - the variance :math:`\sigma^2` of the residual :math:`\varepsilon` is approximated by
          its unbiaised estimator :math:`\hat{\sigma}^2` defined in :eq:`estimSigma2Noise`,
        - the matrix :math:`\mat{\Psi}` is the design matrix defined in :eq:`designMatDef` or :eq:`designMatDef2`.
        """
        return _metamodel.LinearModelResult_getCoefficientsStandardErrors(self)

    def getFormula(self):
        r"""
        Accessor to the formula.

        Returns
        -------
        condensedFormula : str

        Notes
        -----
        This formula gives access to the linear model.
        """
        return _metamodel.LinearModelResult_getFormula(self)

    def getCoefficientsNames(self):
        r"""
        Accessor to the coefficients names.

        Returns
        -------
        coefficientsNames : :class:`~openturns.Description`

        Notes
        -----
        The name of the coefficient :math:`a_k` is the name of the regressor :math:`X_k`.
        """
        return _metamodel.LinearModelResult_getCoefficientsNames(self)

    def getSampleResiduals(self):
        r"""
        Accessor to the residuals.

        Returns
        -------
        sampleResiduals : :class:`~openturns.Sample`
            The sample of the residuals.

        Notes
        -----
        The residuals sample is :math:`(\varepsilon_i)_{1 \leq i \leq \sampleSize}` defined in :eq:`residualDef`.
        """
        return _metamodel.LinearModelResult_getSampleResiduals(self)

    def getNoiseDistribution(self):
        r"""
        Accessor to the normal distribution of the residuals.

        Returns
        -------
        noiseDistribution : :class:`~openturns.Normal`
            The normal distribution estimated from the residuals.

        Notes
        -----
        The noise distribution is the distribution of the residuals. It is assumed to be Gaussian.
        The normal distribution has zero mean and
        its variance is estimated from the residuals sample
        :math:`(\varepsilon_i)_{1 \leq i \leq \sampleSize}` defined in :eq:`residualDef`,
        using the unbiaised estimator defined in :eq:`estimSigma2Noise`.

        If the residuals are not Gaussian, this distribution is not appropriate and should not be used.
        """
        return _metamodel.LinearModelResult_getNoiseDistribution(self)

    def getStandardizedResiduals(self):
        r"""
        Accessor to the standardized residuals.

        Returns
        -------
        standardizedResiduals : :class:`~openturns.Sample`
            The standarduzed residuals :math:`(\varepsilon_i^{st})_{1 \leq i  \leq \sampleSize}`.

        Notes
        -----
        The standardized residuals are defined by:

        .. math::
            :label: stdRes

            \varepsilon_i^{st} = \dfrac{\varepsilon_i}{\sqrt{\hat{\sigma}^2(1 - \ell_i)}}

        where :math:`\hat{\sigma}^2` is the unbiaised residuals variance defined in
        :eq:`estimSigma2Noise` and :math:`\ell_i` is the leverage of experience :math:`i` defined in :eq:`leverageDef`.
        """
        return _metamodel.LinearModelResult_getStandardizedResiduals(self)

    def getDegreesOfFreedom(self):
        r"""
        Accessor to the degrees of freedom.

        Returns
        -------
        dof : int, :math:`\geq 1`
            Number of degrees of freedom.

        Notes
        -----
        If the linear model is defined by :eq:`modelNoBase`, the degrees of freedom :math:`dof` is:

        .. math::
            :label: dofNoBase

            dof = \sampleSize - (p + 1)

        where :math:`p` is the number of regressors.

        Otherwise, the linear model is defined by :eq:`modelWithBase` and its :math:`dof` is:

        .. math::
            :label: dofWithBase

            dof = \sampleSize - p'

        where :math:`p'` is the number of functions in the provided basis.

        """
        return _metamodel.LinearModelResult_getDegreesOfFreedom(self)

    def getLeverages(self):
        r"""
        Accessor to the leverages.

        Returns
        -------
        leverages : :class:`~openturns.Point`
            The leverage of all the experiences :math:`(\ell_i)_{1 \leq i  \leq \sampleSize}`.

        Notes
        -----
        We denote by :math:`\hat{\vect{Y}} = (\hat{Y}_1, \dots, \hat{Y}_n)` the fitted values of the :math:`n` experiences. Then we have: 

        .. math::
          \hat{\vect{Y}} =  \mat{\Psi} \hat{\vect{a}}

        where :math:`\mat{\Psi}` is the design matrix defined in :eq:`designMatDef`. It leads to:

        .. math::
          \Var{\hat{\vect{Y}}} & = \mat{\Psi} \Var{\hat{\vect{a}}}\Tr{\mat{\Psi}} \\
                               & = \sigma^2 \mat{H}

        where:

        .. math::
          \mat{H} = \mat{\Psi} (\Tr{\mat{\Psi}}\mat{\Psi})^{-1} \Tr{\mat{\Psi}}

        Thus, for the experience :math:`i`, we get:

        .. math::
          :label: leverageDef

          \Var{\hat{Y}_i} = \sigma^2 \ell_{ii}

        where :math:`\ell_{ii}` is the :math:`i`-th element of the diagonal of :math:`\mat{H}`:
        :math:`\ell_{ii}` is the leverage :math:`\ell_i`  of experience :math:`i`.
        """
        return _metamodel.LinearModelResult_getLeverages(self)

    def getDiagonalGramInverse(self):
        r"""
        Accessor to the diagonal gram inverse matrix.

        Returns
        -------
        diagonalGramInverse : :class:`~openturns.Point`
            The diagonal of the Gram inverse matrix.

        Notes
        -----
        The Gram matrix is :math:`\Tr{\mat{\Psi}}\mat{\Psi}` where :math:`\mat{\Psi}`
        is the design matrix defined in :eq:`designMatDef` or :eq:`designMatDef2`.
        """
        return _metamodel.LinearModelResult_getDiagonalGramInverse(self)

    def getCookDistances(self):
        r"""
        Accessor to the cook's distances.

        Returns
        -------
        cookDistances : :class:`~openturns.Point`
            The Cook's distance of each experience :math:`(CookD_i)_{1 \leq i  \leq \sampleSize}`.

        Notes
        -----
        The Cook's distance measures the impact of every experience on the linear regression. See
        [rawlings2001]_ (section 11.2.1, *Cook's D* page 362) for more details.

        The Cook distance of experience :math:`i` is defined by:

        .. math::
            :label: cookDef

            CookD_i = \left(\dfrac{1}{\sampleSize-dof}\right) \left( \dfrac{\ell_i}{1 - \ell_i} \right)
            (\varepsilon_i^{st})^2

        where :math:`\varepsilon_i^{st}` is the standardized residual defined in :eq:`stdRes` and :math:`dof` is the 
        degrees of freedom defined in :eq:`dofNoBase` or :eq:`dofWithBase`.
        """
        return _metamodel.LinearModelResult_getCookDistances(self)

    def getResidualsVariance(self):
        r"""
        Accessor to the unbiased sample variance of the residuals.

        Returns
        -------
        residualsVariance : float
            The residuals variance estimator.

        Notes
        -----
        The residual variance estimator is
        the unbiaised empirical variance of the residuals:

        .. math::
           :label: estimSigma2Noise

           \hat{\sigma}^2 = \dfrac{1}{dof} \sum_{i=1}^\sampleSize  \varepsilon_i^2

        where :math:`dof` is the degrees of freedom of the model defined in :eq:`dofNoBase` or :eq:`dofWithBase`.
        """
        return _metamodel.LinearModelResult_getResidualsVariance(self)

    def hasIntercept(self):
        r"""
        Returns if intercept is provided in the basis or not.

        Returns
        -------
        intercept : Bool
           Tells if the model has a constant regressor.

        Notes
        -----
        The *intercept* is True when: 

        - the model is defined in :eq:`modelNoBase`,
        - the model is defined in :eq:`modelWithBase` such that the basis contains a constant function.

        """
        return _metamodel.LinearModelResult_hasIntercept(self)

    def getRSquared(self):
        r"""
        Accessor to the R-squared test.

        Returns
        -------
        rSquared : float
           The indicator :math:`R^2`.

        Notes
        -----
        The :math:`R^2` value quantifies the quality of the linear approximation.

        If the model is defined by :eq:`modelWithBase` such that the basis does not contain any intercept (constant function), then :math:`R^2` is defined by:

        .. math::
           R^2 = 1- \dfrac{\sum_{i=1}^\sampleSize \varepsilon_i^2}{\sum_{i=1}^\sampleSize Y_i^2}

        where the :math:`\varepsilon_i` are the residuals defined in :eq:`residualDef` and :math:`Y_i` the output sample values.

        Otherwise, when the model is defined by :eq:`modelNoBase` or by :eq:`modelWithBase` with an intercept, :math:`R^2` is defined by:

        .. math::
           R^2 = 1- \dfrac{\sum_{i=1}^\sampleSize \varepsilon_i^2}{\sum_{i=1}^\sampleSize (Y_i-\bar{Y})^2}

        where :math:`\bar{Y} = \dfrac{1}{\sampleSize} \sum_{i=1}^\sampleSize Y_i`.
        """
        return _metamodel.LinearModelResult_getRSquared(self)

    def getAdjustedRSquared(self):
        r"""
        Accessor to the Adjusted R-squared test.

        Returns
        -------
        adjustedRSquared : float
           The :math:`R_{ad}^2` indicator.


        Notes
        -----
        The :math:`R_{ad}^2` value quantifies the quality of the linear approximation. With respect to
        :math:`R^2`, :math:`R_{ad}^2` takes into account the data set
        size and the number of hyperparameters.

        If the model is defined by :eq:`modelWithBase` such that the basis does not contain any intercept (constant function), then :math:`R_{ad}^2` is defined by:

        .. math::
           R_{ad}^2 = 1 - \left(\dfrac{\sampleSize}{dof}\right)(1 - R^2)

        where :math:`dof` is the degrees of freedom of the model defined in :eq:`dofWithBase` and :math:`\sampleSize` the number of experiences.

        Otherwise, when the model is defined by :eq:`modelNoBase` or by :eq:`modelWithBase` with an intercept, :math:`R_{ad}^2` is defined by:

        .. math::
           R_{ad}^2 = 1 - \left(\dfrac{\sampleSize - 1}{dof}\right)(1 - R^2)

        where :math:`dof` is defined in :eq:`dofNoBase` or :eq:`dofWithBase`.

        If the degree of freedom :math:`dof` is null, :math:`R_{ad}^2` is not defined.
        """
        return _metamodel.LinearModelResult_getAdjustedRSquared(self)

    def buildMethod(self):
        r"""
        Accessor to the least squares method.

        Returns
        -------
        leastSquaresMethod: :class:`~openturns.LeastSquaresMethod`
            The least squares method.

        Notes
        -----
        The least squares method used to estimate the coefficients is precised in the :class:`~openturns.ResourceMap` class, entry *LinearModelAlgorithm-DecompositionMethod*.
        """
        return _metamodel.LinearModelResult_buildMethod(self)

    def involvesModelSelection(self):
        r"""
        Get the model selection flag.

        A model selection method can be used to select the coefficients
        to best predict the output.
        Model selection can lead to a sparse model.

        Returns
        -------
        involvesModelSelection : bool
            True if the method involves a model selection method.
        """
        return _metamodel.LinearModelResult_involvesModelSelection(self)

    def setInvolvesModelSelection(self, involvesModelSelection):
        r"""
        Set the model selection flag.

        A model selection method can be used to select the coefficients
        to best predict the output.
        Model selection can lead to a sparse model.

        Parameters
        ----------
        involvesModelSelection : bool
            True if the method involves a model selection method.
        """
        return _metamodel.LinearModelResult_setInvolvesModelSelection(self, involvesModelSelection)

    def __init__(self, *args):
        _metamodel.LinearModelResult_swiginit(self, _metamodel.new_LinearModelResult(*args))
    __swig_destroy__ = _metamodel.delete_LinearModelResult

# Register LinearModelResult in _metamodel:
_metamodel.LinearModelResult_swigregister(LinearModelResult)
class MetaModelAlgorithm(openturns.common.PersistentObject):
    r"""
    Base class for metamodel algorithms.

    Parameters
    ----------
    sampleX, sampleY : 2-d sequence of float
        Input/output samples
    distribution : :class:`~openturns.Distribution`, optional
        Joint probability density function of the physical input vector.

    See also
    --------
    LinearModelAlgorithm, GeneralLinearModelAlgorithm, FunctionalChaosAlgorithm
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.MetaModelAlgorithm_getClassName(self)

    def __repr__(self):
        return _metamodel.MetaModelAlgorithm___repr__(self)

    def setDistribution(self, distribution):
        r"""
        Accessor to the joint probability density function of the physical input vector.

        Parameters
        ----------
        distribution : :class:`~openturns.Distribution`
            Joint probability density function of the physical input vector.
        """
        return _metamodel.MetaModelAlgorithm_setDistribution(self, distribution)

    def getDistribution(self):
        r"""
        Accessor to the joint probability density function of the physical input vector.

        Returns
        -------
        distribution : :class:`~openturns.Distribution`
            Joint probability density function of the physical input vector.
        """
        return _metamodel.MetaModelAlgorithm_getDistribution(self)

    def run(self):
        r"""
        Compute the response surfaces.

        Notes
        -----
        It computes the response surfaces and creates a
        :class:`~openturns.MetaModelResult` structure containing all the results.
        """
        return _metamodel.MetaModelAlgorithm_run(self)

    def getInputSample(self):
        r"""
        Accessor to the input sample.

        Returns
        -------
        inputSample : :class:`~openturns.Sample`
            Input sample of a model evaluated apart.
        """
        return _metamodel.MetaModelAlgorithm_getInputSample(self)

    def getOutputSample(self):
        r"""
        Accessor to the output sample.

        Returns
        -------
        outputSample : :class:`~openturns.Sample`
            Output sample of a model evaluated apart.
        """
        return _metamodel.MetaModelAlgorithm_getOutputSample(self)

    def getWeights(self):
        r"""
        Return the weights of the input sample.

        Returns
        -------
        weights : sequence of float
            The weights of the points in the input sample.
        """
        return _metamodel.MetaModelAlgorithm_getWeights(self)

    @staticmethod
    def BuildDistribution(inputSample):
        r"""
        Recover the distribution, with metamodel performance in mind.

        For each marginal, find the best 1-d continuous parametric model
        else fallback to the use of a nonparametric one.

        The selection is done as follow:

          - We start with a list of all parametric models (all factories)
          - For each model, we estimate its parameters if feasible.
          - We check then if model is `valid`, ie if its Kolmogorov score exceeds a threshold 
            fixed in the `MetaModelAlgorithm-PValueThreshold` ResourceMap key. Default value is 5%
          - We sort all `valid` models and return the one with the optimal criterion. 

        For the last step, the criterion might be `BIC`, `AIC` or `AICC`. The specification of the criterion is
        done through the `MetaModelAlgorithm-ModelSelectionCriterion` ResourceMap key. Default value is fixed to `BIC`.
        Note that if there is no `valid` candidate, we estimate a non-parametric model (:class:`~openturns.KernelSmoothing`
        or :class:`~openturns.Histogram`). The `MetaModelAlgorithm-NonParametricModel` ResourceMap key allows selecting
        the preferred one. Default value is `Histogram`

        One each marginal is estimated, we use the Spearman independence test on each component pair to decide whether an 
        independent copula. In case of non independence, we rely on a :class:`~openturns.NormalCopula`.

        Parameters
        ----------
        sample : :class:`~openturns.Sample`
            Input sample.

        Returns
        -------
        distribution : :class:`~openturns.Distribution`
            Input distribution.
        """
        return _metamodel.MetaModelAlgorithm_BuildDistribution(inputSample)

    def __init__(self, *args):
        _metamodel.MetaModelAlgorithm_swiginit(self, _metamodel.new_MetaModelAlgorithm(*args))
    __swig_destroy__ = _metamodel.delete_MetaModelAlgorithm

# Register MetaModelAlgorithm in _metamodel:
_metamodel.MetaModelAlgorithm_swigregister(MetaModelAlgorithm)
class LinearTaylor(openturns.common.PersistentObject):
    r"""
    First order polynomial response surface by Taylor expansion.

    Parameters
    ----------
    center : sequence of float
        Point :math:`\ux_0`.
    function : :class:`~openturns.Function`
        Function :math:`h` to be approximated at the point :math:`\ux_0`.

    Notes
    -----
    The response surface is the first-order Taylor expansion of the function :math:`h` at the point :math:`\ux_0`. Refer to :any:`Taylor Expansion <taylor_expansion>` for details.

    See also
    --------
    QuadraticTaylor, LinearLeastSquares, QuadraticLeastSquares

    Examples
    --------
    >>> import openturns as ot
    >>> formulas = ['x1 * sin(x2)', 'cos(x1 + x2)', '(x2 + 1) * exp(x1 - 2 * x2)']
    >>> myFunc = ot.SymbolicFunction(['x1', 'x2'], formulas)
    >>> myTaylor = ot.LinearTaylor([1, 2], myFunc)
    >>> myTaylor.run()
    >>> responseSurface = myTaylor.getMetaModel()
    >>> print(responseSurface([1.2,1.9]))
    [1.13277,-1.0041,0.204127]
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.LinearTaylor_getClassName(self)

    def __repr__(self):
        return _metamodel.LinearTaylor___repr__(self)

    def run(self):
        r"""Perform the first-order Taylor expansion around :math:`\ux_0`."""
        return _metamodel.LinearTaylor_run(self)

    def getCenter(self):
        r"""
        Get the center.

        Returns
        -------
        center : :class:`~openturns.Point`
            Point :math:`\ux_0` where the Taylor expansion of the function is
            performed.
        """
        return _metamodel.LinearTaylor_getCenter(self)

    def getConstant(self):
        r"""
        Get the constant vector of the approximation.

        Returns
        -------
        constantVector : :class:`~openturns.Point`
            Point :math:`h(\ux_0)`.
        """
        return _metamodel.LinearTaylor_getConstant(self)

    def getLinear(self):
        r"""
        Get the gradient of the function at :math:`\ux_0`.

        Returns
        -------
        gradient : :class:`~openturns.Matrix`
            The matrix :math:`\mat{L}`.
        """
        return _metamodel.LinearTaylor_getLinear(self)

    def getInputFunction(self):
        r"""
        Get the function.

        Returns
        -------
        function : :class:`~openturns.Function`
            Function :math:`h` to be approximated.
        """
        return _metamodel.LinearTaylor_getInputFunction(self)

    def getMetaModel(self):
        r"""
        Get the polynomial approximation of the function.

        Returns
        -------
        approximation : :class:`~openturns.Function`
            The first-order Taylor expansiosn of :math:`h` at :math:`\ux_0`.
        """
        return _metamodel.LinearTaylor_getMetaModel(self)

    def __init__(self, *args):
        _metamodel.LinearTaylor_swiginit(self, _metamodel.new_LinearTaylor(*args))
    __swig_destroy__ = _metamodel.delete_LinearTaylor

# Register LinearTaylor in _metamodel:
_metamodel.LinearTaylor_swigregister(LinearTaylor)
class QuadraticTaylor(openturns.common.PersistentObject):
    r"""
    Second-order Taylor expansion.

    Parameters
    ----------
    center : sequence of float
        Point :math:`\ux_0`.
    function : :class:`~openturns.Function`
        Function :math:`h` to be approximated at the point :math:`\ux_0`.

    Notes
    -----
    The response surface is the second-order Taylor expansion of the function :math:`h` at the point :math:`\ux_0`. Refer to :any:`Taylor Expansion <taylor_expansion>` for details.

    See also
    --------
    LinearTaylor, LinearLeastSquares, QuadraticLeastSquares

    Examples
    --------
    >>> import openturns as ot
    >>> formulas = ['x1 * sin(x2)', 'cos(x1 + x2)', '(x2 + 1) * exp(x1 - 2 * x2)']
    >>> myFunc = ot.SymbolicFunction(['x1', 'x2'], formulas)
    >>> myTaylor = ot.QuadraticTaylor([1, 2], myFunc)
    >>> myTaylor.run()
    >>> responseSurface = myTaylor.getMetaModel()
    >>> print(responseSurface([1.2,1.9]))
    [1.13655,-0.999155,0.214084]
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.QuadraticTaylor_getClassName(self)

    def __repr__(self):
        return _metamodel.QuadraticTaylor___repr__(self)

    def run(self):
        r"""Perform the second-order Taylor expansion around :math:`\ux_0`."""
        return _metamodel.QuadraticTaylor_run(self)

    def getCenter(self):
        r"""
        Get the center.

        Returns
        -------
        center : :class:`~openturns.Point`
            Point :math:`\ux_0` where the Taylor expansion of the function is
            performed.
        """
        return _metamodel.QuadraticTaylor_getCenter(self)

    def getConstant(self):
        r"""
        Get the constant vector of the approximation.

        Returns
        -------
        constantVector : :class:`~openturns.Point`
            Point :math:`h(\ux_0)`.
        """
        return _metamodel.QuadraticTaylor_getConstant(self)

    def getLinear(self):
        r"""
        Get the gradient of the function at :math:`\ux_0`.

        Returns
        -------
        gradient : :class:`~openturns.Matrix`
            The matrix :math:`\mat{L}`.
        """
        return _metamodel.QuadraticTaylor_getLinear(self)

    def getQuadratic(self):
        r"""
        Get the hessian of the function at :math:`\ux_0`.

        Returns
        -------
        tensor : :class:`~openturns.SymmetricTensor`
            The tensor :math:`\mat{Q}`.
        """
        return _metamodel.QuadraticTaylor_getQuadratic(self)

    def getInputFunction(self):
        r"""
        Get the function.

        Returns
        -------
        function : :class:`~openturns.Function`
            Function :math:`h` to be approximated.
        """
        return _metamodel.QuadraticTaylor_getInputFunction(self)

    def getMetaModel(self):
        r"""
        Get the polynomial approximation of the function.

        Returns
        -------
        approximation : :class:`~openturns.Function`
            The second-order Taylor expansion of :math:`h` at :math:`\ux_0`.
        """
        return _metamodel.QuadraticTaylor_getMetaModel(self)

    def __init__(self, *args):
        _metamodel.QuadraticTaylor_swiginit(self, _metamodel.new_QuadraticTaylor(*args))
    __swig_destroy__ = _metamodel.delete_QuadraticTaylor

# Register QuadraticTaylor in _metamodel:
_metamodel.QuadraticTaylor_swigregister(QuadraticTaylor)
class LinearLeastSquares(openturns.common.PersistentObject):
    r"""
    First order polynomial response surface by least squares.

    Parameters
    ----------
    dataIn : 2-d sequence of float
        Input data.
    dataOut : 2-d sequence of float
        Output data.`.

    Notes
    -----
    A least squares meta model provides an approximation of the model which is valid over its whole domain of definition.

    This class estimates the meta model :math:`\metaModel: \Rset^\inputDim \rightarrow \Rset^\outputDim` defined by: 

    .. math::
        :label: LinearLeastSquaresMMOpenTURNSAPI

        \metaModel(\vect{x})  =  \vect{c} + \Tr{\mat{L}}(\vect{x} - \vect{b})

    from an experimental design :math:`\cX` of size :math:`\sampleSize`, that is, a set of observations of
    the input vector defined by:

    .. math::
        :label: inputDataLLS

        \cX = \left\{ \vect{x}^{(1)}, \dots, \vect{x}^{(\sampleSize)} \right\},

    and the corresponding output vectors:

    .. math::
        :label: outputDataLLS

        \cY = \left\{ \vect{y}^{(1)}, \dots, \vect{y}^{(\sampleSize)} \right\}.

    where :math:`\vect{y}^{(k)} = \model{ \vect{x}^{(k)}}`. 

    Refer to :any:`least_squares` to get details on general least squares meta models and to get information on the
    estimation of the matrix :math:`\mat{M} \in \cM_{\inputDim, \outputDim}`, the center vector
    :math:`\vect{b}\in \Rset^\inputDim` and the constant vector :math:`\vect{c} \in \Rset^\outputDim`.


    See also
    --------
    QuadraticLeastSquares, LinearTaylor, QuadraticTaylor

    Examples
    --------
    >>> import openturns as ot
    >>> formulas = ['cos(x1 + x2)', '(x2 + 1) * exp(x1 - 2 * x2)']
    >>> f = ot.SymbolicFunction(['x1', 'x2'], formulas)
    >>> X  = [[0.5,0.5], [-0.5,-0.5], [-0.5,0.5], [0.5,-0.5]]
    >>> X += [[0.25,0.25], [-0.25,-0.25], [-0.25,0.25], [0.25,-0.25]]
    >>> Y = f(X)
    >>> algo = ot.LinearLeastSquares(X, Y)
    >>> algo.run()
    >>> mm = algo.getResult().getMetaModel()
    >>> x = [0.1, 0.1]
    >>> y = mm(x)

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.LinearLeastSquares_getClassName(self)

    def __repr__(self):
        return _metamodel.LinearLeastSquares___repr__(self)

    def run(self):
        r"""Perform the least squares approximation."""
        return _metamodel.LinearLeastSquares_run(self)

    def getCenter(self):
        r"""
        Get the centering vector of the approximation.

        Returns
        -------
        centerVector : :class:`~openturns.Point`
            Centering vector of the approximation, equal to :math:`c`.

        """
        return _metamodel.LinearLeastSquares_getCenter(self)

    def getConstant(self):
        r"""
        Get the constant vector of the approximation.

        Returns
        -------
        constantVector : :class:`~openturns.Point`
            Constant vector :math:`\vect{c}`.

        Notes
        -----
        The constant vector :math:`\vect{c}` is defined in :eq:`LinearLeastSquaresMMOpenTURNSAPI`.

        """
        return _metamodel.LinearLeastSquares_getConstant(self)

    def getLinear(self):
        r"""
        Get the linear matrix of the approximation.

        Returns
        -------
        linearMatrix : :class:`~openturns.Matrix`
            Linear matrix  :math:`\mat{L}`.

        Notes
        -----
        The linear matrix :math:`\mat{L}` is defined in :eq:`LinearLeastSquaresMMOpenTURNSAPI`.

        """
        return _metamodel.LinearLeastSquares_getLinear(self)

    def getResult(self):
        r"""
        Get the meta model result class.

        Returns
        -------
        result : :class:`~openturns.MetaModelResult`
            The class that contains all the results on the meta model. 

        Notes
        -----
        To get the meta model :math:`\metaModel` defined in :eq:`LinearLeastSquaresMMOpenTURNSAPI`
        as a :class:`~openturns.Function`, use the :meth:`~openturns.MetaModelResult.getMetaModel` method.

        """
        return _metamodel.LinearLeastSquares_getResult(self)

    def getMetaModel(self):
        return _metamodel.LinearLeastSquares_getMetaModel(self)

    def getInputSample(self):
        r"""
        Get the input data.

        Returns
        -------
        dataIn : :class:`~openturns.Sample`
            Input data.

        Notes
        -----
        The input experimental design is defined in :eq:`inputDataLLS`.
        """
        return _metamodel.LinearLeastSquares_getInputSample(self)

    def getDataIn(self):
        return _metamodel.LinearLeastSquares_getDataIn(self)

    def getOutputSample(self):
        r"""
        Get the output data.

        Returns
        -------
        dataOut : :class:`~openturns.Sample`
            Output data.

        Notes
        -----
        The output experimental design is defined in :eq:`outputDataLLS`.
        """
        return _metamodel.LinearLeastSquares_getOutputSample(self)

    def setDataOut(self, dataOut):
        r"""
        Set the output data.

        Parameters
        ----------
        dataOut : 2-d sequence of float
            Output data.
        """
        return _metamodel.LinearLeastSquares_setDataOut(self, dataOut)

    def getDataOut(self):
        return _metamodel.LinearLeastSquares_getDataOut(self)

    def __init__(self, *args):
        _metamodel.LinearLeastSquares_swiginit(self, _metamodel.new_LinearLeastSquares(*args))
    __swig_destroy__ = _metamodel.delete_LinearLeastSquares

# Register LinearLeastSquares in _metamodel:
_metamodel.LinearLeastSquares_swigregister(LinearLeastSquares)
class QuadraticLeastSquares(openturns.common.PersistentObject):
    r"""
    Second order polynomial response surface by least squares.

    Parameters
    ----------
    dataIn : 2-d sequence of float
        Input data.
    dataOut : 2-d sequence of float
        Output data.

    Notes
    -----
    A least squares meta model provides an approximation of the model which is valid over its whole domain of definition.

    This class estimates the meta model :math:`\metaModel: \Rset^\inputDim \rightarrow \Rset^\outputDim` defined by: 

    .. math::
        :label: QuadraticLeastSquaresMMOpenTURNSAPI

        \metaModel(\vect{x}) = \vect{c} + \Tr{\mat{L}} ( \vect{x} - \vect{b} ) + \frac{1}{2} \Tr{( \vect{x} - \vect{b} )}\tens{M} ( \vect{x} - \vect{b} )

    from an experimental design :math:`\cX` of size :math:`\sampleSize`, that is, a set of observations of
    the input vector defined by:

    .. math::
        :label: inputDataQLS

        \cX = \left\{ \vect{x}^{(1)}, \dots, \vect{x}^{(\sampleSize)} \right\},

    and the corresponding output vectors:

    .. math::
        :label: outputDataQLS

        \cY = \left\{ \vect{y}^{(1)}, \dots, \vect{y}^{(\sampleSize)} \right\}.

    where :math:`\vect{y}^{(k)} = \model{ \vect{x}^{(k)}}`. 

    Refer to :any:`least_squares` to get details on general least squares meta models and to get information on the
    estimation of the symmetric tensor :math:`\tens{M} \in \Rset^\outputDim \times
    \Rset^\inputDim \times \Rset^\inputDim`,  the matrix :math:`\mat{L} \in \cM_{\inputDim, \outputDim}`, the center
    vector :math:`\vect{b}\in \Rset^\inputDim` and the constant vector :math:`\vect{c} \in \Rset^\outputDim`.

    See also
    --------
    LinearLeastSquares, LinearTaylor, QuadraticTaylor

    Examples
    --------
    >>> import openturns as ot
    >>> formulas = ['x1 * sin(x2)', 'cos(x1 + x2)', '(x2 + 1) * exp(x1 - 2 * x2)']
    >>> f = ot.SymbolicFunction(['x1', 'x2'], formulas)
    >>> X  = [[0.5,0.5], [-0.5,-0.5], [-0.5,0.5], [0.5,-0.5]]
    >>> X += [[0.25,0.25], [-0.25,-0.25], [-0.25,0.25], [0.25,-0.25]]
    >>> Y = f(X)
    >>> algo = ot.QuadraticLeastSquares(X, Y)
    >>> algo.run()
    >>> mm = algo.getResult().getMetaModel()
    >>> x = [0.1, 0.1]
    >>> y = mm(x)

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.QuadraticLeastSquares_getClassName(self)

    def __repr__(self):
        return _metamodel.QuadraticLeastSquares___repr__(self)

    def run(self):
        r"""Perform the least squares approximation."""
        return _metamodel.QuadraticLeastSquares_run(self)

    def getResult(self):
        r"""
        Get the meta model result class.

        Returns
        -------
        result : :class:`~openturns.MetaModelResult`
            The class that contains all the results on the meta model. 

        Notes
        -----
        To get the meta model :math:`\metaModel` defined in :eq:`QuadraticLeastSquaresMMOpenTURNSAPI` as a :class:`~openturns.Function`, use the :meth:`~openturns.MetaModelResult.getMetaModel` method.

        """
        return _metamodel.QuadraticLeastSquares_getResult(self)

    def getCenter(self):
        r"""
        Get the centering vector of the approximation.

        Returns
        -------
        centerVector : :class:`~openturns.Point`
            Centering vector of the approximation, equal to :math:`c`.

        """
        return _metamodel.QuadraticLeastSquares_getCenter(self)

    def getConstant(self):
        r"""
        Get the constant vector of the approximation.

        Returns
        -------
        constantVector : :class:`~openturns.Point`
            Constant  vector :math:`\vect{c}`.

        Notes
        -----
        The constant vector :math:`\vect{c}` is defined in :eq:`QuadraticLeastSquaresMMOpenTURNSAPI`.

        """
        return _metamodel.QuadraticLeastSquares_getConstant(self)

    def getLinear(self):
        r"""
        Get the linear matrix of the approximation.

        Returns
        -------
        linearMatrix : :class:`~openturns.Matrix`
            Linear matrix  :math:`\mat{L}`.

        Notes
        -----
        The linear matrix :math:`\mat{L}` is defined in :eq:`QuadraticLeastSquaresMMOpenTURNSAPI`.

        """
        return _metamodel.QuadraticLeastSquares_getLinear(self)

    def getQuadratic(self):
        r"""
        Get the quadratic term of the approximation.

        Returns
        -------
        tensor : :class:`~openturns.SymmetricTensor`
            Symmetric tensor :math:`\tens{M}`.

        Notes
        -----
        The symmetric tensor :math:`\tens{M}` is defined in :eq:`QuadraticLeastSquaresMMOpenTURNSAPI`.

        """
        return _metamodel.QuadraticLeastSquares_getQuadratic(self)

    def getMetaModel(self):
        return _metamodel.QuadraticLeastSquares_getMetaModel(self)

    def getInputSample(self):
        r"""
        Get the input data.

        Returns
        -------
        dataIn : :class:`~openturns.Sample`
            Input data.

        Notes
        -----
        The input experimental design is defined in :eq:`inputDataQLS`.
        """
        return _metamodel.QuadraticLeastSquares_getInputSample(self)

    def getDataIn(self):
        return _metamodel.QuadraticLeastSquares_getDataIn(self)

    def getOutputSample(self):
        r"""
        Get the output data.

        Returns
        -------
        dataOut : :class:`~openturns.Sample`
            Output data.

        Notes
        -----
        The output experimental design is defined in :eq:`outputDataQLS`.
        """
        return _metamodel.QuadraticLeastSquares_getOutputSample(self)

    def setDataOut(self, dataOut):
        r"""
        Set the output data.

        Parameters
        ----------
        dataOut : 2-d sequence of float
            Output data.
        """
        return _metamodel.QuadraticLeastSquares_setDataOut(self, dataOut)

    def getDataOut(self):
        return _metamodel.QuadraticLeastSquares_getDataOut(self)

    def __init__(self, *args):
        _metamodel.QuadraticLeastSquares_swiginit(self, _metamodel.new_QuadraticLeastSquares(*args))
    __swig_destroy__ = _metamodel.delete_QuadraticLeastSquares

# Register QuadraticLeastSquares in _metamodel:
_metamodel.QuadraticLeastSquares_swigregister(QuadraticLeastSquares)
class AdaptiveStrategyImplementation(openturns.common.PersistentObject):
    r"""
    Base class for the construction of the truncated multivariate orthogonal basis.

    Parameters
    ----------
    orthogonalBasis : :class:`~openturns.OrthogonalBasis`
        An OrthogonalBasis.
    dimension : positive int
        Number of terms of the basis. This first usage has the same implementation
        as the second with a :class:`~openturns.FixedStrategy`. 

    See also
    --------
    FunctionalChaosAlgorithm, FixedStrategy, CleaningStrategy

    Notes
    -----
    A strategy must be chosen for the selection of the different terms of the
    multivariate basis in which the response surface by functional chaos is expressed.
    The selected terms are regrouped in the finite subset :math:`K` of :math:`\Nset`.

    There are two different strategies available:

    - :class:`~openturns.FixedStrategy`,
    - :class:`~openturns.CleaningStrategy`.

    These strategies are conceived in such a way to be adapted for other orthogonal
    expansions (other than polynomial). For the moment, their implementation are
    only useful for the functional chaos expansion.
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.AdaptiveStrategyImplementation_getClassName(self)

    def setMaximumDimension(self, maximumDimension):
        r"""
        Accessor to the maximum dimension of the orthogonal basis.

        Parameters
        ----------
        maximumDimension : int
            Maximum dimension of the truncated basis.
        """
        return _metamodel.AdaptiveStrategyImplementation_setMaximumDimension(self, maximumDimension)

    def getMaximumDimension(self):
        r"""
        Accessor to the maximum dimension of the orthogonal basis.

        Returns
        -------
        maximumDimension : int
            Maximum dimension of the truncated basis.
        """
        return _metamodel.AdaptiveStrategyImplementation_getMaximumDimension(self)

    def computeInitialBasis(self):
        r"""
        Compute initial basis for the approximation.

        See also
        --------
        getPsi
        """
        return _metamodel.AdaptiveStrategyImplementation_computeInitialBasis(self)

    def updateBasis(self, alpha_k, residual, relativeError):
        r"""
        Update the basis for the next iteration of approximation.

        Parameters
        ----------
        alpha_k: sequence of floats
            The coefficients of the expansion at this step.
        residual: float
            The current value of the residual.
        relativeError: float
            The relative error.
        """
        return _metamodel.AdaptiveStrategyImplementation_updateBasis(self, alpha_k, residual, relativeError)

    def __repr__(self):
        return _metamodel.AdaptiveStrategyImplementation___repr__(self)

    def getBasis(self):
        r"""
        Accessor to the underlying orthogonal basis.

        Returns
        -------
        basis : :class:`~openturns.OrthogonalBasis`
            Orthogonal basis of which the adaptive strategy is based.
        """
        return _metamodel.AdaptiveStrategyImplementation_getBasis(self)

    def getPsi(self):
        r"""
        Accessor to the selected orthogonal polynomials in the basis.

        The value returned by this method depends on the specific
        choice of adaptive strategy and the previous calls to the
        :meth:`updateBasis` method.

        Returns
        -------
        polynomials : list of polynomials
            Sequence of :math:`P` polynomials.

        Notes
        -----
        The method :meth:`computeInitialBasis` must be applied first.

        Examples
        --------
        >>> import openturns as ot
        >>> productBasis = ot.OrthogonalProductPolynomialFactory([ot.HermiteFactory()])
        >>> adaptiveStrategy = ot.FixedStrategy(productBasis, 3)
        >>> adaptiveStrategy.computeInitialBasis()
        >>> print(adaptiveStrategy.getPsi())
        [1,x0,-0.707107 + 0.707107 * x0^2]
        """
        return _metamodel.AdaptiveStrategyImplementation_getPsi(self)

    def involvesModelSelection(self):
        r"""
        Get the model selection flag.

        A model selection method can be used to select the coefficients
        of the decomposition which enable to best predict the output.
        Model selection can lead to a sparse functional chaos expansion.

        Returns
        -------
        involvesModelSelection : bool
            True if the method involves a model selection method.
        """
        return _metamodel.AdaptiveStrategyImplementation_involvesModelSelection(self)

    def __init__(self, *args):
        _metamodel.AdaptiveStrategyImplementation_swiginit(self, _metamodel.new_AdaptiveStrategyImplementation(*args))
    __swig_destroy__ = _metamodel.delete_AdaptiveStrategyImplementation

# Register AdaptiveStrategyImplementation in _metamodel:
_metamodel.AdaptiveStrategyImplementation_swigregister(AdaptiveStrategyImplementation)
class FixedStrategy(AdaptiveStrategyImplementation):
    r"""
    Fixed truncation strategy.

    Parameters
    ----------
    orthogonalBasis : :class:`~openturns.OrthogonalBasis`
        An OrthogonalBasis.
    dimension : positive int
        Number of terms of the basis.

    See also
    --------
    AdaptiveStrategy, CleaningStrategy

    Notes
    -----
    The so-called fixed strategy simply consists in selecting the first :math:`P`
    elements of the PC basis, the latter being ordered according to a given
    :class:`~openturns.EnumerateFunction` (hyperbolic or not). The retained set is
    built in a single pass. The truncated PC expansion is given by:

    .. math::

        \widehat{h} (\uZ) = \sum_{j=0}^{P-1} \vect{a}_j \Psi_j (\uZ)

    In case of a :class:`~openturns.LinearEnumerateFunction`, for a given natural
    integer :math:`p` representing the total polynomial degree, the number of
    coefficients is equal to:

    .. math::

        P = \binom{n_X + p}{p} = \frac{(n_X + p)!}{n_X!\,p!}

    where :math:`n_X` is the input dimension.
    This way the set of retained basis functions :math:`\{\Psi_j, j = 0, \ldots, P-1\}`
    gathers all the polynomials with total degree not greater than :math:`p`.
    The number of terms :math:`P` grows polynomially both in :math:`n_X` and :math:`p`
    though, which may lead to difficulties in terms of computational efficiency and
    memory requirements when dealing with high-dimensional problems.

    Examples
    --------
    >>> import openturns as ot
    >>> ot.RandomGenerator.SetSeed(0)
    >>> # Define the model
    >>> inputDim = 1
    >>> model = ot.SymbolicFunction(['x'], ['x*sin(x)'])
    >>> # Create the input distribution
    >>> distribution = ot.JointDistribution([ot.Uniform()]*inputDim)
    >>> # Construction of the multivariate orthonormal basis
    >>> polyColl = [0.0]*inputDim
    >>> for i in range(distribution.getDimension()):
    ...     polyColl[i] = ot.StandardDistributionPolynomialFactory(distribution.getMarginal(i))
    >>> enumerateFunction = ot.LinearEnumerateFunction(inputDim)
    >>> productBasis = ot.OrthogonalProductPolynomialFactory(polyColl, enumerateFunction)
    >>> # Truncature strategy of the multivariate orthonormal basis
    >>> # We choose all the polynomials of degree <= 4
    >>> degree = 4
    >>> indexMax = enumerateFunction.getStrataCumulatedCardinal(degree)
    >>> print(indexMax)
    5
    >>> # We keep all the polynomials of degree <= 4
    >>> # which corresponds to the 5 first ones
    >>> adaptiveStrategy = ot.FixedStrategy(productBasis, indexMax)

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.FixedStrategy_getClassName(self)

    def computeInitialBasis(self):
        r"""
        Compute initial basis for the approximation.

        See also
        --------
        getPsi
        """
        return _metamodel.FixedStrategy_computeInitialBasis(self)

    def updateBasis(self, alpha_k, residual, relativeError):
        r"""
        Update the basis for the next iteration of approximation.

        No changes are made to the basis in the fixed strategy.
        Hence, the number of functions in the basis is equal to *dimension*,
        whatever the number of calls to the *updateBasis* method.

        Parameters
        ----------
        alpha_k : sequence of floats
            The coefficients of the expansion at this step.
        residual : float
            The current value of the residual.
        relativeError : float
            The relative error.
        """
        return _metamodel.FixedStrategy_updateBasis(self, alpha_k, residual, relativeError)

    def involvesModelSelection(self):
        r"""
        Get the model selection flag.

        A model selection method can be used to select the coefficients
        of the decomposition which enable to best predict the output.
        Model selection can lead to a sparse functional chaos expansion.

        Returns
        -------
        involvesModelSelection : bool
            True if the method involves a model selection method.
        """
        return _metamodel.FixedStrategy_involvesModelSelection(self)

    def __repr__(self):
        return _metamodel.FixedStrategy___repr__(self)

    def __init__(self, *args):
        _metamodel.FixedStrategy_swiginit(self, _metamodel.new_FixedStrategy(*args))
    __swig_destroy__ = _metamodel.delete_FixedStrategy

# Register FixedStrategy in _metamodel:
_metamodel.FixedStrategy_swigregister(FixedStrategy)
class CleaningStrategy(AdaptiveStrategyImplementation):
    r"""
    Cleaning truncation strategy.

    Available constructors:
        CleaningStrategy(*orthogonalBasis, maximumDimension*)

        CleaningStrategy(*orthogonalBasis, maximumDimension, maximumSize, 
        significanceFactor*)

    Parameters
    ----------
    orthogonalBasis : :class:`~openturns.OrthogonalBasis`
        An OrthogonalBasis.
    maximumDimension : positive int
        Maximum index of the basis function that can be used by the :class:`~openturns.EnumerateFunction`.
    maximumSize : positive int, :math:`maximumSize \leq maximumDimension`
        Maximum number of functions used in the meta model.
        Its default value is the `CleaningStrategy-DefaultMaximumSize` key of
        the :class:`~openturns.ResourceMap`.
    significanceFactor : float 
        Parameter used as a threshold factor for selecting the efficient coefficients of
        the basis. The actual threshold is the product of the
        *significanceFactor* with the maximum magnitude of the current
        coefficients.
        Its default value is the `CleaningStrategy-DefaultSignificanceFactor` key of
        the :class:`~openturns.ResourceMap`.

    See also
    --------
    AdaptiveStrategy, FixedStrategy

    Notes
    -----
    The cleaning strategy aims at building a PC expansion containing
    only a subset of the coefficients of the full expansion.
    Hence, this strategy can lead to a sparse expansion which can
    limit the chances of potential surrogate model overfitting.

    Let *maximumDimension* be the number of coefficients in the full expansion
    and let *maximumSize* be the maximum number of coefficients defined
    by the user. On output, at most *maximumSize*
    coefficients are selected.
    Let :math:`\epsilon` be the value of the *significanceFactor*.
    The method proceeds as follows:

    - Generate an initial PC basis made of the *maximumSize* first functions
      (according to the adopted :class:`~openturns.EnumerateFunction`), or
      equivalently an initial set of indices :math:`\cK = \{0, \ldots, maximumSize - 1\}`.

    - Discard from the basis any function :math:`\Psi_j` associated with 
      an insignificant coefficient :math:`a_j`, i.e. such that:

    .. math::

        |a_j| \leq \epsilon \max_{ k \in \cK, k \neq 0 } |a_k|.

    - Add the next function to the current basis :math:`\cK` according to the :class:`~openturns.EnumerateFunction` used.
    - Reiterate the procedure until the first *maximumDimension* functions have been considered.


    Examples
    --------
    In the next example, we select, among the `maximumDimension = 100` first polynomials of
    the multivariate basis, those which have the `maximumSize = 20` most
    significant contribution (greatest absolute value of the coefficients), with respect to the
    significance factor :math:`10^{-4}`.

    >>> import openturns as ot
    >>> ot.RandomGenerator.SetSeed(0)
    >>> # Define the model
    >>> inputDim = 1
    >>> model = ot.SymbolicFunction(['x'], ['x*sin(x)'])
    >>> # Create the input distribution
    >>> distribution = ot.JointDistribution([ot.Uniform()]*inputDim)
    >>> # Construction of the multivariate orthonormal basis
    >>> polyColl = [0.0]*inputDim
    >>> for i in range(distribution.getDimension()):
    ...     polyColl[i] = ot.StandardDistributionPolynomialFactory(distribution.getMarginal(i))
    >>> enumerateFunction = ot.LinearEnumerateFunction(inputDim)
    >>> productBasis = ot.OrthogonalProductPolynomialFactory(polyColl, enumerateFunction)
    >>> maximumDimension = 100
    >>> maximumSize = 20
    >>> significanceFactor = 1e-4
    >>> adaptiveStrategy = ot.CleaningStrategy(
    ...     productBasis, maximumDimension, maximumSize, significanceFactor
    ... )

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.CleaningStrategy_getClassName(self)

    def computeInitialBasis(self):
        r"""
        Compute initial basis for the approximation.

        See also
        --------
        getPsi
        """
        return _metamodel.CleaningStrategy_computeInitialBasis(self)

    def updateBasis(self, alpha_k, residual, relativeError):
        r"""
        Update the basis for the next iteration of approximation.

        In this strategy, the *residual* and the *relativeError* input arguments
        are ignored.

        Parameters
        ----------
        alpha_k : sequence of floats
            The coefficients of the expansion at this step.
        residual : float
            The current value of the residual. Ignored.
        relativeError : float
            The relative error. Ignored.

        Examples
        --------
        >>> import openturns as ot
        >>> dimension = 3
        >>> enumerateFunction = ot.LinearEnumerateFunction(dimension)
        >>> productBasis = ot.OrthogonalProductPolynomialFactory(
        ...     [ot.LegendreFactory()] * dimension, enumerateFunction
        ... )
        >>> degree = 6
        >>> basisSize = enumerateFunction.getBasisSizeFromTotalDegree(degree)
        >>> maximumDimension = 100
        >>> maximumSize = 20
        >>> significanceFactor = 1e-4
        >>> adaptiveStrategy = ot.CleaningStrategy(
        ...     productBasis, maximumDimension, maximumSize, significanceFactor
        ... )
        >>> adaptiveStrategy.computeInitialBasis()
        >>> print(adaptiveStrategy.getCurrentVectorIndex())
        20
        >>> psi = adaptiveStrategy.getPsi()
        >>> print(len(psi))
        20
        >>> alpha_k = [3.5, 0.1, 0.0, -0.2, 0.0, 0.3, 0.0, -0.4, 0.0, -0.5]
        >>> residual = 0.0  # Ignored
        >>> relativeError = 0.0  # Ignored
        >>> adaptiveStrategy.updateBasis(alpha_k, residual, relativeError)
        >>> psi = adaptiveStrategy.getPsi()
        >>> print(len(psi))
        7
        """
        return _metamodel.CleaningStrategy_updateBasis(self, alpha_k, residual, relativeError)

    def __repr__(self):
        return _metamodel.CleaningStrategy___repr__(self)

    def getCurrentVectorIndex(self):
        r"""
        Accessor to the current vector index.

        Returns
        -------
        index : int
            Current index of the basis term.
        """
        return _metamodel.CleaningStrategy_getCurrentVectorIndex(self)

    def getMaximumSize(self):
        r"""
        Accessor to the maximum number of functions used.

        Returns
        -------
        maximumSize : int
            Maximum number of significant terms of the basis.

        See also
        --------
        setMaximumSize
        """
        return _metamodel.CleaningStrategy_getMaximumSize(self)

    def setMaximumSize(self, maximumSize):
        r"""
        Accessor to the maximum number of functions used.

        Parameters
        ----------
        maximumSize : int
            Maximum number of significant terms of the basis.

        See also
        --------
        getMaximumSize
        """
        return _metamodel.CleaningStrategy_setMaximumSize(self, maximumSize)

    def getSignificanceFactor(self):
        r"""
        Accessor to the significance factor.

        Returns
        -------
        significanceFactor : float
            Value of the significance factor.

        See also
        --------
        setSignificanceFactor
        """
        return _metamodel.CleaningStrategy_getSignificanceFactor(self)

    def setSignificanceFactor(self, significanceFactor):
        r"""
        Accessor to the significance factor.

        Parameters
        ----------
        significanceFactor : float
            Value of the significance factor.

        See also
        --------
        getSignificanceFactor
        """
        return _metamodel.CleaningStrategy_setSignificanceFactor(self, significanceFactor)

    def involvesModelSelection(self):
        r"""
        Get the model selection flag.

        A model selection method can be used to select the coefficients
        of the decomposition which enable to best predict the output.
        Model selection can lead to a sparse functional chaos expansion.

        Returns
        -------
        involvesModelSelection : bool
            True if the method involves a model selection method.
        """
        return _metamodel.CleaningStrategy_involvesModelSelection(self)

    def __init__(self, *args):
        _metamodel.CleaningStrategy_swiginit(self, _metamodel.new_CleaningStrategy(*args))
    __swig_destroy__ = _metamodel.delete_CleaningStrategy

# Register CleaningStrategy in _metamodel:
_metamodel.CleaningStrategy_swigregister(CleaningStrategy)
class _AdaptiveStrategyImplementationTypedInterfaceObject(openturns.common.InterfaceObject):
    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __repr__ = _swig_repr

    def __init__(self, *args):
        _metamodel._AdaptiveStrategyImplementationTypedInterfaceObject_swiginit(self, _metamodel.new__AdaptiveStrategyImplementationTypedInterfaceObject(*args))

    def getImplementation(self):
        r"""
        Accessor to the underlying implementation.

        Returns
        -------
        impl : Implementation
            A copy of the underlying implementation object.
        """
        return _metamodel._AdaptiveStrategyImplementationTypedInterfaceObject_getImplementation(self)

    def setName(self, name):
        r"""
        Accessor to the object's name.

        Parameters
        ----------
        name : str
            The name of the object.
        """
        return _metamodel._AdaptiveStrategyImplementationTypedInterfaceObject_setName(self, name)

    def getName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        name : str
            The name of the object.
        """
        return _metamodel._AdaptiveStrategyImplementationTypedInterfaceObject_getName(self)

    def __eq__(self, other):
        return _metamodel._AdaptiveStrategyImplementationTypedInterfaceObject___eq__(self, other)

    def __ne__(self, other):
        return _metamodel._AdaptiveStrategyImplementationTypedInterfaceObject___ne__(self, other)
    __swig_destroy__ = _metamodel.delete__AdaptiveStrategyImplementationTypedInterfaceObject

# Register _AdaptiveStrategyImplementationTypedInterfaceObject in _metamodel:
_metamodel._AdaptiveStrategyImplementationTypedInterfaceObject_swigregister(_AdaptiveStrategyImplementationTypedInterfaceObject)
class AdaptiveStrategy(_AdaptiveStrategyImplementationTypedInterfaceObject):
    r"""
    Base class for the construction of the truncated multivariate orthogonal basis.

    Parameters
    ----------
    orthogonalBasis : :class:`~openturns.OrthogonalBasis`
        An OrthogonalBasis.
    dimension : positive int
        Number of terms of the basis. This first usage has the same implementation
        as the second with a :class:`~openturns.FixedStrategy`. 

    See also
    --------
    FunctionalChaosAlgorithm, FixedStrategy, CleaningStrategy

    Notes
    -----
    A strategy must be chosen for the selection of the different terms of the
    multivariate basis in which the response surface by functional chaos is expressed.
    The selected terms are regrouped in the finite subset :math:`K` of :math:`\Nset`.

    There are two different strategies available:

    - :class:`~openturns.FixedStrategy`,
    - :class:`~openturns.CleaningStrategy`.

    These strategies are conceived in such a way to be adapted for other orthogonal
    expansions (other than polynomial). For the moment, their implementation are
    only useful for the functional chaos expansion.
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.AdaptiveStrategy_getClassName(self)

    def setMaximumDimension(self, maximumDimension):
        r"""
        Accessor to the maximum dimension of the orthogonal basis.

        Parameters
        ----------
        maximumDimension : int
            Maximum dimension of the truncated basis.
        """
        return _metamodel.AdaptiveStrategy_setMaximumDimension(self, maximumDimension)

    def getMaximumDimension(self):
        r"""
        Accessor to the maximum dimension of the orthogonal basis.

        Returns
        -------
        maximumDimension : int
            Maximum dimension of the truncated basis.
        """
        return _metamodel.AdaptiveStrategy_getMaximumDimension(self)

    def computeInitialBasis(self):
        r"""
        Compute initial basis for the approximation.

        See also
        --------
        getPsi
        """
        return _metamodel.AdaptiveStrategy_computeInitialBasis(self)

    def updateBasis(self, alpha_k, residual, relativeError):
        r"""
        Update the basis for the next iteration of approximation.

        Parameters
        ----------
        alpha_k: sequence of floats
            The coefficients of the expansion at this step.
        residual: float
            The current value of the residual.
        relativeError: float
            The relative error.
        """
        return _metamodel.AdaptiveStrategy_updateBasis(self, alpha_k, residual, relativeError)

    def getBasis(self):
        r"""
        Accessor to the underlying orthogonal basis.

        Returns
        -------
        basis : :class:`~openturns.OrthogonalBasis`
            Orthogonal basis of which the adaptive strategy is based.
        """
        return _metamodel.AdaptiveStrategy_getBasis(self)

    def getPsi(self):
        r"""
        Accessor to the selected orthogonal polynomials in the basis.

        The value returned by this method depends on the specific
        choice of adaptive strategy and the previous calls to the
        :meth:`updateBasis` method.

        Returns
        -------
        polynomials : list of polynomials
            Sequence of :math:`P` polynomials.

        Notes
        -----
        The method :meth:`computeInitialBasis` must be applied first.

        Examples
        --------
        >>> import openturns as ot
        >>> productBasis = ot.OrthogonalProductPolynomialFactory([ot.HermiteFactory()])
        >>> adaptiveStrategy = ot.FixedStrategy(productBasis, 3)
        >>> adaptiveStrategy.computeInitialBasis()
        >>> print(adaptiveStrategy.getPsi())
        [1,x0,-0.707107 + 0.707107 * x0^2]
        """
        return _metamodel.AdaptiveStrategy_getPsi(self)

    def __repr__(self):
        return _metamodel.AdaptiveStrategy___repr__(self)

    def __str__(self, *args):
        return _metamodel.AdaptiveStrategy___str__(self, *args)

    def __init__(self, *args):
        _metamodel.AdaptiveStrategy_swiginit(self, _metamodel.new_AdaptiveStrategy(*args))
    __swig_destroy__ = _metamodel.delete_AdaptiveStrategy

# Register AdaptiveStrategy in _metamodel:
_metamodel.AdaptiveStrategy_swigregister(AdaptiveStrategy)
class ProjectionStrategyImplementation(openturns.common.PersistentObject):
    r"""
    Base class for the evaluation strategies of the approximation coefficients.

    Available constructors:
        ProjectionStrategy(*projectionStrategy*)

    Parameters
    ----------
    projectionStrategy : :class:`~openturns.ProjectionStrategy`
        A projection strategy which is a :class:`~openturns.LeastSquaresStrategy` or
        an :class:`~openturns.IntegrationStrategy`.

    See also
    --------
    FunctionalChaosAlgorithm, LeastSquaresStrategy, IntegrationStrategy

    Notes
    -----
    This class is used in the :any:`functional chaos expansion context <functional_chaos>` implemented
    in the class :class:`~openturns.FunctionalChaosAlgorithm`. It is not usable outside this context. 

    The model is approximated by the meta model defined in :any:`functional_chaos` by equation :eq:`metaModelPn` and the coefficients :math:`(a_k)_{k \in I_n}` are computed by:

    - solving the least squares problem defined in :any:`functional_chaos` by equation
      :eq:`metaModeleF` : use the class
      :class:`~openturns.LeastSquaresStrategy`,
    - computing the inner product defined in :any:`functional_chaos` by equation
      :eq:`scalProd`: use the class
      :class:`~openturns.IntegrationStrategy`. In that case, the basis of the approximation space
      must be orthonormal to the input distribution.


    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.ProjectionStrategyImplementation_getClassName(self)

    def __repr__(self):
        return _metamodel.ProjectionStrategyImplementation___repr__(self)

    def __str__(self, *args):
        return _metamodel.ProjectionStrategyImplementation___str__(self, *args)

    def __repr_markdown__(self):
        return _metamodel.ProjectionStrategyImplementation___repr_markdown__(self)

    def _repr_html_(self):
        return _metamodel.ProjectionStrategyImplementation__repr_html_(self)

    def setMeasure(self, measure):
        r"""
        Accessor to the measure.

        Parameters
        ----------
        m : Distribution
            Measure :math:`\mu_{\inputRV}` defining the scalar product.
        """
        return _metamodel.ProjectionStrategyImplementation_setMeasure(self, measure)

    def getMeasure(self):
        r"""
        Accessor to the measure.

        Returns
        -------
        mu : Distribution
            Measure :math:`\mu_{\inputRV}` defining the inner product.
        """
        return _metamodel.ProjectionStrategyImplementation_getMeasure(self)

    def setInputSample(self, inputSample):
        r"""
        Accessor to the input sample.

        Parameters
        ----------
        X : :class:`~openturns.Sample`
            Input Sample.
        """
        return _metamodel.ProjectionStrategyImplementation_setInputSample(self, inputSample)

    def getInputSample(self):
        r"""
        Accessor to the input sample.

        Returns
        -------
        X : :class:`~openturns.Sample`
            Input Sample.
        """
        return _metamodel.ProjectionStrategyImplementation_getInputSample(self)

    def setOutputSample(self, outputSample):
        r"""
        Accessor to the output sample.

        Parameters
        ----------
        Y : :class:`~openturns.Sample`
            Output Sample.
        """
        return _metamodel.ProjectionStrategyImplementation_setOutputSample(self, outputSample)

    def getOutputSample(self):
        r"""
        Accessor to the output sample.

        Returns
        -------
        Y : :class:`~openturns.Sample`
            Output Sample.
        """
        return _metamodel.ProjectionStrategyImplementation_getOutputSample(self)

    def setWeights(self, weights):
        r"""
        Accessor to the weights.

        Parameters
        ----------
        w : :class:`~openturns.Point`
            Weights of the design of experiments.
        """
        return _metamodel.ProjectionStrategyImplementation_setWeights(self, weights)

    def getWeights(self):
        r"""
        Accessor to the weights.

        Returns
        -------
        w : :class:`~openturns.Point`
            Weights of the design of experiments.
        """
        return _metamodel.ProjectionStrategyImplementation_getWeights(self)

    def getResidual(self):
        r"""
        Accessor to the residual.

        Returns
        -------
        er : float
            Residual error.
        """
        return _metamodel.ProjectionStrategyImplementation_getResidual(self)

    def getRelativeError(self):
        r"""
        Accessor to the relative error.

        Returns
        -------
        e : float
            Relative error.
        """
        return _metamodel.ProjectionStrategyImplementation_getRelativeError(self)

    def getCoefficients(self):
        r"""
        Accessor to the coefficients.

        Returns
        -------
        coef : :class:`~openturns.Point`
            Coefficients :math:`(\alpha_k)_{k \in I_n}`.
        """
        return _metamodel.ProjectionStrategyImplementation_getCoefficients(self)

    def setExperiment(self, weightedExperiment):
        r"""
        Accessor to the design of experiment.

        Parameters
        ----------
        exp : :class:`~openturns.WeightedExperiment`
            Weighted design of experiment.
        """
        return _metamodel.ProjectionStrategyImplementation_setExperiment(self, weightedExperiment)

    def getExperiment(self):
        r"""
        Accessor to the experiments.

        Returns
        -------
        exp : :class:`~openturns.WeightedExperiment`
            Weighted experiment used to evaluate the coefficients.
        """
        return _metamodel.ProjectionStrategyImplementation_getExperiment(self)

    def getDesignProxy(self):
        r"""
        Accessor to the design proxy.

        Parameters
        ----------
        designProxy : :class:`~openturns.DesignProxy`
            The design matrix.
        """
        return _metamodel.ProjectionStrategyImplementation_getDesignProxy(self)

    def isLeastSquares(self):
        r"""
        Get the least squares flag.

        There are two methods to compute the coefficients: integration
        or least squares.

        Returns
        -------
        isLeastSquares : bool
            True if the coefficients are estimated from least squares.
        """
        return _metamodel.ProjectionStrategyImplementation_isLeastSquares(self)

    def involvesModelSelection(self):
        r"""
        Get the model selection flag.

        A model selection method can be used to select the coefficients
        of the decomposition which enable to best predict the output.
        Model selection can lead to a sparse functional chaos expansion.

        Returns
        -------
        involvesModelSelection : bool
            True if the method involves a model selection method.
        """
        return _metamodel.ProjectionStrategyImplementation_involvesModelSelection(self)

    def __init__(self, *args):
        _metamodel.ProjectionStrategyImplementation_swiginit(self, _metamodel.new_ProjectionStrategyImplementation(*args))
    __swig_destroy__ = _metamodel.delete_ProjectionStrategyImplementation

# Register ProjectionStrategyImplementation in _metamodel:
_metamodel.ProjectionStrategyImplementation_swigregister(ProjectionStrategyImplementation)
class LeastSquaresStrategy(ProjectionStrategyImplementation):
    r"""
    Least squares strategy for the approximation coefficients.

    Available constructors:
        LeastSquaresStrategy(*weightedExp*)

        LeastSquaresStrategy(*weightedExp, approxAlgoImpFact*)

        LeastSquaresStrategy(*approxAlgoImpFact*)

        LeastSquaresStrategy(*measure, approxAlgoImpFact*)

        LeastSquaresStrategy(*measure, weightedExp, approxAlgoImpFact*)

        LeastSquaresStrategy(*inputSample, outputSample, approxAlgoImpFact*)

        LeastSquaresStrategy(*inputSample, weights, outputSample, approxAlgoImpFact*)

    Parameters
    ----------
    weightedExp : :class:`~openturns.WeightedExperiment`
        Experimental design used for the transformed input data.

        By default, the class :class:`~openturns.MonteCarloExperiment` is used.
    approxAlgoImpFact : :class:`~openturns.ApproximationAlgorithmImplementationFactory`
        The factory that builds the desired :class:`~openturns.ApproximationAlgorithm`.

        By default, the class :class:`~openturns.PenalizedLeastSquaresAlgorithmFactory` is used.
    measure : :class:`~openturns.Distribution`
        The input distribution :math:`\mu_{\inputRV}`.

        By default, the limit measure defined within the class
        :class:`~openturns.WeightedExperiment` is used.
    inputSample : 2-d sequence of float
        The input sample of size :math:`\sampleSize`.
    outputSample : 2-d sequence of float
        The output sample of size :math:`\sampleSize`.
    weights : sequence of float
        Numerical point that are the weights associated to the input sample points
        such that the corresponding weighted experiment is a good approximation of
        :math:`\mu_{\inputRV}`.

        By default, all weights are equal to
        :math:`\omega_i = \frac{1}{\sampleSize}`.

    See also
    --------
    FunctionalChaosAlgorithm, ProjectionStrategy, IntegrationStrategy

    Notes
    -----
    This class is used in the :any:`functional chaos expansion context <functional_chaos>` implemented
    in the class :class:`~openturns.FunctionalChaosAlgorithm`. It is not usable outside this context.

    The model is approximated by the meta model defined in :any:`functional_chaos` by equation :eq:`metaModelPn`
    and the coefficients :math:`(a_k)_{k \in I_n}` are computed by solving the least squares problem defined in :any:`functional_chaos` by equation :eq:`metaModeleF`.

    Refer to :any:`least_squares` for more details on the resolution of least-squares problem.

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.LeastSquaresStrategy_getClassName(self)

    def __repr__(self):
        return _metamodel.LeastSquaresStrategy___repr__(self)

    def isLeastSquares(self):
        r"""
        Get the least squares flag.

        There are two methods to compute the coefficients: integration
        or least squares.

        Returns
        -------
        isLeastSquares : bool
            True if the coefficients are estimated from least squares.
        """
        return _metamodel.LeastSquaresStrategy_isLeastSquares(self)

    def involvesModelSelection(self):
        r"""
        Get the model selection flag.

        A model selection method can be used to select the coefficients
        of the decomposition which enable to best predict the output.
        Model selection can lead to a sparse functional chaos expansion.

        Returns
        -------
        involvesModelSelection : bool
            True if the method involves a model selection method.
        """
        return _metamodel.LeastSquaresStrategy_involvesModelSelection(self)

    def __init__(self, *args):
        _metamodel.LeastSquaresStrategy_swiginit(self, _metamodel.new_LeastSquaresStrategy(*args))
    __swig_destroy__ = _metamodel.delete_LeastSquaresStrategy

# Register LeastSquaresStrategy in _metamodel:
_metamodel.LeastSquaresStrategy_swigregister(LeastSquaresStrategy)
class IntegrationStrategy(ProjectionStrategyImplementation):
    r"""
    Integration strategy for the approximation coefficients.

    Available constructors:
        IntegrationStrategy(*measure*)

        IntegrationStrategy(*weightedExp*)

        IntegrationStrategy(*measure, weightedExp*)

        IntegrationStrategy(*inputSample, outputSample*)

        IntegrationStrategy(*inputSample, weights, outputSample*)

    Parameters
    ----------
    weightedExp : :class:`~openturns.WeightedExperiment`
        Experimental design used for the transformed input data. 

        By default the class :class:`~openturns.MonteCarloExperiment` is used.
    measure : :class:`~openturns.Distribution`
        The input distribution :math:`\mu_{\inputRV}`
        with respect to which the basis is orthonormal.

        By default, the limit measure defined within the class
        :class:`~openturns.WeightedExperiment` is used.
    inputSample : 2-d sequence of float
        The input sample of size :math:`\sampleSize`.
    outputSample : 2-d sequence of float
        The output sample of size :math:`\sampleSize`.
    weights : sequence of float
        Numerical point that are the weights associated to the input sample points
        such that the corresponding weighted experiment is a good approximation of
        :math:`\mu_{\inputRV}`.

        By default, all weights are equal to
        :math:`\omega_i = \frac{1}{\sampleSize}`.

    See also
    --------
    FunctionalChaosAlgorithm, ProjectionStrategy, LeastSquaresStrategy

    Notes
    -----
    This class is used in the :any:`functional chaos expansion context <functional_chaos>` implemented
    in the class :class:`~openturns.FunctionalChaosAlgorithm`. It is not usable outside this context.

    The model is approximated by the meta model defined in :any:`functional_chaos` by equation :eq:`metaModelPn`
    and the coefficients :math:`a_k)_{k \in I_n}` are computed with the inner product defined in :any:`functional_chaos`
    by equation :eq:`scalProd`. This computation makes sense if and only if the basis is orthonormal with respect to the distribution :math:`\mu_{\inputRV}`.

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.IntegrationStrategy_getClassName(self)

    def __repr__(self):
        return _metamodel.IntegrationStrategy___repr__(self)

    def isLeastSquares(self):
        r"""
        Get the least squares flag.

        There are two methods to compute the coefficients: integration
        or least squares.

        Returns
        -------
        isLeastSquares : bool
            True if the coefficients are estimated from least squares.
        """
        return _metamodel.IntegrationStrategy_isLeastSquares(self)

    def involvesModelSelection(self):
        r"""
        Get the model selection flag.

        A model selection method can be used to select the coefficients
        of the decomposition which enable to best predict the output.
        Model selection can lead to a sparse functional chaos expansion.

        Returns
        -------
        involvesModelSelection : bool
            True if the method involves a model selection method.
        """
        return _metamodel.IntegrationStrategy_involvesModelSelection(self)

    def __init__(self, *args):
        _metamodel.IntegrationStrategy_swiginit(self, _metamodel.new_IntegrationStrategy(*args))
    __swig_destroy__ = _metamodel.delete_IntegrationStrategy

# Register IntegrationStrategy in _metamodel:
_metamodel.IntegrationStrategy_swigregister(IntegrationStrategy)
class _ProjectionStrategyImplementationTypedInterfaceObject(openturns.common.InterfaceObject):
    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __repr__ = _swig_repr

    def __init__(self, *args):
        _metamodel._ProjectionStrategyImplementationTypedInterfaceObject_swiginit(self, _metamodel.new__ProjectionStrategyImplementationTypedInterfaceObject(*args))

    def getImplementation(self):
        r"""
        Accessor to the underlying implementation.

        Returns
        -------
        impl : Implementation
            A copy of the underlying implementation object.
        """
        return _metamodel._ProjectionStrategyImplementationTypedInterfaceObject_getImplementation(self)

    def setName(self, name):
        r"""
        Accessor to the object's name.

        Parameters
        ----------
        name : str
            The name of the object.
        """
        return _metamodel._ProjectionStrategyImplementationTypedInterfaceObject_setName(self, name)

    def getName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        name : str
            The name of the object.
        """
        return _metamodel._ProjectionStrategyImplementationTypedInterfaceObject_getName(self)

    def __eq__(self, other):
        return _metamodel._ProjectionStrategyImplementationTypedInterfaceObject___eq__(self, other)

    def __ne__(self, other):
        return _metamodel._ProjectionStrategyImplementationTypedInterfaceObject___ne__(self, other)
    __swig_destroy__ = _metamodel.delete__ProjectionStrategyImplementationTypedInterfaceObject

# Register _ProjectionStrategyImplementationTypedInterfaceObject in _metamodel:
_metamodel._ProjectionStrategyImplementationTypedInterfaceObject_swigregister(_ProjectionStrategyImplementationTypedInterfaceObject)
class ProjectionStrategy(_ProjectionStrategyImplementationTypedInterfaceObject):
    r"""
    Base class for the evaluation strategies of the approximation coefficients.

    Available constructors:
        ProjectionStrategy(*projectionStrategy*)

    Parameters
    ----------
    projectionStrategy : :class:`~openturns.ProjectionStrategy`
        A projection strategy which is a :class:`~openturns.LeastSquaresStrategy` or
        an :class:`~openturns.IntegrationStrategy`.

    See also
    --------
    FunctionalChaosAlgorithm, LeastSquaresStrategy, IntegrationStrategy

    Notes
    -----
    This class is used in the :any:`functional chaos expansion context <functional_chaos>` implemented
    in the class :class:`~openturns.FunctionalChaosAlgorithm`. It is not usable outside this context. 

    The model is approximated by the meta model defined in :any:`functional_chaos` by equation :eq:`metaModelPn` and the coefficients :math:`(a_k)_{k \in I_n}` are computed by:

    - solving the least squares problem defined in :any:`functional_chaos` by equation
      :eq:`metaModeleF` : use the class
      :class:`~openturns.LeastSquaresStrategy`,
    - computing the inner product defined in :any:`functional_chaos` by equation
      :eq:`scalProd`: use the class
      :class:`~openturns.IntegrationStrategy`. In that case, the basis of the approximation space
      must be orthonormal to the input distribution.


    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.ProjectionStrategy_getClassName(self)

    def setMeasure(self, measure):
        r"""
        Accessor to the measure.

        Parameters
        ----------
        m : Distribution
            Measure :math:`\mu_{\inputRV}` defining the scalar product.
        """
        return _metamodel.ProjectionStrategy_setMeasure(self, measure)

    def getMeasure(self):
        r"""
        Accessor to the measure.

        Returns
        -------
        mu : Distribution
            Measure :math:`\mu_{\inputRV}` defining the inner product.
        """
        return _metamodel.ProjectionStrategy_getMeasure(self)

    def setInputSample(self, inputSample):
        r"""
        Accessor to the input sample.

        Parameters
        ----------
        X : :class:`~openturns.Sample`
            Input Sample.
        """
        return _metamodel.ProjectionStrategy_setInputSample(self, inputSample)

    def getInputSample(self):
        r"""
        Accessor to the input sample.

        Returns
        -------
        X : :class:`~openturns.Sample`
            Input Sample.
        """
        return _metamodel.ProjectionStrategy_getInputSample(self)

    def setOutputSample(self, outputSample):
        r"""
        Accessor to the output sample.

        Parameters
        ----------
        Y : :class:`~openturns.Sample`
            Output Sample.
        """
        return _metamodel.ProjectionStrategy_setOutputSample(self, outputSample)

    def getOutputSample(self):
        r"""
        Accessor to the output sample.

        Returns
        -------
        Y : :class:`~openturns.Sample`
            Output Sample.
        """
        return _metamodel.ProjectionStrategy_getOutputSample(self)

    def setWeights(self, weights):
        r"""
        Accessor to the weights.

        Parameters
        ----------
        w : :class:`~openturns.Point`
            Weights of the design of experiments.
        """
        return _metamodel.ProjectionStrategy_setWeights(self, weights)

    def getWeights(self):
        r"""
        Accessor to the weights.

        Returns
        -------
        w : :class:`~openturns.Point`
            Weights of the design of experiments.
        """
        return _metamodel.ProjectionStrategy_getWeights(self)

    def getResidual(self):
        r"""
        Accessor to the residual.

        Returns
        -------
        er : float
            Residual error.
        """
        return _metamodel.ProjectionStrategy_getResidual(self)

    def getRelativeError(self):
        r"""
        Accessor to the relative error.

        Returns
        -------
        e : float
            Relative error.
        """
        return _metamodel.ProjectionStrategy_getRelativeError(self)

    def getCoefficients(self):
        r"""
        Accessor to the coefficients.

        Returns
        -------
        coef : :class:`~openturns.Point`
            Coefficients :math:`(\alpha_k)_{k \in I_n}`.
        """
        return _metamodel.ProjectionStrategy_getCoefficients(self)

    def setExperiment(self, weightedExperiment):
        r"""
        Accessor to the design of experiment.

        Parameters
        ----------
        exp : :class:`~openturns.WeightedExperiment`
            Weighted design of experiment.
        """
        return _metamodel.ProjectionStrategy_setExperiment(self, weightedExperiment)

    def getExperiment(self):
        r"""
        Accessor to the experiments.

        Returns
        -------
        exp : :class:`~openturns.WeightedExperiment`
            Weighted experiment used to evaluate the coefficients.
        """
        return _metamodel.ProjectionStrategy_getExperiment(self)

    def getDesignProxy(self):
        r"""
        Accessor to the design proxy.

        Parameters
        ----------
        designProxy : :class:`~openturns.DesignProxy`
            The design matrix.
        """
        return _metamodel.ProjectionStrategy_getDesignProxy(self)

    def isLeastSquares(self):
        r"""
        Get the least squares flag.

        There are two methods to compute the coefficients: integration
        or least squares.

        Returns
        -------
        isLeastSquares : bool
            True if the coefficients are estimated from least squares.
        """
        return _metamodel.ProjectionStrategy_isLeastSquares(self)

    def involvesModelSelection(self):
        r"""
        Get the model selection flag.

        A model selection method can be used to select the coefficients
        of the decomposition which enable to best predict the output.
        Model selection can lead to a sparse functional chaos expansion.

        Returns
        -------
        involvesModelSelection : bool
            True if the method involves a model selection method.
        """
        return _metamodel.ProjectionStrategy_involvesModelSelection(self)

    def __repr__(self):
        return _metamodel.ProjectionStrategy___repr__(self)

    def __str__(self, *args):
        return _metamodel.ProjectionStrategy___str__(self, *args)

    def _repr_html_(self):
        return _metamodel.ProjectionStrategy__repr_html_(self)

    def __init__(self, *args):
        _metamodel.ProjectionStrategy_swiginit(self, _metamodel.new_ProjectionStrategy(*args))
    __swig_destroy__ = _metamodel.delete_ProjectionStrategy

# Register ProjectionStrategy in _metamodel:
_metamodel.ProjectionStrategy_swigregister(ProjectionStrategy)
class FunctionalChaosResult(MetaModelResult):
    r"""
    Functional chaos result.

    Returned by functional chaos algorithms, see :class:`~openturns.FunctionalChaosAlgorithm`.

    Refer to :any:`functional_chaos` to get more details on functional chaos expansion.

    Parameters
    ----------
    sampleX : 2-d sequence of float
        Input sample of :math:`\inputRV \in \Rset^{\inputDim}`.
    sampleY : 2-d sequence of float
        Output sample of :math:`\outputRV \in \Rset^{\outputDim}`.
    distribution : :class:`~openturns.Distribution`
        Distribution of the random vector :math:`\inputRV`
    transformation : :class:`~openturns.Function`
        The function that maps the input :math:`\inputRV` to the 
        standardized input :math:`\standardRV`.
    inverseTransformation : :class:`~openturns.Function`
        The function that maps the standardized input :math:`\standardRV` to
        the input :math:`\inputRV`.
    orthogonalBasis : :class:`~openturns.OrthogonalBasis`
        The multivariate orthogonal basis.
    indices : sequence of `int`
        The indices of the selected basis function within the orthogonal basis.
    alpha_k : 2-d sequence of `float`
        The coefficients of the functional chaos expansion.
    Psi_k : sequence of :class:`~openturns.Function`
        The functions of the multivariate basis selected by the algorithm.
    isLeastSquares : bool
        True if the expansion is computed using least squares.
    isModelSelection : bool
        True if the expansion is computed using model selection.

    Notes
    -----
    Let :math:`\sampleSize \in \Nset` be the sample size.
    Let :math:`\outputDim \in \Nset` be the dimension of the output of the model.
    For any :math:`j = 1, ..., \sampleSize` and any :math:`i = 1, ..., \outputDim`,
    let :math:`y_{j, i} \in \Rset` be the output of the
    model and let :math:`\hat{y}_{j, i} \in \Rset` be the output of the meta model.
    For any :math:`i = 1, ..., \outputDim`, let :math:`\outputRV_i \in \Rset^\sampleSize` be
    the sample output and let :math:`\widehat{\outputRV}_i \in \Rset^\sampleSize` be the
    output predicted by the metamodel.
    The marginal residual is:

    .. math::

        \hat{r}_i = \frac{\sqrt{SS_i}}{\sampleSize} 

    for :math:`i = 1, ..., \outputDim`, where :math:`SS_i` is the marginal sum of squares:

    .. math::

        SS_i = \sum_{j = 1}^\sampleSize (y_{j, i} - \hat{y}_{j, i})^2.

    The marginal relative error is:

    .. math::

        \widehat{re}_i = \frac{\hat{r}_i / \sampleSize}{\hat{s}_{Y, i}^2}

    for :math:`i = 1, ..., \outputDim`, where :math:`\hat{s}_{Y, i}^2` is the unbiased 
    sample variance of the :math:`i`-th output.

    This structure is created by the method `run()` of
    :class:`~openturns.FunctionalChaosAlgorithm`, and obtained thanks to the 
    `getResult()` method.
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.FunctionalChaosResult_getClassName(self)

    def __repr__(self):
        return _metamodel.FunctionalChaosResult___repr__(self)

    def __str__(self, *args):
        return _metamodel.FunctionalChaosResult___str__(self, *args)

    def __repr_markdown__(self):
        return _metamodel.FunctionalChaosResult___repr_markdown__(self)

    def getDistribution(self):
        r"""
        Get the input distribution.

        Returns
        -------
        distribution : :class:`~openturns.Distribution`
            Distribution of the  input random vector :math:`\inputRV`.
        """
        return _metamodel.FunctionalChaosResult_getDistribution(self)

    def getTransformation(self):
        r"""
        Get the isoprobabilistic transformation.

        Returns
        -------
        transformation : :class:`~openturns.Function`
            Transformation :math:`T` such that :math:`T(\inputRV) = \standardRV`.
        """
        return _metamodel.FunctionalChaosResult_getTransformation(self)

    def getInverseTransformation(self):
        r"""
        Get the inverse isoprobabilistic transformation.

        Returns
        -------
        invTransf : :class:`~openturns.Function`
             :math:`T^{-1}` such that :math:`T(\inputRV) = \standardRV`.
        """
        return _metamodel.FunctionalChaosResult_getInverseTransformation(self)

    def getOrthogonalBasis(self):
        r"""
        Get the orthogonal basis.

        Returns
        -------
        basis : :class:`~openturns.OrthogonalBasis`
            Factory of the orthogonal basis.
        """
        return _metamodel.FunctionalChaosResult_getOrthogonalBasis(self)

    def getIndices(self):
        r"""
        Get the indices of the final basis.

        Returns
        -------
        indices : :class:`~openturns.Indices`
            Indices :math:`\set{J}^P_s` of the elements of the multivariate basis used in the decomposition.
            Each integer in this list is the input argument of the :class:`~.openturns.EnumerateFunction`.
            If a model selection method such as :class:`~.openturns.LARS` is used,
            these indices are not contiguous.
        """
        return _metamodel.FunctionalChaosResult_getIndices(self)

    def getCoefficients(self):
        r"""
        Get the coefficients.

        Returns
        -------
        coefficients : 2-d sequence of float
            Coefficients :math:`(\vect{a_k})_{k \in \set{J}^P_s}`.
        """
        return _metamodel.FunctionalChaosResult_getCoefficients(self)

    def getReducedBasis(self):
        r"""
        Get the reduced basis.

        Returns
        -------
        basis : list of :class:`~openturns.Function`
            Collection of the functions  :math:`(\psi_k)_{k\in \set{J}^P_s}`  used in the 
            decomposition.
        """
        return _metamodel.FunctionalChaosResult_getReducedBasis(self)

    def getComposedMetaModel(self):
        r"""
        Get the composed metamodel.

        The composed metamodel is defined on the standard space :math:`\standardInputSpace`. 
        It is defined by the equation:

        .. math::
            \tilde{h}(\standardReal) =  \sum_{k \in \set{J}^P_s} \vect{a}_k \psi_k(\standardReal)

        for any :math:`\standardReal \in \standardInputSpace`.

        Returns
        -------
        composedMetamodel : :class:`~openturns.Function`
            The metamodel in the standard space :math:`\standardInputSpace`.
        """
        return _metamodel.FunctionalChaosResult_getComposedMetaModel(self)

    def getSampleResiduals(self):
        r"""
        Get residuals sample.

        Returns
        -------
        residualsSample : :class:`~openturns.Sample`
            The sample of residuals :math:`r_{ji} = y_{ji} - \metaModel_i(\vect{x^{(j)}})`
            for :math:`i = 1, ..., n_Y` and :math:`j = 1, ..., n`.
        """
        return _metamodel.FunctionalChaosResult_getSampleResiduals(self)

    def isLeastSquares(self):
        r"""
        Get the least squares flag.

        Returns
        -------
        isLeastSquares : bool
            True if the coefficients were estimated from least squares.
        """
        return _metamodel.FunctionalChaosResult_isLeastSquares(self)

    def involvesModelSelection(self):
        r"""
        Get the model selection flag.

        A model selection method can be used to select the coefficients
        of the decomposition which enable to best predict the output.
        Model selection can lead to a sparse functional chaos expansion.

        Returns
        -------
        involvesModelSelection : bool
            True if the method involves a model selection method.
        """
        return _metamodel.FunctionalChaosResult_involvesModelSelection(self)

    def setIsLeastSquares(self, isLeastSquares):
        r"""
        Set the least squares flag.

        Parameters
        ----------
        isLeastSquares : bool
            True if the coefficients were estimated from least squares.
        """
        return _metamodel.FunctionalChaosResult_setIsLeastSquares(self, isLeastSquares)

    def setInvolvesModelSelection(self, involvesModelSelection):
        r"""
        Set the model selection flag.

        A model selection method can be used to select the coefficients
        of the decomposition which enable to best predict the output.
        Model selection can lead to a sparse functional chaos expansion.

        Parameters
        ----------
        involvesModelSelection : bool
            True if the method involves a model selection method.
        """
        return _metamodel.FunctionalChaosResult_setInvolvesModelSelection(self, involvesModelSelection)

    def getConditionalExpectation(self, conditioningIndices):
        r"""
        Get the conditional expectation of the expansion given one vector input.

        This method returns the functional chaos result corresponding to the conditional 
        expectation of the output given an input vector.
        Indeed, the conditional expectation of a polynomial chaos expansion is, again, 
        a polynomial chaos expansion.
        This is possible only if the marginals of the input distribution are independent.
        Otherwise, an exception is generated.
        An example is provided in :doc:`/auto_surrogate_modeling/polynomial_chaos/plot_chaos_conditional_expectation`.

        We consider the notations introduced in :any:`functional_chaos`.
        Let :math:`\inputRV \in \Rset^{\inputDim}` be the input and let :math:`\vect{u} \subseteq \{1, ..., \inputDim\}`
        be a set of marginal indices. 
        Let :math:`\inputRV_{\vect{u}} \in \Rset^{|\vect{u}|}` be the vector 
        corresponding to the group of input variables where :math:`|\vect{u}| = \operatorname{card}(\vect{u})`
        is the number of input variables in the group.
        Let :math:`\metaModel(\inputRV)` be the polynomial chaos
        expansion of the physical model :math:`\model`.
        This function returns the functional chaos expansion of:

        .. math::

            \metaModel_{\vect{u}}\left(\inputReal_{\vect{u}}\right) 
            = \Expect{\metaModel(\inputRV) | \inputRV_{\vect{u}} = \inputReal_{\vect{u}}}

        for any :math:`\inputReal_{\vect{u}} \in \Rset^{|\vect{u}|}`.

        **Mathematical analysis**

        The mathematical derivation is better described in the standard space
        :math:`\standardInputSpace` than in the physical space :math:`\physicalInputSpace` and 
        this is why we consider the former.
        Assume that the basis functions :math:`\{\psi_{\vect{\alpha}}\}_{\vect{\alpha} \in \set{J}^P}` 
        are defined by the tensor product:

        .. math::

            \psi_{\vect{\alpha}}(\standardReal)
            = \prod_{i = 1}^\inputDim \pi_{\alpha_i}^{(i)}(z_i)

        for any :math:`\vect{\alpha} \in \set{J}^P` and any 
        :math:`\standardReal \in \standardInputSpace` where 
        :math:`\left\{\pi_k^{(i)}\right\}_{k \geq 0}` is the set of orthonormal  
        polynomials of degree :math:`k` for the :math:`i`-th input marginal. 
        Assume that the PCE to order :math:`P` is:

        .. math::

            \widetilde{h}(\standardReal) 
            = \sum_{\vect{\alpha} \in \set{J}^P} 
            a_{\vect{\alpha}} \psi_{\vect{\alpha}}(\standardReal)

        for any :math:`\standardReal \in \standardInputSpace`. 
        Assume that the input marginals :math:`\{Z_i\}_{i = 1, ..., \inputDim}` are independent. 
        Let :math:`\vect{u} \subseteq \{1, ..., \inputDim\}` be a group 
        of variables with dimension :math:`\operatorname{card}(\vect{u}) \in \Nset`. 
        Assume that :math:`\standardInputSpace` is the Cartesian product of vectors which 
        have components in the group :math:`\vect{u}` and other components, 
        i.e. assume that:

        .. math::

            \standardInputSpace = \standardInputSpace_{\vect{u}} \times \standardInputSpace_{\overline{\vect{u}}}

        where :math:`\standardInputSpace_{\vect{u}} \subseteq \Rset^{|\vect{u}|}` 
        and :math:`\standardInputSpace_{\overline{\vect{u}}} \subseteq \Rset^{|\overline{\vect{u}}|}`. 
        Let :math:`\widetilde{h}_{\vect{u}}^{\operatorname{ce}}` be the conditional expectation of the function :math:`\widetilde{h}` 
        given :math:`\standardReal_{\vect{u}}`:

        .. math::

            \widetilde{h}_{\vect{u}}^{\operatorname{ce}}(\standardReal_{\vect{u}})
            = \mathbb{E}_{\standardRV_{\overline{\vect{u}}}} 
            \left[\widetilde{h}\left(\standardRV\right) | \standardRV_{\vect{u}} 
            = \standardReal_{\vect{u}}\right]

        for any :math:`\standardReal_{\vect{u}} \in \standardInputSpace_{\vect{u}}`. 
        Let :math:`\set{J}_{\vect{u}}^{\operatorname{ce}} \subseteq \set{J}^P` be the 
        set of multi-indices having zero components when the marginal multi-index 
        is not in :math:`\vect{u}`:

        .. math::

            \set{J}_{\vect{u}}^{\operatorname{ce}} 
            = \left\{\vect{\alpha} \in \set{J}^P \; | \; 
            \alpha_i = 0 \textrm{ if } i \not \in \vect{u}, \; i = 1, ..., \inputDim\right\}.

        This set of multi-indices defines the functions that depends on the
        variables in the group :math:`\vect{u}` and *only* them.
        For any :math:`\vect{\alpha} \in \set{J}_{\vect{u}}^{\operatorname{ce}}`, let 
        :math:`\psi_{\vect{\alpha}}^{\operatorname{ce}}` be the orthogonal polynomial defined by :

        .. math::

            \psi_{\vect{\alpha}}^{\operatorname{ce}}(\standardReal_{\vect{u}})
            = 
            \begin{cases}
            \prod_{\substack{i = 1 \\ i \in \vect{u}}}^\inputDim \pi_{\alpha_i}^{(i)} (z_i) & \textrm{if } \alpha_i = 0 \textrm{ for any } i \not \in \vect{u}, \\
            1 & \textrm{if } \alpha_i = 0 \textrm{ for } i = 1, ..., \inputDim, \\
            0 & \textrm{otherwise}.
            \end{cases}

        Therefore :

        .. math::

            \widetilde{h}_{\vect{u}}^{\operatorname{ce}}(\standardReal_{\vect{u}})
            = \sum_{\vect{\alpha} \in \set{J}_{\vect{u}}^{\operatorname{ce}}}
            a_{\vect{\alpha}} \psi_{\vect{\alpha}}^{\operatorname{ce}}(\standardReal_{\vect{u}})

        for any :math:`\standardReal_{\vect{u}} \in \standardInputSpace_{\vect{u}}`.
        Finally, the conditional expectation of the surrogate model is:

        .. math::

          \metaModel_{\vect{u}}\left(\inputReal_{\vect{u}}\right)
          = \widetilde{h}_{\vect{u}}^{\operatorname{ce}}(T_{\vect{u}}\left(\inputReal_{\vect{u}}\right))

        where :math:`\standardRV_{\vect{u}} = T_{\vect{u}}(\inputRV_{\vect{u}})`
        is the corresponding marginal mapping of the iso-probabilistic mapping
        :math:`\standardRV = T(\inputRV)`.

        Parameters
        ----------
        conditioningIndices : sequence of int in [0, inputDimension - 1]
            The indices :math:`\vect{u}` of the input random vector to condition.

        Returns
        -------
        conditionalPCE : :class:`~openturns.FunctionalChaosResult`
            The functional chaos result of the conditional expectation.
            Its input dimension is :math:`\operatorname{card}(\vect{u})` and its output dimension
            is :math:`\outputDim` (i.e. the output dimension is unchanged).
        """
        return _metamodel.FunctionalChaosResult_getConditionalExpectation(self, conditioningIndices)

    def getIndicesHistory(self):
        r"""
        The basis indices selection history accessor.

        This is only available with :class:`~openturns.LARS`, and when the output dimension is 1.

        Returns
        -------
        indicesHistory : 2-d sequence of int
            The basis indices selection history, for each iteration.
            Each inner list gives the indices of the basis terms at i-th iteration.
        """
        return _metamodel.FunctionalChaosResult_getIndicesHistory(self)

    def getCoefficientsHistory(self):
        r"""
        The coefficients values selection history accessor.

        This is only available with :class:`~openturns.LARS`, and when the output dimension is 1.

        Returns
        -------
        coefficientsHistory : 2-d sequence of float
            The coefficients values selection history, for each iteration.
            Each inner list gives the coefficients values of the basis terms at i-th iteration.
        """
        return _metamodel.FunctionalChaosResult_getCoefficientsHistory(self)

    def setSelectionHistory(self, indicesHistory, coefficientsHistory):
        r"""
        The basis coefficients and indices accessor.

        Parameters
        ----------
        indicesHistory : 2-d sequence of int
            The basis indices selection history
        coefficientsHistory : 2-d sequence of float
            The coefficients values selection history
            Must be of same size as indicesHistory.
        """
        return _metamodel.FunctionalChaosResult_setSelectionHistory(self, indicesHistory, coefficientsHistory)

    def drawSelectionHistory(self):
        r"""
        Draw the basis selection history.

        This is only available with :class:`~openturns.LARS`, and when the output dimension is 1.

        Returns
        -------
        graph : :class:`~openturns.Graph`
            The evolution of the basis coefficients at each selection iteration
        """
        return _metamodel.FunctionalChaosResult_drawSelectionHistory(self)

    def setErrorHistory(self, errorHistory):
        r"""
        The error history accessor.

        Parameters
        ----------
        errorHistory : sequence of float
            The error history
        """
        return _metamodel.FunctionalChaosResult_setErrorHistory(self, errorHistory)

    def getErrorHistory(self):
        r"""
        The error history accessor.

        This is only available with :class:`~openturns.LARS`, and when the output dimension is 1.

        Returns
        -------
        errorHistory : sequence of float
            The error history
        """
        return _metamodel.FunctionalChaosResult_getErrorHistory(self)

    def drawErrorHistory(self):
        r"""
        Draw the error history.

        This is only available with :class:`~openturns.LARS`, and when the output dimension is 1.

        Returns
        -------
        graph : :class:`~openturns.Graph`
            The evolution of the error at each selection iteration
        """
        return _metamodel.FunctionalChaosResult_drawErrorHistory(self)

    def getMarginal(self, *args):
        r"""
        Get the marginal chaos.

        When the chaos expansion has several outputs, this method can be used
        to extract a particular marginal.
        If there are several outputs, zero marginal coefficients may occur: these
        are filtered out of the marginal chaos if possible.

        Parameters
        ----------
        outputIndex : int or list of ints, :math:`0 \leq i < \outputDim`
            The index or indices of the output marginal.

        Returns
        -------
        marginalPCE : :class:`~openturns.FunctionalChaosResult`
            The marginal chaos.
        """
        return _metamodel.FunctionalChaosResult_getMarginal(self, *args)

    def setUseDomination(self, useDomination):
        r"""
        Domination method flag accessor.

        Parameters
        ----------
        useDomination : bool
            Whether to use the domination method.

        Notes
        -----
        The domination method consists in using the basis defined in the argument *adaptiveStrategy*. No
        isoprobabilistic transformation is used. This basis it is not necessarily orthonormal with respect to
        the *inputDistribution*. As a result, the coefficients can be computed with a least squares method only
        (:math:`isLeastSquares` must be *True*) and the Sobol' indices will not be computed.

        """
        return _metamodel.FunctionalChaosResult_setUseDomination(self, useDomination)

    def getUseDomination(self):
        r"""
        Domination method flag accessor.

        Returns
        -------
        useDomination : bool
            Whether to use the domination method.

        Notes
        -----
        The domination method consists in using the basis defined in the argument *adaptiveStrategy*. No
        isoprobabilistic transformation is used. This basis it is not necessarily orthonormal with respect to
        the *inputDistribution*. As a result, the coefficients must have been computed with a least squares method only
        (:meth:`isLeastSquares` must be *True*) and the Sobol' indices will not be computed.

        """
        return _metamodel.FunctionalChaosResult_getUseDomination(self)

    def __init__(self, *args):
        _metamodel.FunctionalChaosResult_swiginit(self, _metamodel.new_FunctionalChaosResult(*args))
    __swig_destroy__ = _metamodel.delete_FunctionalChaosResult

# Register FunctionalChaosResult in _metamodel:
_metamodel.FunctionalChaosResult_swigregister(FunctionalChaosResult)

def __FunctionalChaosResult_repr_html(self):
    """Get HTML representation."""
    html = ""
    html += f"{self.getClassName()}\n"
    coefficients = self.getCoefficients()
    basis = self.getOrthogonalBasis()
    enumerateFunction = basis.getEnumerateFunction()
    indices = self.getIndices()
    indicesSize = indices.getSize()
# Table of attributes
    inputDimension = self.getMetaModel().getInputDimension()
    outputDimension = self.getMetaModel().getOutputDimension()
    transformation = self.getTransformation()
    inverseTransformation = self.getInverseTransformation()
    orthogonalBasis = self.getOrthogonalBasis()
    distribution = self.getDistribution()
    fmt = openturns.common.ResourceMap.GetAsString("FunctionalChaosResult-PrintFormat")
    ell_threshold = openturns.common.ResourceMap.GetAsUnsignedInteger("FunctionalChaosResult-PrintEllipsisThreshold")
    ell_size = openturns.common.ResourceMap.GetAsUnsignedInteger("FunctionalChaosResult-PrintEllipsisSize")
    ellipsis = indicesSize * outputDimension > ell_threshold
# Header
    html += "<ul>\n"
    html += f"  <li>input dimension: {inputDimension}</li>\n"
    html += f"  <li>output dimension: {outputDimension}</li>\n"
    html += f"  <li>distribution dimension: {distribution.getDimension()}</li>\n"
    html += f"  <li>transformation: {transformation.getInputDimension()} -> {transformation.getOutputDimension()}</li>\n"
    html += f"  <li>inverse transformation: {inverseTransformation.getInputDimension()} -> {inverseTransformation.getOutputDimension()}</li>\n"
    html += f"  <li>orthogonal basis dimension: {orthogonalBasis.getMeasure().getDimension()}</li>\n"
    html += f"  <li>indices size: {indicesSize}</li>\n"
    html += "</ul>\n"
# Table of coefficients
    html += "<table>\n"
# Header
    html += "  <tr>\n"
    html += "    <th>Index</th>\n"
    html += "    <th>Multi-index</th>\n"
    isEllipsisEnabled = (ellipsis and outputDimension > 2 * ell_size)
    if isEllipsisEnabled:
        actualNumberOfColumns = 3 + 2 * ell_size
    else:
        actualNumberOfColumns = 2 + outputDimension
    if isEllipsisEnabled:
        for j in range(ell_size):
            html += f"    <th>Coeff.#{j}</th>\n"
        html += "    <th>...</th>\n"
        for j in range(outputDimension - ell_size, outputDimension):
            html += f"    <th>Coeff.#{j}</th>\n"
    else:
        if outputDimension == 1:
            html += "    <th>Coeff.</th>\n"
        else:
            for j in range(outputDimension):
                html += f"    <th>Coeff.#{j}</th>\n"
    html += "  </tr>\n"
# Content
    for i in range(indicesSize):
        if ellipsis and indicesSize > 2 * ell_size:
            if i == ell_size:
                html += "  <tr>\n"
                html += f'    <td colspan="{actualNumberOfColumns}">...</td>\n'
                html += "  </tr>\n" 
                continue
            else:
                if i > ell_size and i < indicesSize - ell_size:
                    continue
        globalIndex = indices[i]
        multiindex = enumerateFunction(globalIndex)
        html += "  <tr>\n"
        html += f"    <th>{i}</th>\n"
        html += f"    <td>{multiindex}</td>\n"
        if isEllipsisEnabled:
            for j in range(ell_size):
                html += "    <td>" + fmt.format(coefficients[i, j]) + "</td>\n"
            html += "    <td>...</td>\n"
            for j in range(outputDimension - ell_size, outputDimension):
                html += "    <td>" + fmt.format(coefficients[i, j]) + "</td>\n"
        else:
            for j in range(outputDimension):
                html += "    <td>" + fmt.format(coefficients[i, j]) + "</td>\n"
        html += "  </tr>\n"
    html += "</table>\n"

    return html

FunctionalChaosResult._repr_html_ = __FunctionalChaosResult_repr_html

class FunctionalChaosAlgorithm(MetaModelAlgorithm):
    r"""
    Functional chaos algorithm.

    Refer to :any:`functional_chaos` to get more details on functional chaos expansion.

    Available constructors:
        FunctionalChaosAlgorithm(*inputSample, outputSample*)

        FunctionalChaosAlgorithm(*inputSample, outputSample, distribution*)

        FunctionalChaosAlgorithm(*inputSample, outputSample, distribution, adaptiveStrategy*)

        FunctionalChaosAlgorithm(*inputSample, outputSample, distribution, adaptiveStrategy, projectionStrategy*)

        FunctionalChaosAlgorithm(*inputSample, weights, outputSample, distribution, adaptiveStrategy*)

        FunctionalChaosAlgorithm(*inputSample, weights, outputSample, distribution, adaptiveStrategy, projectionStrategy*)

    Parameters
    ----------
    inputSample: 2-d sequence of float
        Sample of the input random vectors with size :math:`\sampleSize` and dimension :math:`\inputDim`.
    outputSample: 2-d sequence of float
        Sample of the output random vectors with size :math:`\sampleSize` and dimension :math:`\outputDim`.
    distribution : :class:`~openturns.Distribution`
        Distribution of the random vector :math:`\inputRV` of dimension :math:`\inputDim`.
        When the *distribution* is unspecified, the
        :meth:`~openturns.MetaModelAlgorithm.BuildDistribution` static
        method is evaluated on the *inputSample*.
    adaptiveStrategy : :class:`~openturns.AdaptiveStrategy`
        Strategy of selection of the different terms of the multivariate basis.
    projectionStrategy : :class:`~openturns.ProjectionStrategy`
        Strategy of evaluation of the coefficients :math:`a_k`
    weights : sequence of float
        Weights :math:`(w_i)_{i = 1, ..., \sampleSize}` associated to the output
        sample, where :math:`\sampleSize` is the sample size.
        Default values are :math:`w_i = \frac{1}{\sampleSize}` for :math:`i = 1, ..., \sampleSize`. 

    See also
    --------
    FunctionalChaosResult

    Notes
    -----
    This class creates a functional chaos expansion  based on an input and output
    sample of the model.

    Refer to :any:`functional_chaos` to get more details on functional chaos expansion.

    Once the expansion is computed, the :class:`~openturns.FunctionalChaosRandomVector`
    class provides methods to get the mean and variance of the PCE.
    Moreover, if the input distribution has independent marginals and if the domination method is not used,
    the :class:`~openturns.FunctionalChaosSobolIndices` provides Sobol' indices
    of the input components.

    In order to use the domination method, use the :meth:`setUseDomination` method. 


    **Default settings for the adaptive strategy**

    When the *adaptiveStrategy* is unspecified, the following :class:`~openturns.FixedStrategy` is selected as an
    :class:`~openturns.AdaptiveStrategy`.
    The associated basis is built as the tensorization of the univariate polynomials family
    orthonormal to the standard representative of the input marginals distribution (if not specified, the input 
    distribution is fitted on the input sample).
    The basis which is associated to the enumerate function is chosen according to
    the `FunctionalChaosAlgorithm-QNorm` parameter of the :class:`~openturns.ResourceMap`:

    - If this parameter is equal to 1, then the :class:`~openturns.LinearEnumerateFunction` class is used.
    - Otherwise, the :class:`~openturns.HyperbolicAnisotropicEnumerateFunction` class is used.

    The first elements of the basis are used to build the approximation space. By default, the number of elements is
    defined by the keys `FunctionalChaosAlgorithm-BasisSize` and  `FunctionalChaosAlgorithm-TotalDegree`:

    - is the BasisSize is 0, then the number is computed from the total degree (using the enumerate function of the basis);
    - is the BasisSize is less than the input sample size, this value is used;
    - is the BasisSize is greater than the input sample size, the number is the input sample size.

    If the `FunctionalChaosAlgorithm-BasisSize` key of the :class:`~openturns.ResourceMap` is nonzero,
    then this parameter sets the basis size.
    Otherwise, the `FunctionalChaosAlgorithm-MaximumTotalDegree` key of the
    :class:`~openturns.ResourceMap` is used to compute the basis size using the `getBasisSizeFromTotalDegree`
    method of the orthogonal basis (with a maximum of :math:`n` terms due to the sample size).
    Finally, the :class:`~openturns.FixedStrategy` class is used.

    **Default settings for the projection strategy**

    When the *projectionStrategy* is unspecified, the 
    `FunctionalChaosAlgorithm-Sparse` key of the :class:`~openturns.ResourceMap` is used.
    If it is false, then the :class:`~openturns.LeastSquaresStrategy` class is
    used, which produces a full PCE, without model selection.
    Otherwise, a :class:`~openturns.LARS` PCE is created, i.e.
    a sparse PCE is computed using model selection.
    In this case, the `FunctionalChaosAlgorithm-FittingAlgorithm`
    key of the :class:`~openturns.ResourceMap` is used.

    - If this key is equal to 'CorrectedLeaveOneOut', then the
      :class:`~openturns.CorrectedLeaveOneOut` criteria is used.
    - If this key is equal to 'KFold', then the
      :class:`~openturns.KFold` criteria is used.
    - Otherwise, an exception is produced.

    Examples
    --------
    Create the model:

    >>> import openturns as ot
    >>> ot.RandomGenerator.SetSeed(0)
    >>> inputDimension = 1
    >>> model = ot.SymbolicFunction(['x'], ['x * sin(x)'])
    >>> distribution = ot.JointDistribution([ot.Uniform()] * inputDimension)

    Build the multivariate orthonormal basis:

    >>> polyColl = [0.0] * inputDimension
    >>> for i in range(distribution.getDimension()):
    ...     polyColl[i] = ot.StandardDistributionPolynomialFactory(distribution.getMarginal(i))
    >>> enumerateFunction = ot.LinearEnumerateFunction(inputDimension)
    >>> productBasis = ot.OrthogonalProductPolynomialFactory(polyColl, enumerateFunction)

    Define the  strategy to truncate the multivariate orthonormal basis:
    We choose all the polynomials of degree lower or equal to 4.

    >>> degree = 4
    >>> indexMax = enumerateFunction.getBasisSizeFromTotalDegree(degree)
    >>> print(indexMax)
    5

    We keep all the polynomials of degree lower or equal to 4 (which corresponds
    to the 5 first ones):

    >>> adaptiveStrategy = ot.FixedStrategy(productBasis, indexMax)

    Define the evaluation strategy of the  coefficients:

    >>> samplingSize = 50
    >>> experiment = ot.MonteCarloExperiment(distribution, samplingSize)
    >>> inputSample = experiment.generate()
    >>> outputSample = model(inputSample)
    >>> projectionStrategy = ot.LeastSquaresStrategy()

    Create the chaos algorithm:

    >>> algo = ot.FunctionalChaosAlgorithm(
    ...     inputSample, outputSample, distribution, adaptiveStrategy, projectionStrategy
    ... )
    >>> algo.run()

    Get the result:

    >>> functionalChaosResult = algo.getResult()
    >>> # print(functionalChaosResult)  # Pretty-print
    >>> metamodel = functionalChaosResult.getMetaModel()

    Test it:

    >>> X = [0.5]
    >>> print(model(X))
    [0.239713]
    >>> print(metamodel(X))
    [0.239514]

    There are several methods to define the algorithm: default 
    settings are used when the information is not provided by the user.
    The simplest is to set only the input and output samples.
    In this case, the distribution and its parameters are estimated from
    the *inputSample* using the :class:`~openturns.MetaModelAlgorithm.BuildDistribution` class.
    See the :doc:`/auto_surrogate_modeling/polynomial_chaos/plot_chaos_build_distribution`
    example for more details on this topic.

    >>> algo = ot.FunctionalChaosAlgorithm(inputSample, outputSample)

    In many cases, the distribution is known and it is best to use this information
    when we have it.

    >>> algo = ot.FunctionalChaosAlgorithm(inputSample, outputSample, distribution)

    A more involved method is to define the method to set the orthogonal basis of functions or
    polynomials.
    We use the :class:`~openturns.OrthogonalProductPolynomialFactory` class to define the
    orthogonal basis of polynomials.
    Then we use the :class:`FixedStrategy` to define the maximum number of candidate polynomials
    to consider in the expansion, up to the total degree equal to 10.

    >>> enumerateFunction = ot.LinearEnumerateFunction(inputDimension)
    >>> maximumTotalDegree = 10
    >>> totalSize = enumerateFunction.getBasisSizeFromTotalDegree(maximumTotalDegree)
    >>> polynomialsList = []
    >>> for i in range(inputDimension):
    ...     marginalDistribution = distribution.getMarginal(i)
    ...     marginalPolynomial = ot.StandardDistributionPolynomialFactory(marginalDistribution)
    ...     polynomialsList.append(marginalPolynomial)
    >>> basis = ot.OrthogonalProductPolynomialFactory(polynomialsList, enumerateFunction)
    >>> adaptiveStrategy = ot.FixedStrategy(basis, totalSize)
    >>> algo = ot.FunctionalChaosAlgorithm(
    ...     inputSample, outputSample, distribution, adaptiveStrategy
    ... )

    The most involved method is to define the way to compute the coefficients,
    thanks to the :class:`~openturns.ProjectionStrategy`.
    In the next example, we use :class:`~openturns.LARS` to create a
    sparse PCE.

    >>> selection = ot.LeastSquaresMetaModelSelectionFactory(
    ...     ot.LARS(),
    ...     ot.CorrectedLeaveOneOut()
    ... )
    >>> projectionStrategy = ot.LeastSquaresStrategy(inputSample, outputSample, selection)
    >>> algo = ot.FunctionalChaosAlgorithm( 
    ...     inputSample, outputSample, distribution, adaptiveStrategy, projectionStrategy
    ... )

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.FunctionalChaosAlgorithm_getClassName(self)

    def __repr__(self):
        return _metamodel.FunctionalChaosAlgorithm___repr__(self)

    def setMaximumResidual(self, residual):
        r"""
        Set the maximum residual.

        Parameters
        ----------
        residual : float
            Residual value needed in the projection strategy. 

            Default value is :math:`0`.
        """
        return _metamodel.FunctionalChaosAlgorithm_setMaximumResidual(self, residual)

    def getMaximumResidual(self):
        r"""
        Get the maximum residual.

        Returns
        -------
        residual : float
            Residual value needed in the projection strategy. 

            Default value is :math:`0`.
        """
        return _metamodel.FunctionalChaosAlgorithm_getMaximumResidual(self)

    def setProjectionStrategy(self, projectionStrategy):
        r"""
        Set the projection strategy.

        Parameters
        ----------
        projectionStrategy : :class:`~openturns.ProjectionStrategy`
            Strategy to estimate the coefficients :math:`a_k`.
        """
        return _metamodel.FunctionalChaosAlgorithm_setProjectionStrategy(self, projectionStrategy)

    def getProjectionStrategy(self):
        r"""
        Get the projection strategy.

        Returns
        -------
        strategy : :class:`~openturns.ProjectionStrategy`
            Projection strategy.

        Notes
        -----
        The projection strategy selects the different terms of the
        multivariate basis to define the subset *K*.
        """
        return _metamodel.FunctionalChaosAlgorithm_getProjectionStrategy(self)

    def getAdaptiveStrategy(self):
        r"""
        Get the adaptive strategy.

        Returns
        -------
        adaptiveStrategy : :class:`~openturns.AdaptiveStrategy`
            Strategy of selection of the different terms of the multivariate basis.
        """
        return _metamodel.FunctionalChaosAlgorithm_getAdaptiveStrategy(self)

    def setUseDomination(self, useDomination):
        r"""
        Domination method flag accessor.

        Parameters
        ----------
        useDomination : bool
            Whether to use the domination method.

        Notes
        -----
        The domination method consists in using the basis defined in the argument *adaptiveStrategy* (or its default
        implementation if not specified). No
        isoprobabilistic transformation is used. This basis it is not necessarily orthonormal with respect to
        the *inputDistribution*. As a result, the coefficients can be computed with a least squares method only
        (select class:`~openturns.LeastSquaresStrategy` for the *projectionStrategy*) and the Sobol' indices will not
        be computed.

        """
        return _metamodel.FunctionalChaosAlgorithm_setUseDomination(self, useDomination)

    def getUseDomination(self):
        r"""
        Domination method flag accessor.

        Returns
        -------
        useDomination : bool
            Whether the domination method is used.

        Notes
        -----
        The domination method consists in using the basis defined in the argument *adaptiveStrategy* (or its default
        implementation if not specified). No
        isoprobabilistic transformation is used. This basis it is not necessarily orthonormal with respect to
        the *inputDistribution*. As a result, the coefficients can be computed with a least squares method only
        (select class:`~openturns.LeastSquaresStrategy` for the *projectionStrategy*) and the Sobol' indices will not
        be computed.

        """
        return _metamodel.FunctionalChaosAlgorithm_getUseDomination(self)

    def run(self):
        r"""
        Compute the metamodel.

        Notes
        -----
        Evaluates the metamodel and stores all the results in a result structure.
        """
        return _metamodel.FunctionalChaosAlgorithm_run(self)

    def getResult(self):
        r"""
        Get the results of the metamodel computation.

        Returns
        -------
        result : :class:`~openturns.FunctionalChaosResult`
            Result structure, created by the method :py:meth:`run`.
        """
        return _metamodel.FunctionalChaosAlgorithm_getResult(self)

    def __init__(self, *args):
        _metamodel.FunctionalChaosAlgorithm_swiginit(self, _metamodel.new_FunctionalChaosAlgorithm(*args))
    __swig_destroy__ = _metamodel.delete_FunctionalChaosAlgorithm

# Register FunctionalChaosAlgorithm in _metamodel:
_metamodel.FunctionalChaosAlgorithm_swigregister(FunctionalChaosAlgorithm)
class FunctionalChaosSobolIndices(openturns.common.PersistentObject):
    r"""
    Sensitivity analysis based on functional chaos expansion.

    Parameters
    ----------
    result : :class:`~openturns.FunctionalChaosResult`
        A functional chaos result resulting from a polynomial chaos expansion.

    See also
    --------
    FunctionalChaosAlgorithm, FunctionalChaosResult

    Notes
    -----
    This structure is created from a :class:`~openturns.FunctionalChaosResult` in order to evaluate the
    Sobol' indices associated to the polynomial chaos expansion of the model. 
    The :meth:`~openturns.SobolIndicesAlgorithm.DrawSobolIndices` static method can be used to 
    draw the indices.

    This class provides methods to estimate the Sobol' indices which
    are presented in :any:`sensitivity_sobol`.
    These indices can be easily computed from the polynomial chaos expansion
    using the methods presented in :any:`sensitivity_sobol_from_pce`.

    The next table presents the map from the Sobol' index to the
    corresponding method.

    +-------------------------------------+----------------------+------------------------------------+----------------------------------------------+
    | Single variable or group            | Sensitivity Index    | Notation                           | Method                                       |
    +=====================================+======================+====================================+==============================================+
    | One single variable :math:`i`       | First order          | :math:`S_i`                        | `getSobolIndex(i)`                           |
    +-------------------------------------+----------------------+------------------------------------+----------------------------------------------+
    |                                     | Total                | :math:`S^T_i`                      | `getSobolTotalIndex(i)`                      |
    +-------------------------------------+----------------------+------------------------------------+----------------------------------------------+
    | Group interaction :math:`\bdu`      | First order          | :math:`S_\bdu`                     | `getSobolIndex(variableIndices)`             |
    +-------------------------------------+----------------------+------------------------------------+----------------------------------------------+
    |                                     | Total interaction    | :math:`S^{T,i}_\bdu`               | `getSobolTotalIndex(variableIndices)`        |
    +-------------------------------------+----------------------+------------------------------------+----------------------------------------------+
    | Group closed :math:`\bdu`           | First order closed   | :math:`S_\bdu^{\operatorname{cl}}` | `getSobolGroupedIndex(variableIndices)`      |
    +-------------------------------------+----------------------+------------------------------------+----------------------------------------------+
    |                                     | Total                | :math:`S^T_\bdu`                   | `getSobolGroupedTotalIndex(variableIndices)` |
    +-------------------------------------+----------------------+------------------------------------+----------------------------------------------+

    **Table 1.** Sobol' indices and the corresponding methods.

    By default, printing the object will print the Sobol’ indices and the
    multi-indices ordered by decreasing part of variance.
    If a multi-index accounts for a smaller part of the variance than some
    threshold, it is not printed.
    This threshold can be customized using the
    `FunctionalChaosSobolIndices-VariancePartThreshold` key of the
    :class:`~openturns.ResourceMap`.

    Examples
    --------
    Create a polynomial chaos for the Ishigami function:

    >>> import openturns as ot
    >>> from math import pi
    >>> import openturns.viewer as otv

    Create the function:

    >>> ot.RandomGenerator.SetSeed(0)
    >>> formula = ['sin(X1) + 7. * sin(X2)^2 + 0.1 * X3^4 * sin(X1)']
    >>> input_names = ['X1', 'X2', 'X3']
    >>> g = ot.SymbolicFunction(input_names, formula)

    Create the probabilistic model:

    >>> distributionList = [ot.Uniform(-pi, pi)] * 3
    >>> distribution = ot.JointDistribution(distributionList)

    Create a training sample:

    >>> N = 100 
    >>> inputTrain = distribution.getSample(N)
    >>> outputTrain = g(inputTrain)

    Create the chaos:

    >>> chaosalgo = ot.FunctionalChaosAlgorithm(inputTrain, outputTrain, distribution)
    >>> chaosalgo.run()
    >>> result = chaosalgo.getResult()

    Print Sobol' indices (see :doc:`/auto_surrogate_modeling/polynomial_chaos/plot_chaos_ishigami_grouped_indices`
    for details):

    >>> chaosSI = ot.FunctionalChaosSobolIndices(result) 
    >>> #print(chaosSI)  # Prints a table of multi-indices

    Get first order Sobol' index for X0:

    >>> s0 = chaosSI.getSobolIndex(0)
    >>> print('S(0) = ', s0)
    S(0) =  0.26...

    Get total Sobol' index for X0:

    >>> st0 = chaosSI.getSobolTotalIndex(0)
    >>> print('ST(0) = ', st0)
    ST(0) =  0.48...

    Get interaction Sobol' index for the group (X0, X1):

    >>> s01 = chaosSI.getSobolIndex([0, 1])
    >>> print('S([0, 1]) = ', s01)
    S([0, 1]) =  0.00...

    Get total interaction Sobol' index for the group (X0, X1):

    >>> st01 = chaosSI.getSobolTotalIndex([0, 1])
    >>> print('ST([0, 1]) = ', st01)
    ST([0, 1]) =  0.00...

    Get first order Sobol' index for group [X0,X1]:

    >>> sg01 = chaosSI.getSobolGroupedIndex([0,1])
    >>> print('SG([0, 1]) = ', sg01)
    SG([0, 1]) =  0.76...

    Get total Sobol' index for group [X0,X1]:

    >>> stg01 = chaosSI.getSobolGroupedTotalIndex([0,1])
    >>> print('STG([0, 1]) = ', stg01)
    STG([0, 1]) =  0.99...

    Get the part of variance of first multi-indices:

    >>> partOfVariance = chaosSI.getPartOfVariance()

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.FunctionalChaosSobolIndices_getClassName(self)

    def __repr__(self):
        return _metamodel.FunctionalChaosSobolIndices___repr__(self)

    def __str__(self, *args):
        return _metamodel.FunctionalChaosSobolIndices___str__(self, *args)

    def __repr_markdown__(self):
        return _metamodel.FunctionalChaosSobolIndices___repr_markdown__(self)

    def getSobolIndex(self, *args):
        r"""
        Get the first order Sobol' index of an input variable
        or the interaction (high order) index of a group of variables.
        This function can take a single variable or a group of variables as input
        argument.

        *Case 1: single variable.* 
        Let :math:`i \in \{0, ..., d - 1\}` the index of an input 
        variable. 
        Therefore, the method computes the first order Sobol' index :math:`S_i`
        of the variable :math:`X_i`.
        See :any:`sensitivity_sobol_from_pce_first_order_variable`
        for the computation of this sensitivity index based on a PCE.

        *Case 2: group of variables.*
        Let :math:`\bdu \subseteq \{0, ..., d - 1\}` the list of variable indices
        in the group. 
        Therefore, the method computes the interaction (high order) Sobol'
        index :math:`S_\bdu` of the group :math:`\bdu`.
        See :any:`sensitivity_sobol_from_pce_interaction_group`
        for the computation of this sensitivity index based on a PCE.

        Parameters
        ----------
        i : int or sequence of int, :math:`0 \leq i \leq d - 1`
            Indice(s) of the variable(s). 
        marginalIndex : int
            Output marginal index.
            Default value is 0, i.e. the first output.

        Returns
        -------
        s : float
            The Sobol' first order index of an input variable or interaction index
            of a group of input variables.
        """
        return _metamodel.FunctionalChaosSobolIndices_getSobolIndex(self, *args)

    def getSobolTotalIndex(self, *args):
        r"""
        Get the Sobol' total index of an input variable or the total interaction
        index of a group of input variables.
        This function can take a single variable or a group of variables as input
        argument.

        *Case 1: single variable.* 
        Let :math:`i \in \{0, ..., d - 1\}` the index of an input 
        variable. 
        Therefore, the method computes the total index :math:`S^T_i`
        of the variable :math:`X_i`.
        See :any:`sensitivity_sobol_from_pce_total_variable`
        for the computation of this sensitivity index based on a PCE.

        *Case 2: group of variables.*
        Let :math:`\bdu \subseteq \{0, ..., d - 1\}` the list of variable indices
        in the group. 
        Therefore, the method computes the total interaction (high order)
        Sobol' index :math:`S_\bdu^{T, i}` of the group :math:`\bdu`.
        See :any:`sensitivity_sobol_from_pce_total_interaction_group`
        for the computation of this sensitivity index based on a PCE.

        Parameters
        ----------
        i : int or sequence of int, :math:`0 \leq i \leq d - 1`
            Indice(s) of the variable(s).
        marginalIndex : int
            Output marginal index.
            Default value is 0, i.e. the first output.

        Returns
        -------
        s : float
            The Sobol’ total index of an input variable or total interaction
            index of a group of input variables.
        """
        return _metamodel.FunctionalChaosSobolIndices_getSobolTotalIndex(self, *args)

    def getSobolGroupedIndex(self, variableIndices, marginalIndex=0):
        r"""
        Get the Sobol' first order closed index of a group of input variables.

        Let :math:`\bdu \subseteq \{0, ..., d - 1\}` the list of variable indices
        in the group. 
        Therefore, the method computes the first order closed Sobol' index 
        :math:`S^{\operatorname{cl}}_\bdu` of the group :math:`\bdu`.
        See :any:`sensitivity_sobol_from_pce_first_order_closed_group`
        for the computation of this sensitivity index based on a PCE.

        Parameters
        ----------
        variableIndices : sequence of int, :math:`0 \leq i \leq d - 1`
            Indice(s) of the variable(s) in the group.
        marginalIndex : int
            Output marginal index.
            Default value is 0, i.e. the first output.

        Returns
        -------
        s : float
            The Sobol' first order closed index of a group of input variables.
        """
        return _metamodel.FunctionalChaosSobolIndices_getSobolGroupedIndex(self, variableIndices, marginalIndex)

    def getSobolGroupedTotalIndex(self, variableIndices, marginalIndex=0):
        r"""
        Get the Sobol' total index of a group of input variables.

        Let :math:`\bdu \subseteq \{0, ..., d - 1\}` the list of variable indices
        in the group. 
        Therefore, the method computes the total Sobol' index :math:`S^T_\bdu` of
        the group :math:`\bdu`.
        See :any:`sensitivity_sobol_from_pce_total_group`
        for the computation of this sensitivity index based on a PCE.

        Parameters
        ----------
        variableIndices : sequence of int, :math:`0 \leq i \leq d - 1`
            Indice(s) of the variable(s) in the group.
        marginalIndex : int
            Output marginal index.
            Default value is 0, i.e. the first output.

        Returns
        -------
        s : float
            The Sobol' total closed index of a group of input variables.
        """
        return _metamodel.FunctionalChaosSobolIndices_getSobolGroupedTotalIndex(self, variableIndices, marginalIndex)

    def getFunctionalChaosResult(self):
        r"""
        Accessor to the functional chaos result.

        Returns
        -------
        functionalChaosResult : :class:`~openturns.FunctionalChaosResult`
            The functional chaos result resulting from a polynomial chaos decomposition.
        """
        return _metamodel.FunctionalChaosSobolIndices_getFunctionalChaosResult(self)

    def getPartOfVariance(self, marginalIndex=0):
        r"""
        Get the part of variance corresponding to each multi-index.

        Parameters
        ----------
        marginalIndex : int
            Output marginal index.
            Default value is 0, i.e. the first output.

        Returns
        -------
        partOfVariance : :class:`~openturns.Point`
            The part of variance `partOfVariance[i]` of each multi-index, 
            for `i = 0, ..., indicesSize - 1` where `indicesSize` is the 
            number of indices.
            The part of variance of a given multi-index is in the [0, 1] interval.
            This is a sensitivity index which represents 
            the part of the variance explained by the corresponding function.
            The sum of part of variances is equal to 1.
            If the corresponding multi-index has total degree equal to 0,
            then the corresponding part of variance is equal to zero.
        """
        return _metamodel.FunctionalChaosSobolIndices_getPartOfVariance(self, marginalIndex)

    def __init__(self, *args):
        _metamodel.FunctionalChaosSobolIndices_swiginit(self, _metamodel.new_FunctionalChaosSobolIndices(*args))
    __swig_destroy__ = _metamodel.delete_FunctionalChaosSobolIndices

# Register FunctionalChaosSobolIndices in _metamodel:
_metamodel.FunctionalChaosSobolIndices_swigregister(FunctionalChaosSobolIndices)

def __FunctionalChaosSobolIndices_repr_html(self):
    """Get HTML representation."""
    chaosResult = self.getFunctionalChaosResult()
    inputDimension = chaosResult.getDistribution().getDimension()
    outputDimension = chaosResult.getMetaModel().getOutputDimension()
    enumerateFunction = chaosResult.getOrthogonalBasis().getEnumerateFunction()
    indices = chaosResult.getIndices()
    basisSize = indices.getSize()
    coefficients = chaosResult.getCoefficients()
    inputDescription = chaosResult.getDistribution().getDescription()
    sobolIndexFormat = openturns.ResourceMap.GetAsString("FunctionalChaosSobolIndices-PrintFormat")
    partOfVarianceThreshold = openturns.ResourceMap.GetAsScalar("FunctionalChaosSobolIndices-VariancePartThreshold")
    maximumNumberOfOutput = openturns.ResourceMap.GetAsUnsignedInteger("FunctionalChaosSobolIndices-MaximumNumberOfOutput")

# compute the mean, the variance, the standard deviation
    randomVector = openturns.FunctionalChaosRandomVector(chaosResult)
    mean = randomVector.getMean()
    covarianceMatrix = randomVector.getCovariance()
    stdDev = openturns.Point(outputDimension)
    for i in range(outputDimension):
        stdDev[i] = covarianceMatrix[i, i] ** 0.5

# quick summary
    basisSize = chaosResult.getReducedBasis().getSize()
    html = ""
    html += f"{self.getClassName()}\n"
    html += "<ul>\n"
    html += f"  <li>input dimension: {inputDimension}</li>\n"
    html += f"  <li>output dimension: {outputDimension}</li>\n"
    html += f"  <li>basis size: {basisSize}</li>\n"
    html += f"  <li>mean: {mean}</li>\n"
    html += f"  <li>std-dev: {stdDev}</li>\n"
    html += "</ul>\n"

    for i in range(outputDimension):
        if i > maximumNumberOfOutput:
            break
        if outputDimension > 1:
            html += f"Output marginal: {i}\n"

# Table of Sobol' indices
        html += "<table>\n"
# Header
        html += "  <tr>\n"
        html += "    <th>Input</th>\n"
        html += "    <th>Variable</th>\n"
        html += "    <th>Sobol' index</th>\n"
        html += "    <th>Total index</th>\n"
        html += "  </tr>\n"
# Content
        for j in range(inputDimension):
            html += "  <tr>\n"
            html += f"    <td>{j}</td>\n"
            html += f"    <td>{inputDescription[j]}</td>\n"
            sobolIndex = self.getSobolIndex(j, i)
            html += "    <td>" + sobolIndexFormat.format(sobolIndex) + "</td>\n"
            sobolIndex = self.getSobolTotalIndex(j, i)
            html += "    <td>" + sobolIndexFormat.format(sobolIndex) + "</td>\n"
            html += "  </tr>\n"

        html += "</table>\n"

# Compute the part of variance of each multi-index
        partOfVariance = self.getPartOfVariance(i)
# Sort marginal variances in decreasing order
        marginalPartOfVarianceSample = openturns.Sample.BuildFromPoint(partOfVariance)
        order = marginalPartOfVarianceSample.argsort(False)

# Table of part of variances indices
        html += "<table>\n"
# Header
        html += "  <tr>\n"
        html += "    <th>Index</th>\n"
        html += "    <th>Multi-index</th>\n"
        html += "    <th>Part of variance</th>\n"
        html += "  </tr>\n"
# Content
        for k in range(basisSize):
            sortedIndex = order[k]
            globalIndex = indices[sortedIndex]
            multiIndex = enumerateFunction(globalIndex)
            partOfVarianceIndex = marginalPartOfVarianceSample[sortedIndex]
            if partOfVarianceIndex[0] > partOfVarianceThreshold:
                html += "  <tr>\n"
                html += f"    <td>{sortedIndex}</td>\n"
                html += f"    <td>{multiIndex}</td>\n"
                html += "    <td>" + sobolIndexFormat.format(partOfVarianceIndex[0]) + "</td>\n"
                html += "  </tr>\n"

        html += "</table>\n"

    return html

FunctionalChaosSobolIndices._repr_html_ = __FunctionalChaosSobolIndices_repr_html

class MetaModelValidation(openturns.common.PersistentObject):
    r"""
    Scores a metamodel in order to perform its validation.

    Parameters
    ----------
    outputSample : 2-d sequence of float
        The output validation sample, not used during the learning step.

    metamodelPredictions: 2-d sequence of float
        The output prediction sample from the metamodel.

    Notes
    -----
    A `MetaModelValidation` object is used for the validation of a metamodel.
    For that purpose, a dataset independent of the learning step, is used to score the surrogate model.
    Its main functionalities are :

    - compute the coefficient of determination :math:`R^2` ;
    - get the residual sample and its non parametric distribution ;
    - draw a validation graph presenting the metamodel predictions against
      the model observations.

    More details on this topic are presented in :any:`cross_validation`.

    Examples
    --------
    In this example, we introduce the sinus model and approximate it with a least
    squares metamodel.
    Then we validate this metamodel using a test sample.

    >>> import openturns as ot
    >>> from math import pi
    >>> dist = ot.Uniform(-pi / 2, pi / 2)
    >>> # Define the model
    >>> model = ot.SymbolicFunction(['x'], ['sin(x)'])
    >>> # We can build several types of models (kriging, polynomial chaos expansion, ...)
    >>> # We use here a least squares expansion on canonical basis and compare
    >>> # the metamodel with the model
    >>> # Build the metamodel using a train sample
    >>> x_train = dist.getSample(25)
    >>> y_train = model(x_train)
    >>> total_degree = 3
    >>> polynomialCollection = [f'x^{degree + 1}' for degree in range(total_degree)]
    >>> basis = ot.SymbolicFunction(['x'], polynomialCollection)
    >>> designMatrix = basis(x_train)
    >>> myLeastSquares = ot.LinearLeastSquares(designMatrix, y_train)
    >>> myLeastSquares.run()
    >>> leastSquaresModel = myLeastSquares.getMetaModel()
    >>> metaModel = ot.ComposedFunction(leastSquaresModel, basis)
    >>> # Validate the metamodel using a test sample
    >>> x_test = dist.getSample(100)
    >>> y_test = model(x_test)
    >>> metamodelPredictions = metaModel(x_test)
    >>> val = ot.MetaModelValidation(y_test, metamodelPredictions)
    >>> # Compute the R2 score
    >>> r2Score = val.computeR2Score()
    >>> # Get the residual
    >>> residual = val.getResidualSample()
    >>> # Get the histogram of residuals
    >>> histoResidual = val.getResidualDistribution(False)
    >>> # Draw the validation graph
    >>> graph = val.drawValidation()
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.MetaModelValidation_getClassName(self)

    def __init__(self, *args):
        _metamodel.MetaModelValidation_swiginit(self, _metamodel.new_MetaModelValidation(*args))

    def __repr__(self):
        return _metamodel.MetaModelValidation___repr__(self)

    def getOutputSample(self):
        r"""
        Accessor to the output sample.

        Returns
        -------
        outputSample : :class:`~openturns.Sample`
            Output sample of a model evaluated apart.
        """
        return _metamodel.MetaModelValidation_getOutputSample(self)

    def getMetamodelPredictions(self):
        r"""
        Accessor to the output predictions from the metamodel.

        Returns
        -------
        outputMetamodelSample : :class:`~openturns.Sample`
            Output sample of the metamodel.
        """
        return _metamodel.MetaModelValidation_getMetamodelPredictions(self)

    def computeR2Score(self):
        r"""
        Compute the R2 score.

        Returns
        -------
        r2Score : :class:`~openturns.Point`
            The coefficient of determination R2

        Notes
        -----
        The coefficient of determination :math:`R^2` is the fraction of the
        variance of the output explained by the metamodel.
        It is defined as:

        .. math::
            R^2 = 1 - \operatorname{FVU}

        where :math:`\operatorname{FVU}` is the fraction of unexplained variance:

        .. math::
            \operatorname{FVU} = \frac{\operatorname{MSE}(\tilde{g}) }{\Var{Y}}

        where :math:`Y = g(\bdX)` is the output of the physical model :math:`g`,
        :math:`\Var{Y}` is the variance of the output and :math:`\operatorname{MSE}` is the 
        mean squared error of the metamodel:

        .. math::
            \operatorname{MSE}(\tilde{g}) = \Expect{\left(g(\bdX) - \tilde{g}(\bdX) \right)^2}.

        The sample :math:`R^2` is:

        .. math::
            \hat{R}^2 = 1 - \frac{\frac{1}{n} \sum_{j=1}^{n} \left(y^{(j)} - \tilde{g}\left(\bdx^{(j)}\right)\right)^2}{\hat{\sigma}^2_Y}

        where :math:`n \in \Nset` is the sample size, :math:`\tilde{g}` is the metamodel,
        :math:`\left\{\bdx^{(j)} \in \Rset^{n_X}\right\}_{j = 1, ..., n}` is the input experimental design,
        :math:`\left\{y^{(j)} \in \Rset\right\}_{j = 1, ..., n}` is the output of the model and
        :math:`\hat{\sigma}^2_Y` is the sample variance of the output:

        .. math::
            \hat{\sigma}^2_Y = \frac{1}{n - 1} \sum_{j=1}^{n} \left(y^{(j)} - \overline{y}\right)^2

        where :math:`\overline{y}` is the output sample mean:

        .. math::
            \overline{y} = \frac{1}{n} \sum_{j=1}^{n} y^{(j)}.
        """
        return _metamodel.MetaModelValidation_computeR2Score(self)

    def computeMeanSquaredError(self):
        r"""
        Accessor to the mean squared error.

        Returns
        -------
        meanSquaredError : :class:`~openturns.Point`
            The mean squared error of each marginal output dimension.

        Notes
        -----
        The sample mean squared error is:

        .. math::
            \widehat{\operatorname{MSE}} 
            = \frac{1}{n} \sum_{j=1}^{n} \left(y^{(j)} - \tilde{g}\left(\bdx^{(j)}\right)\right)^2

        where :math:`n \in \Nset` is the sample size, :math:`\tilde{g}` is the metamodel,
        :math:`\{\bdx^{(j)} \in \Rset^{n_X}\}_{j = 1, ..., n}` is the input experimental design and
        :math:`\{y^{(j)} \in \Rset\}_{j = 1, ..., n}` is the output of the model.

        If the output is multi-dimensional, the same calculations are repeated separately for
        each output marginal :math:`k` for :math:`k = 1, ..., n_y` where :math:`n_y \in \Nset`
        is the output dimension.
        """
        return _metamodel.MetaModelValidation_computeMeanSquaredError(self)

    def getResidualSample(self):
        r"""
        Compute the residual sample.

        Returns
        -------
        residual : :class:`~openturns.Sample`
            The residual sample.

        Notes
        -----
        The residual sample is given by :

        .. math::

            r^{(j)} = y^{(j)} - \tilde{g}\left(\vect{x}^{(j)}\right)

        for :math:`j = 1, ..., n` where :math:`n \in \Nset` is the sample size,
        :math:`y^{(j)}` is the model observation,
        :math:`\tilde{g}` is the metamodel and :math:`\vect{x}^{(j)}` is the :math:`j`-th input observation.

        If the output is multi-dimensional, the residual sample has dimension :math:`n_y \in \Nset`,
        where :math:`n_y` is the output dimension.
        """
        return _metamodel.MetaModelValidation_getResidualSample(self)

    def getResidualDistribution(self, smooth=True):
        r"""
        Compute the non parametric distribution of the residual sample.

        Parameters
        ----------
        smooth : bool
            Tells if distribution is smooth (true) or not.
            Default argument is true.

        Returns
        -------
        residualDistribution : :class:`~openturns.Distribution`
            The residual distribution.

        Notes
        -----
        The residual distribution is built thanks to :class:`~openturns.KernelSmoothing` if `smooth` argument is true. Otherwise, an histogram distribution is returned, thanks to :class:`~openturns.HistogramFactory`.
        """
        return _metamodel.MetaModelValidation_getResidualDistribution(self, smooth)

    def drawValidation(self):
        r"""
        Plot a model vs metamodel graph for visual validation.

        Returns
        -------
        graph : :class:`~openturns.GridLayout`
            The visual validation graph.

        Notes
        -----
        The plot presents the metamodel predictions depending on the model observations. 
        If the points are close to the diagonal line of the plot, then the 
        metamodel validation is satisfactory. 
        Points which are far away from the diagonal represent outputs 
        for which the metamodel is not accurate.

        If the output is multi-dimensional, the graph has 1 row and :math:`n_y \in \Nset`
        columns, where :math:`n_y` is the output dimension.
        """
        return _metamodel.MetaModelValidation_drawValidation(self)
    __swig_destroy__ = _metamodel.delete_MetaModelValidation

# Register MetaModelValidation in _metamodel:
_metamodel.MetaModelValidation_swigregister(MetaModelValidation)
class GeneralLinearModelResult(MetaModelResult):
    r"""
    General linear model result.

    Parameters
    ----------
    inputSample, outputSample : :class:`~openturns.Sample`
        The samples :math:`(\vect{x}_k)_{1 \leq k \leq N} \in \Rset^d` and :math:`(\vect{y}_k)_{1 \leq k \leq N}\in \Rset^p`.
    metaModel : :class:`~openturns.Function`
        The meta model: :math:`\tilde{\cM}: \Rset^d \rightarrow \Rset^p`, defined in :eq:metaModel.
    basis :  :class:`~openturns.Basis`
        Functional basis of size :math:`b` : :math:`(\varphi^l: \Rset^d \rightarrow \Rset^p)` for each :math:`l \in [1, b]`.
        Its size should be equal to zero if the trend is not estimated.
    trendCoef : sequence of float
        The trend coefficients vectors :math:`(\vect{\alpha}^1, \dots, \vect{\alpha}^p)` stored as a Point.
    covarianceModel : :class:`~openturns.CovarianceModel`
        Covariance function of the Gaussian process with its optimized parameters.
    optimalLogLikelihood : float
        The maximum log-likelihood corresponding to the model.

    Notes
    -----
    The structure is usually created by the method *run()* of a :class:`~openturns.GeneralLinearModelAlgorithm`, and obtained thanks to the *getResult()* method.

    The meta model :math:`\tilde{\cM}: \Rset^d \rightarrow \Rset^p` is defined by:

    .. math::
        :label: metaModel

        \tilde{\cM}(\vect{x}) = \left(
          \begin{array}{l}
            \mu_1(\vect{x}) \\
            \dots  \\
            \mu_p(\vect{x}) 
           \end{array}
         \right)

    where :math:`\mu_l(\vect{x}) = \sum_{j=1}^{b} \alpha_j^l \varphi_j^l(\vect{x})` and :math:`\varphi_j^l: \Rset^d \rightarrow \Rset` are the trend functions
    (the :math:`l-th` marginal of `\varphi(x)`).


    .. math::
        :label: metaModelWithT

        \tilde{\cM}(\vect{x}) = \left(
          \begin{array}{l}
            \mu_1\circ T(\vect{x}) \\
            \dots  \\
            \mu_p\circ T(\vect{x}) 
           \end{array}
         \right)

    Examples
    --------
    Create the model :math:`\cM: \Rset \mapsto \Rset` and the samples:

    >>> import openturns as ot
    >>> f = ot.SymbolicFunction(['x'],  ['x * sin(x)'])
    >>> sampleX = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]]
    >>> sampleY = f(sampleX)

    Create the algorithm:

    >>> basis = ot.Basis([ot.SymbolicFunction(['x'], ['x']), ot.SymbolicFunction(['x'], ['x^2'])])
    >>> covarianceModel = ot.GeneralizedExponential([2.0], 2.0)
    >>> algo = ot.GeneralLinearModelAlgorithm(sampleX, sampleY, covarianceModel, basis)
    >>> algo.run()

    Get the result:

    >>> result = algo.getResult()

    Get the meta model:

    >>> metaModel = result.getMetaModel()
    >>> graph = metaModel.draw(0.0, 7.0)
    >>> cloud = ot.Cloud(sampleX, sampleY)
    >>> cloud.setPointStyle('fcircle')
    >>> graph = ot.Graph()
    >>> graph.add(cloud)
    >>> graph.add(f.draw(0.0, 7.0))

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.GeneralLinearModelResult_getClassName(self)

    def __repr__(self):
        return _metamodel.GeneralLinearModelResult___repr__(self)

    def __str__(self, *args):
        return _metamodel.GeneralLinearModelResult___str__(self, *args)

    def getBasis(self):
        r"""
        Accessor to the functional basis.

        Returns
        -------
        basis : :class:`~openturns.Basis`
            Functional basis of size :math:`b` : :math:`(\varphi^l: \Rset^d \rightarrow \Rset^p)` for each :math:`l \in [1, b]`.

        Notes
        -----
        If the trend is not estimated, the collection is empty. 

        """
        return _metamodel.GeneralLinearModelResult_getBasis(self)

    def getTrendCoefficients(self):
        r"""
        Accessor to the trend coefficients.

        Returns
        -------
        trendCoef : :class:`~openturns.Point`
            The trend coefficients vectors :math:`(\vect{\alpha}^1, \dots, \vect{\alpha}^p)`

        """
        return _metamodel.GeneralLinearModelResult_getTrendCoefficients(self)

    def getCovarianceModel(self):
        r"""
        Accessor to the covariance model.

        Returns
        -------
        covModel : :class:`~openturns.CovarianceModel`
            The covariance model of the Gaussian process *W*.

        """
        return _metamodel.GeneralLinearModelResult_getCovarianceModel(self)

    def getNoise(self):
        r"""
        Accessor to the Gaussian process.

        Returns
        -------
        process : :class:`~openturns.Process`
            Returns the Gaussian process :math:`W` with the optimized parameters.

        """
        return _metamodel.GeneralLinearModelResult_getNoise(self)

    def getOptimalLogLikelihood(self):
        r"""
        Accessor to the optimal log-likelihood of the model.

        Returns
        -------
        optimalLogLikelihood : float
            The value of the log-likelihood corresponding to the model.

        """
        return _metamodel.GeneralLinearModelResult_getOptimalLogLikelihood(self)

    def __init__(self, *args):
        _metamodel.GeneralLinearModelResult_swiginit(self, _metamodel.new_GeneralLinearModelResult(*args))
    __swig_destroy__ = _metamodel.delete_GeneralLinearModelResult

# Register GeneralLinearModelResult in _metamodel:
_metamodel.GeneralLinearModelResult_swigregister(GeneralLinearModelResult)
class GeneralLinearModelAlgorithm(MetaModelAlgorithm):
    r"""
    Algorithm for the evaluation of general linear models.

    Refer to :any:`gaussian_process_regression`.

    Available constructors:
        GeneralLinearModelAlgorithm(*inputSample, outputSample, covarianceModel, keepCovariance=True*)

        GeneralLinearModelAlgorithm(*inputSample, outputSample, covarianceModel, basis, keepCovariance=True*)

    Parameters
    ----------
    inputSample, outputSample : 2-d sequence of float
        The samples :math:`(\vect{x}_k)_{1 \leq k \leq \sampleSize} \in \Rset^\inputDim` and
        :math:`(\vect{y}_k)_{1 \leq k \leq \sampleSize}\in \Rset^\outputDim`.

    covarianceModel : :class:`~openturns.CovarianceModel`
        Covariance model of the Gaussian process. See notes for the details.

    basis : :class:`~openturns.Basis`
        Functional basis to estimate the trend: :math:`(\varphi_j)_{1 \leq j \leq n_1}: \Rset^\inputDim \rightarrow \Rset`.
        If :math:`\outputDim > 1`, the same basis is used for each marginal output.

    keepCovariance : bool, optional
        Indicates whether the covariance matrix has to be stored in the result structure *GeneralLinearModelResult*.
        Default value is set in resource map key `GeneralLinearModelAlgorithm-KeepCovariance`

    Notes
    -----
    We suppose we have a sample :math:`(\vect{x}_k, \vect{y}_k)_{1 \leq k \leq \sampleSize}` where
    :math:`\sampleSize \in \Nset` is the sample size, :math:`\vect{y}_k = \model(\vect{x}_k)` for all :math:`k \in \{1, ..., \sampleSize\}`
    and :math:`\model:\Rset^\inputDim \mapsto \Rset^\outputDim` is the model.
    The objective is to build a metamodel :math:`\metaModel`, using a **general linear model**: the sample
    :math:`(\vect{y}_k)_{1 \leq k \leq \sampleSize}` is considered as the restriction of a Gaussian process
    :math:`\vect{Y}(\omega, \vect{x})` on :math:`(\vect{x}_k)_{1 \leq k \leq \sampleSize}`.
    The Gaussian process :math:`\vect{Y}(\omega, \vect{x})` is defined by:

    .. math::

        \vect{Y}(\omega, \vect{x}) = \vect{\mu}(\vect{x}) + \vect{W}(\omega, \vect{x})

    where:

    .. math::

        \vect{\mu}(\vect{x}) = \left(
          \begin{array}{l}
            \mu_1(\vect{x}) \\
            \vdots  \\
            \mu_\outputDim(\vect{x})
           \end{array}
         \right)

    with :math:`\mu_\ell(\vect{x}) = \sum_{j=1}^{n_\ell} \beta_j^\ell \varphi_j^\ell(\vect{x})`
    for any :math:`\ell \in \{1, ..., \outputDim\}`,
    where :math:`n_\ell \in \Nset` is the number trend functions of the :math:`\ell`-th output component, and
    :math:`\varphi_j^\ell: \Rset^\inputDim \rightarrow \Rset` the trend functions.
    The Gaussian process :math:`\vect{W}` is of dimension :math:`\outputDim` with zero mean and covariance function
    :math:`C = C(\vect{\theta}, \vect{\sigma}, \mat{R}, \vect{\lambda})` (see :any:`process_definitions`
    for the notations).

    We note:

    .. math::

        \vect{\beta}^\ell = \left(
          \begin{array}{l}
            \beta_1^\ell \\
            \vdots  \\
            \beta_{n_\ell}^\ell
           \end{array}
         \right) \in \Rset^{n_\ell}
         \quad \mbox{ and } \quad
         \vect{\beta} = \left(
          \begin{array}{l}
             \vect{\beta}^1\\
             \vdots  \\
             \vect{\beta}^\outputDim
           \end{array}
         \right)\in \Rset^{n_t}

    where :math:`n_t = \sum_{\ell = 1}^p n_\ell` is the total number of trend functions for all
    output dimensions.

    The *GeneralLinearModelAlgorithm* class estimates the coefficients
    :math:`(\beta_j^\ell)_{j=1, ..., n_\ell, \; \ell=1, ..., \outputDim}` and :math:`\vect{p}`
    where :math:`\vect{p}` is the vector of parameters of the covariance model, i.e. a subset of
    :math:`\vect{\theta}, \vect{\sigma}, \mat{R}, \vect{\lambda}`, that has been declared as
    *active* (by default, the full vectors :math:`\vect{\theta}` and :math:`\vect{\sigma}`).
    The estimation is done by maximizing the *reduced* log-likelihood of the model
    (see the equation :eq:`logLikelihood` below).

    **Estimation of the parameters** :math:`\beta_j^\ell` and :math:`\vect{p}`

    We note:

    .. math::

        \vect{y} = \left(
          \begin{array}{l}
            \vect{y}_1 \\
            \vdots  \\
            \vect{y}_\sampleSize
           \end{array}
         \right) \in \Rset^{\sampleSize \outputDim},
         \quad
         \vect{m}_{\vect{\beta}} = \left(
          \begin{array}{l}
            \vect{\mu}(\vect{x}_1) \\
            \vdots  \\
            \vect{\mu}(\vect{x}_\sampleSize)
           \end{array}
         \right) \in \Rset^{\sampleSize \outputDim}

    and

    .. math::

        \mat{C}_{\vect{p}} = \left(
          \begin{array}{lcl}
            \mat{C}_{11} & \dots &  \mat{C}_{1 \sampleSize}\\
            \vdots       &       & \vdots \\
            \mat{C}_{\sampleSize1} & \dots &  \mat{C}_{\sampleSize\sampleSize}
           \end{array}
         \right) \in \cS_{\sampleSize \outputDim}^+(\Rset)

    where :math:`\mat{C}_{ij} = C_{\vect{p}}(\vect{x}_i, \vect{x}_j)`.
    The model likelihood writes:

    .. math::

        \cL(\vect{\beta}, \vect{p};(\vect{x}_k, \vect{y}_k)_{1 \leq k \leq \sampleSize}) 
        = \dfrac{1}{(2\pi)^{\frac{1}{2} \sampleSize \outputDim} \left|\det\left(\mat{C}_{\vect{p}}\right)\right|^{\frac{1}{2}}}
        \exp\left( -\dfrac{1}{2}\Tr{\left( \vect{y}-\vect{m} \right)} \mat{C}_{\vect{p}}^{-1}  \left( \vect{y}-\vect{m} \right)  \right)

    Let :math:`\mat{L}_{\vect{p}}` be the Cholesky factor of :math:`\mat{C}_{\vect{p}}`, i.e. the lower triangular matrix
    with positive diagonal such that :math:`\mat{L}_{\vect{p}} \,\Tr{\mat{L}_{\vect{p}}} = \mat{C}_{\vect{p}}`.
    Therefore the log-likelihood is:

    .. math::
        :label: logLikelihood

        \log \cL(\vect{\beta}, \vect{p};(\vect{x}_k, \vect{y}_k)_{1 \leq k \leq \sampleSize}) 
        = \alpha - \log \left( \det \left(\mat{L}_{\vect{p}}\right) \right)
        -\dfrac{1}{2}  \left\| \mat{L}_{\vect{p}}^{-1}(\vect{y}-\vect{m}_{\vect{\beta}}) \right\|^2_2

    where :math:`\alpha \in \Rset` is a constant independent of :math:`\vect{\beta}` and :math:`\vect{p}`.
    The maximization of :eq:`logLikelihood` leads to the following optimality condition for :math:`\vect{\beta}`:

    .. math::

        \vect{\beta}^*(\vect{p}^*)
        = \argmin_{\vect{\beta}} \left\| \mat{L}_{\vect{p}^*}^{-1} \left(\vect{y} - \vect{m}_{\vect{\beta}} \right) \right\|^2_2

    This expression of :math:`\vect{\beta}^*` as a function of :math:`\vect{p}^*` is taken as a
    general relation between :math:`\vect{\beta}` and :math:`\vect{p}` and is substituted into
    :eq:`logLikelihood`, leading to a *reduced log-likelihood* function depending solely on :math:`\vect{p}`.

    In the particular case where :math:`\outputDim = \dim(\vect{\sigma}) = 1` and :math:`\sigma` is a part of
    :math:`\vect{p}`, then a further reduction is possible. In this case, let :math:`\vect{q}` be
    the vector :math:`\vect{p}` in which :math:`\sigma` has been substituted by 1.
    Therefore:

    .. math::

        \left\| \mat{L}_{\vect{p}}^{-1}(\vect{y}-\vect{m}_{\vect{\beta}}) \right\|^2 
        = \frac{1}{\sigma^2} \left\| \mat{L}_{\vect{q}}^{-1} \left(\vect{y} - \vect{m}_{\vect{\beta}} \right) \right\|^2_2.

    This shows that :math:`\vect{\beta}^*` is a function of :math:`\vect{q}^*` only, and the optimality
    condition for :math:`\sigma` reads:

    .. math::

        \vect{\sigma}^*(\vect{q}^*)
        =\dfrac{1}{\sampleSize} 
        \left\| \mat{L}_{\vect{q}^*}^{-1} \left(\vect{y} - \vect{m}_{\vect{\beta}^*(\vect{q}^*)}\right) \right\|^2_2.

    This leads to a further reduction of the log-likelihood function where both :math:`\vect{\beta}`
    and :math:`\sigma` are replaced by their expression in terms of :math:`\vect{q}`.

    The default optimizer is :class:`~openturns.TNC` and can be changed thanks to the *setOptimizationAlgorithm* method.
    User could also change the default optimization solver by setting the `GeneralLinearModelAlgorithm-DefaultOptimizationAlgorithm`
    resource map key to one of the :class:`~openturns.NLopt` solver names.

    It is also possible to proceed as follows:

    - ask for the reduced log-likelihood function of the *GeneralLinearModelAlgorithm* thanks to the *getObjectiveFunction()* method
    - optimize it with respect to the parameters :math:`\vect{\theta}` and  :math:`\vect{\sigma}` using any
      optimization algorithms (that can take into account some additional constraints if needed)
    - set the optimal parameter value into the covariance model used in the *GeneralLinearModelAlgorithm*
    - tell the algorithm not to optimize the parameter using *setOptimizeParameters*

    The behaviour of the reduction is controlled by the following keys in :class:`~openturns.ResourceMap`:

    - *ResourceMap.SetAsBool('GeneralLinearModelAlgorithm-UseAnalyticalAmplitudeEstimate', True)* to use the reduction associated to :math:`\sigma`. It has no effect if :math:`\outputDim > 1` or if :math:`\outputDim = 1` and :math:`\sigma` is not part of :math:`\vect{p}`
    - *ResourceMap.SetAsBool('GeneralLinearModelAlgorithm-UnbiasedVariance', True)* allows one to use the *unbiased* estimate of :math:`\sigma` where :math:`\dfrac{1}{\sampleSize}` is replaced by :math:`\dfrac{1}{\sampleSize - d_p}` in the optimality condition for :math:`\sigma`, where :math:`d_p \in \Nset` is the dimension of the vector :math:`\vect{p}`.

    With huge samples, the `hierarchical matrix <http://en.wikipedia.org/wiki/Hierarchical_matrix>`_  implementation could be used if OpenTURNS had been compiled with `hmat-oss` support.

    This implementation, which is based on a compressed representation of an approximated covariance matrix (and its Cholesky factor),
    has a better complexity both in terms of memory requirements and floating point operations.
    To use it, the `GeneralLinearModelAlgorithm-LinearAlgebra` resource map key should be set to `HMAT`. Default value of the key is `LAPACK`.

    A known centered gaussian observation noise :math:`\epsilon_k` can be taken into account
    with :func:`setNoise()`:

    .. math::
        \widehat{\vect{y}}_k 
        = \vect{y}_k + \epsilon_k, \quad \epsilon_k \sim \mathcal{N}\left(0, \tau_k^2\right)

    Examples
    --------
    Create the model :math:`\model: \Rset \mapsto \Rset` and the samples:

    >>> import openturns as ot
    >>> f = ot.SymbolicFunction(['x'], ['x+x * sin(x)'])
    >>> inputSample = ot.Sample([[1.0], [3.0], [5.0], [6.0], [7.0], [8.0]])
    >>> outputSample = f(inputSample)

    Create the algorithm:

    >>> f1 = ot.SymbolicFunction(['x'], ['sin(x)'])
    >>> f2 = ot.SymbolicFunction(['x'], ['x'])
    >>> f3 = ot.SymbolicFunction(['x'], ['cos(x)'])
    >>> basis = ot.Basis([f1,f2, f3])
    >>> covarianceModel = ot.SquaredExponential([1.0])
    >>> covarianceModel.setActiveParameter([])
    >>> algo = ot.GeneralLinearModelAlgorithm(inputSample, outputSample, covarianceModel, basis)
    >>> algo.run()

    Get the resulting meta model:

    >>> result = algo.getResult()
    >>> metamodel = result.getMetaModel()

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.GeneralLinearModelAlgorithm_getClassName(self)
    LAPACK = _metamodel.GeneralLinearModelAlgorithm_LAPACK
    HMAT = _metamodel.GeneralLinearModelAlgorithm_HMAT

    def __repr__(self):
        return _metamodel.GeneralLinearModelAlgorithm___repr__(self)

    def run(self):
        r"""
        Compute the response surface.

        Notes
        -----
        It computes the response surface and creates a
        :class:`~openturns.GeneralLinearModelResult` structure containing all the results.
        """
        return _metamodel.GeneralLinearModelAlgorithm_run(self)

    def getResult(self):
        r"""
        Get the results of the metamodel computation.

        Returns
        -------
        result : :class:`~openturns.GeneralLinearModelResult`
            Structure containing all the results obtained after computation
            and created by the method :py:meth:`run`.

        """
        return _metamodel.GeneralLinearModelAlgorithm_getResult(self)

    def getObjectiveFunction(self):
        r"""
        Accessor to the log-likelihood function that writes as argument of the covariance's model parameters.

        Returns
        -------
        logLikelihood : :class:`~openturns.Function`
            The log-likelihood function degined in :eq:`logLikelihood` as a function of :math:`(\vect{\theta}, \vect{\sigma})`.

        Notes
        -----
        The log-likelihood function may be useful for some postprocessing: maximization using external optimizers for example.


        Examples
        --------
        Create the model :math:`\model: \Rset \mapsto \Rset` and the samples:

        >>> import openturns as ot
        >>> f = ot.SymbolicFunction(['x0'], ['x0 * sin(x0)'])
        >>> inputSample = ot.Sample([[1.0], [3.0], [5.0], [6.0], [7.0], [8.0]])
        >>> outputSample = f(inputSample)

        Create the algorithm:

        >>> basis = ot.ConstantBasisFactory().build()
        >>> covarianceModel = ot.SquaredExponential(1)
        >>> algo = ot.GeneralLinearModelAlgorithm(inputSample, outputSample, covarianceModel, basis)
        >>> algo.run()

        Get the log-likelihood function:

        >>> likelihoodFunction = algo.getObjectiveFunction()

        """
        return _metamodel.GeneralLinearModelAlgorithm_getObjectiveFunction(self)

    def getOptimizationAlgorithm(self):
        r"""
        Accessor to solver used to optimize the covariance model parameters.

        Returns
        -------
        algorithm : :class:`~openturns.OptimizationAlgorithm`
            Solver used to optimize the covariance model parameters.
            Default optimizer is :class:`~openturns.TNC`
        """
        return _metamodel.GeneralLinearModelAlgorithm_getOptimizationAlgorithm(self)

    def setOptimizationAlgorithm(self, solver):
        r"""
        Accessor to the solver used to optimize the covariance model parameters.

        Parameters
        ----------
        algorithm : :class:`~openturns.OptimizationAlgorithm`
            Solver used to optimize the covariance model parameters.
        """
        return _metamodel.GeneralLinearModelAlgorithm_setOptimizationAlgorithm(self, solver)

    def getOptimizeParameters(self):
        r"""
        Accessor to the covariance model parameters optimization flag.

        Returns
        -------
        optimizeParameters : bool
            Whether to optimize the covariance model parameters.
        """
        return _metamodel.GeneralLinearModelAlgorithm_getOptimizeParameters(self)

    def setOptimizeParameters(self, optimizeParameters):
        r"""
        Accessor to the covariance model parameters optimization flag.

        Parameters
        ----------
        optimizeParameters : bool
            Whether to optimize the covariance model parameters.
        """
        return _metamodel.GeneralLinearModelAlgorithm_setOptimizeParameters(self, optimizeParameters)

    def setOptimizationBounds(self, optimizationBounds):
        r"""
        Optimization bounds accessor.

        Parameters
        ----------
        bounds : :class:`~openturns.Interval`
            Bounds for covariance model parameter optimization.

        Notes
        -----
        Parameters involved by this method are:

         - Scale parameters,
         - Amplitude parameters if output dimension is greater than one or
           analytical sigma disabled,
         - Additional parameters.

        Lower & upper bounds are defined in resource map.
        Default lower upper bounds value for all parameters is
        :math:`10^{-2}` and defined thanks to the
        `GeneralLinearModelAlgorithm-DefaultOptimizationLowerBound`
        resource map key.

        For scale parameters, default upper bounds are set as :math:`2`
        times the difference between the max and min values of `X` for
        each coordinate, `X` being the (transformed) input sample.
        The value :math:`2` is defined in resource map
        (`GeneralLinearModelAlgorithm-DefaultOptimizationScaleFactor`).

        Finally for other parameters (amplitude,...), default upper bound is set
        to :math:`100` (corresponding resource map key is
        `GeneralLinearModelAlgorithm-DefaultOptimizationUpperBound`)

        """
        return _metamodel.GeneralLinearModelAlgorithm_setOptimizationBounds(self, optimizationBounds)

    def getOptimizationBounds(self):
        r"""
        Optimization bounds accessor.

        Returns
        -------
        bounds : :class:`~openturns.Interval`
            Bounds for covariance model parameter optimization.
        """
        return _metamodel.GeneralLinearModelAlgorithm_getOptimizationBounds(self)

    def setNoise(self, noise):
        r"""
        Observation noise variance accessor.

        Parameters
        ----------
        noise : sequence of positive float
            The noise variance :math:`\tau_k^2` of each output value.
        """
        return _metamodel.GeneralLinearModelAlgorithm_setNoise(self, noise)

    def getNoise(self):
        r"""
        Observation noise variance accessor.

        Parameters
        ----------
        noise : sequence of positive float
            The noise variance :math:`\tau_k^2` of each output value.
        """
        return _metamodel.GeneralLinearModelAlgorithm_getNoise(self)

    def __init__(self, *args):
        _metamodel.GeneralLinearModelAlgorithm_swiginit(self, _metamodel.new_GeneralLinearModelAlgorithm(*args))
    __swig_destroy__ = _metamodel.delete_GeneralLinearModelAlgorithm

# Register GeneralLinearModelAlgorithm in _metamodel:
_metamodel.GeneralLinearModelAlgorithm_swigregister(GeneralLinearModelAlgorithm)
class KrigingAlgorithm(MetaModelAlgorithm):
    r"""
    Kriging algorithm.

    Refer to :any:`gaussian_process_regression`.


    Parameters
    ----------
    inputSample, outputSample : 2-d sequence of float
        The samples :math:`(\vect{x}_k)_{1 \leq k \leq N} \in \Rset^d` and :math:`(\vect{y}_k)_{1 \leq k \leq N}\in \Rset^p` upon which the meta-model is built.
    covarianceModel : :class:`~openturns.CovarianceModel`
        Covariance model used for the underlying Gaussian process assumption.
    basis : :class:`~openturns.Basis`, optional
        Functional basis to estimate the trend (universal kriging): :math:`(\varphi_j)_{1 \leq j \leq n_1}: \Rset^d \rightarrow \Rset`.
        If :math:`p>1`, the same basis is used for each marginal output.

    Notes
    -----
    We suppose we have a sample :math:`(\vect{x}_k, \vect{y}_k)_{1 \leq k \leq N}` where :math:`\vect{y}_k = \cM(\vect{x}_k)` for all *k*, with :math:`\cM:\Rset^d \mapsto \Rset^p` the model.

    The meta model *Kriging* is based on the same principles as those of the general linear model: it assumes that the sample :math:`(\vect{y}_k)_{1 \leq k \leq N}` is considered as the trace of a Gaussian process :math:`\vect{Y}(\omega, \vect{x})` on :math:`(\vect{x}_k)_{1 \leq k \leq N}`. The Gaussian process :math:`\vect{Y}(\omega, \vect{x})` is defined by:


    .. math::
        :label: metaModelKrigAlgo

        \vect{Y}(\omega, \vect{x}) = \vect{\mu}(\vect{x}) + W(\omega, \vect{x})

    where:

    .. math::

        \vect{\mu}(\vect{x}) = \left(
          \begin{array}{l}
            \mu_1(\vect{x}) \\
            \dots  \\
            \mu_p(\vect{x})
           \end{array}
         \right)

    with :math:`\mu_l(\vect{x}) = \sum_{j=1}^{n_l} \beta_j^l \varphi_j^l(\vect{x})` and :math:`\varphi_j^l: \Rset^d \rightarrow \Rset` the trend functions.

    :math:`W` is a Gaussian process of dimension *p* with zero mean and covariance function :math:`C = C(\vect{\theta}, \vect{\sigma}, \mat{R}, \vect{\lambda})` (see :class:`~openturns.CovarianceModel` for the notations).

    The estimation of the all parameters (the trend coefficients :math:`\beta_j^l`, the scale :math:`\vect{\theta}` and the amplitude :math:`\vect{\sigma}`) are made by the :class:`~openturns.GeneralLinearModelAlgorithm` class.

    The Kriging algorithm makes the general linear model interpolating on the input samples. The Kriging meta model :math:`\tilde{\cM}` is defined by:


    .. math::

        \tilde{\cM}(\vect{x}) =  \vect{\mu}(\vect{x}) + \Expect{\vect{Y}(\omega, \vect{x})\, | \,  \cC}

    where :math:`\cC` is the condition :math:`\vect{Y}(\omega, \vect{x}_k) = \vect{y}_k` for each :math:`k \in [1, N]`.

    :eq:`metaModelKrigAlgo` writes:

    .. math::

        \tilde{\cM}(\vect{x}) = \vect{\mu}(\vect{x}) + \Cov{\vect{Y}(\omega, \vect{x}), (\vect{Y}(\omega, \vect{x}_1), \dots, \vect{Y}(\omega, \vect{x}_N))} \vect{\gamma}

    where :math:`\Cov{\vect{Y}(\omega, \vect{x}), (\vect{Y}(\omega, \vect{x}_1), \dots, \vect{Y}(\omega, \vect{x}_N))} = \left( \mat{C}( \vect{x},  \vect{x}_1) | \dots | \mat{C}( \vect{x},  \vect{x}_N)  \right)` is a matrix in :math:`\cM_{p,NP}(\Rset)` and :math:`\vect{\gamma} = \mat{C}^{-1}(\vect{y}-\vect{m})`.

    A known centered gaussian observation noise :math:`\epsilon_k` can be taken into account
    with :func:`setNoise()`:

    .. math:: \hat{\vect{y}}_k = \vect{y}_k + \epsilon_k, \epsilon_k \sim \mathcal{N}(0, \tau_k^2)

    Examples
    --------
    Create the model :math:`\cM: \Rset \mapsto \Rset` and the samples:

    >>> import openturns as ot
    >>> f = ot.SymbolicFunction(['x'],  ['x * sin(x)'])
    >>> sampleX = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0]]
    >>> sampleY = f(sampleX)

    Create the algorithm:

    >>> basis = ot.Basis([ot.SymbolicFunction(['x'], ['x']), ot.SymbolicFunction(['x'], ['x^2'])])
    >>> covarianceModel = ot.SquaredExponential([1.0])
    >>> covarianceModel.setActiveParameter([])
    >>> algo = ot.KrigingAlgorithm(sampleX, sampleY, covarianceModel, basis)
    >>> algo.run()

    Get the resulting meta model:

    >>> result = algo.getResult()
    >>> metamodel = result.getMetaModel()

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.KrigingAlgorithm_getClassName(self)

    def __repr__(self):
        return _metamodel.KrigingAlgorithm___repr__(self)

    def run(self):
        r"""
        Compute the response surface.

        Notes
        -----
        It computes the kriging response surface and creates a
        :class:`~openturns.KrigingResult` structure containing all the results.
        """
        return _metamodel.KrigingAlgorithm_run(self)

    def getResult(self):
        r"""
        Get the results of the metamodel computation.

        Returns
        -------
        result : :class:`~openturns.KrigingResult`
            Structure containing all the results obtained after computation
            and created by the method :py:meth:`run`.

        """
        return _metamodel.KrigingAlgorithm_getResult(self)

    def getOptimizationAlgorithm(self):
        r"""
        Accessor to solver used to optimize the covariance model parameters.

        Returns
        -------
        solver : :class:`~openturns.OptimizationAlgorithm`
            Solver used to optimize the covariance model parameters.
        """
        return _metamodel.KrigingAlgorithm_getOptimizationAlgorithm(self)

    def setOptimizationAlgorithm(self, solver):
        r"""
        Accessor to the solver used to optimize the covariance model parameters.

        Parameters
        ----------
        solver : :class:`~openturns.OptimizationAlgorithm`
            Solver used to optimize the covariance model parameters.

        Examples
        --------
        Create the model :math:`\cM: \Rset \mapsto \Rset` and the samples:

        >>> import openturns as ot
        >>> input_data = ot.Uniform(-1.0, 2.0).getSample(10)
        >>> model = ot.SymbolicFunction(['x'], ['x-1+sin(pi_*x/(1+0.25*x^2))'])
        >>> output_data = model(input_data)

        Create the Kriging algorithm with the optimizer option:

        >>> basis = ot.Basis([ot.SymbolicFunction(['x'], ['0.0'])])
        >>> thetaInit = 1.0
        >>> covariance = ot.GeneralizedExponential([thetaInit], 2.0)
        >>> bounds = ot.Interval(1e-2,1e2)
        >>> algo = ot.KrigingAlgorithm(input_data, output_data, covariance, basis)
        >>> algo.setOptimizationBounds(bounds)

        """
        return _metamodel.KrigingAlgorithm_setOptimizationAlgorithm(self, solver)

    def setOptimizationBounds(self, optimizationBounds):
        r"""
        Accessor to the optimization bounds.

        Parameters
        ----------
        optimizationBounds : :class:`~openturns.Interval`
            The bounds used for numerical optimization of the likelihood.

        Notes
        -----
        See :class:`~openturns.GeneralLinearModelAlgorithm` class for more details,
        particularly :meth:`~openturns.GeneralLinearModelAlgorithm.setOptimizationBounds`.
        """
        return _metamodel.KrigingAlgorithm_setOptimizationBounds(self, optimizationBounds)

    def getOptimizationBounds(self):
        r"""
        Accessor to the optimization bounds.

        Returns
        -------
        optimizationBounds : :class:`~openturns.Interval`
            The bounds used for numerical optimization of the likelihood.
        """
        return _metamodel.KrigingAlgorithm_getOptimizationBounds(self)

    def getReducedLogLikelihoodFunction(self):
        r"""
        Accessor to the reduced log-likelihood function that writes as argument of the covariance's model parameters.

        Returns
        -------
        reducedLogLikelihood : :class:`~openturns.Function`
            The *potentially* reduced log-likelihood function.

        Notes
        -----
        We use the same notations as in :class:`~openturns.CovarianceModel` and :class:`~openturns.GeneralLinearModelAlgorithm` : :math:`\vect{\theta}` refers to the scale parameters and
        :math:`\vect{\sigma}` the amplitude. We can consider three situations here:

          - Output dimension is :math:`\geq 2`. In that case, we get the **full** log-likelihood function :math:`\mathcal{L}(\vect{\theta}, \vect{\sigma})`.

          - Output dimension is **1** and the `GeneralLinearModelAlgorithm-UseAnalyticalAmplitudeEstimate` key of :class:`~openturns.ResourceMap` is set to *True*.
            The amplitude parameter of the covariance model :math:`\vect{\theta}` is in the active set of parameters and thus we get the **reduced**
            log-likelihood function :math:`\mathcal{L}(\vect{\theta})`.

          - Output dimension is **1** and the `GeneralLinearModelAlgorithm-UseAnalyticalAmplitudeEstimate` key of :class:`~openturns.ResourceMap` is set to *False*.
            In that case, we get the **full** log-likelihood :math:`\mathcal{L}(\vect{\theta}, \vect{\sigma})`.

        The reduced log-likelihood function may be useful for some pre/postprocessing: visualisation of the maximizer, use of an external optimizers to maximize the reduced log-likelihood etc.


        Examples
        --------
        Create the model :math:`\cM: \Rset \mapsto \Rset` and the samples:

        >>> import openturns as ot
        >>> f = ot.SymbolicFunction(['x0'], ['x0 * sin(x0)'])
        >>> inputSample = ot.Sample([[1.0], [3.0], [5.0], [6.0], [7.0], [8.0]])
        >>> outputSample = f(inputSample)

        Create the algorithm:

        >>> basis = ot.ConstantBasisFactory().build()
        >>> covarianceModel = ot.SquaredExponential(1)
        >>> algo = ot.KrigingAlgorithm(inputSample, outputSample, covarianceModel, basis)
        >>> algo.run()

        Get the reduced log-likelihood function:

        >>> reducedLogLikelihoodFunction = algo.getReducedLogLikelihoodFunction()

        """
        return _metamodel.KrigingAlgorithm_getReducedLogLikelihoodFunction(self)

    def getOptimizeParameters(self):
        r"""
        Accessor to the covariance model parameters optimization flag.

        Returns
        -------
        optimizeParameters : bool
            Whether to optimize the covariance model parameters.
        """
        return _metamodel.KrigingAlgorithm_getOptimizeParameters(self)

    def setOptimizeParameters(self, optimizeParameters):
        r"""
        Accessor to the covariance model parameters optimization flag.

        Parameters
        ----------
        optimizeParameters : bool
            Whether to optimize the covariance model parameters.
        """
        return _metamodel.KrigingAlgorithm_setOptimizeParameters(self, optimizeParameters)

    def setNoise(self, noise):
        r"""
        Observation noise variance accessor.

        Parameters
        ----------
        noise : sequence of positive float
            The noise variance :math:`\tau_k^2` of each output value.
        """
        return _metamodel.KrigingAlgorithm_setNoise(self, noise)

    def getNoise(self):
        r"""
        Observation noise variance accessor.

        Returns
        -------
        noise : sequence of positive float
            The noise variance :math:`\tau_k^2` of each output value.
        """
        return _metamodel.KrigingAlgorithm_getNoise(self)

    def setMethod(self, method):
        r"""
        Linear algebra method set accessor.

        Parameters
        ----------
        method : str
               Used linear algebra method.
               Value should be `LAPACK` or `HMAT`

        Notes
        -----
        The setter update the implementation and require new evaluation.
        We might also use the ResourceMap key to set the method when instantiating the algorithm.
        For that purpose, we can use ResourceMap.SetAsString(`GeneralLinearModelAlgorithm-LinearAlgebra`, key)
        with `key` being `HMAT` or `LAPACK`.
        """
        return _metamodel.KrigingAlgorithm_setMethod(self, method)

    def getMethod(self):
        r"""
        Linear algebra method accessor.

        Returns
        -------
        method : str
               Used linear algebra method.
        """
        return _metamodel.KrigingAlgorithm_getMethod(self)

    def __init__(self, *args):
        _metamodel.KrigingAlgorithm_swiginit(self, _metamodel.new_KrigingAlgorithm(*args))
    __swig_destroy__ = _metamodel.delete_KrigingAlgorithm

# Register KrigingAlgorithm in _metamodel:
_metamodel.KrigingAlgorithm_swigregister(KrigingAlgorithm)
class LinearModelStepwiseAlgorithm(openturns.common.PersistentObject):
    r"""
    Stepwise linear model algorithm.

    Parameters
    ----------
    inputSample, outputSample : 2-d sequence of float
        The input and output samples of a model.
    basis : :class:`~openturns.Basis`
        Functional basis to estimate the trend.
    minimalIndices : sequence of int
        The indices of minimal model
    direction : int, default=FORWARD
        BACKWARD, FORWARD or BOTH.
    startIndices : sequence of int, default=[]
         The indices of start model used for the stepwise regression method.
         Can only be specified in BOTH mode.

    See Also
    --------
    LinearModelAlgorithm, LinearModelResult

    Notes
    -----
    The objective is to select the best linear regression model by using the
    stepwise method. Starting from the `basis` and `minimalIndices`, the stepwise
    strategy consists in adding basis elements (`FORWARD`), dropping
    some (`BACKWARD`) or adding and dropping (`BOTH` strategy) some
    elements. At each step, we get a model. We compute the corresponding penalty
    (BIC or AIC) and we continue repeatedly this process until the penalty could
    not be improved or the maximum iterations number is reached.
    Finally we get a regression model between the scalar variable :math:`Y`
    and the :math:`n`-dimensional one :math:`\vect{X} = (X_i)_{i \leq n}` writes as follows:

    .. math::

        \tilde{Y} = a_0 + \sum_{i \in I} a_i \phi_i(X) + \epsilon

    where :math:`\epsilon` is the residual, supposed to follow the standard Normal
    distribution, :math:`\phi_i` the i-th element of the basis.


    Examples
    --------
    Definition of the data set

    >>> import openturns as ot
    >>> ot.RandomGenerator.SetSeed(0)
    >>> distribution = ot.Normal()
    >>> func = ot.SymbolicFunction(['x1','x2', 'x3'], ['x1 + x2 + sin(x2 * 2 * pi_)/5 + 1e-3 * x3'])
    >>> dimension = 3
    >>> distribution = ot.JointDistribution([ot.Normal()]*dimension)
    >>> input_sample = distribution.getSample(20)
    >>> output_sample = func(input_sample)

    Creation of a basis

    >>> functions = []
    >>> input_description = ['x1','x2', 'x3']
    >>> functions.append(ot.SymbolicFunction(input_description, ['1.0'])) #Constant term
    >>> for i in range(dimension): #Linear terms
    ...     functions.append(ot.SymbolicFunction(input_description, [input_description[i]])) 
    >>> basis = ot.Basis(functions)

    Stepwise regression

    >>> minimalIndices = [0]
    >>> direction = ot.LinearModelStepwiseAlgorithm.BACKWARD
    >>> penalty = 2.0 #Akaike Information Criterion, log(n) can be used for a BIC
    >>> algo_forward = ot.LinearModelStepwiseAlgorithm(input_sample, output_sample, basis, minimalIndices, direction)
    >>> algo_forward.setPenalty(penalty)
    >>> algo_forward.run()
    >>> result_forward = algo_forward.getResult()

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.LinearModelStepwiseAlgorithm_getClassName(self)
    BACKWARD = _metamodel.LinearModelStepwiseAlgorithm_BACKWARD
    FORWARD = _metamodel.LinearModelStepwiseAlgorithm_FORWARD
    BOTH = _metamodel.LinearModelStepwiseAlgorithm_BOTH

    def __repr__(self):
        return _metamodel.LinearModelStepwiseAlgorithm___repr__(self)

    def __str__(self, *args):
        return _metamodel.LinearModelStepwiseAlgorithm___str__(self, *args)

    def getInputSample(self):
        r"""
        Accessor to the input sample.

        Returns
        -------
        input_sample : :class:`~openturns.Sample`
            Input sample.
        """
        return _metamodel.LinearModelStepwiseAlgorithm_getInputSample(self)

    def getOutputSample(self):
        r"""
        Accessor to the output sample.

        Returns
        -------
        output_sample : :class:`~openturns.Sample`
            Output sample.
        """
        return _metamodel.LinearModelStepwiseAlgorithm_getOutputSample(self)

    def getDirection(self):
        r"""
        Accessor to the direction.

        Returns
        -------
        direction : int
            Direction.
        """
        return _metamodel.LinearModelStepwiseAlgorithm_getDirection(self)

    def setPenalty(self, penalty):
        r"""
        Accessor to the penalty.

        Parameters
        ----------
        penalty : positive float
             The multiple of the degrees of freedom used for the penalty of the stepwise regression method:

             - 2      Akaike   information criterion (AIC) (default)
             - log(n) Bayesian information criterion (BIC)
        """
        return _metamodel.LinearModelStepwiseAlgorithm_setPenalty(self, penalty)

    def getPenalty(self):
        r"""
        Accessor to the penalty.

        Returns
        -------
        penalty : float
            Penalty.
        """
        return _metamodel.LinearModelStepwiseAlgorithm_getPenalty(self)

    def setMaximumIterationNumber(self, maximumIteration):
        r"""
        Accessor to the maximum iteration number.

        Parameters
        ----------
        maximum_iteration : int
             The maximum number of iterations of the stepwise regression method.
        """
        return _metamodel.LinearModelStepwiseAlgorithm_setMaximumIterationNumber(self, maximumIteration)

    def getMaximumIterationNumber(self):
        r"""
        Accessor to the maximum iteration number.

        Returns
        -------
        maximum_iteration : int
            Maximum number of iterations.
        """
        return _metamodel.LinearModelStepwiseAlgorithm_getMaximumIterationNumber(self)

    def run(self):
        r"""Run the algorithm."""
        return _metamodel.LinearModelStepwiseAlgorithm_run(self)

    def getResult(self):
        r"""
        Accessor to the result.

        Returns
        -------
        result : :class:`~openturns.LinearModelResult`
            The result.
        """
        return _metamodel.LinearModelStepwiseAlgorithm_getResult(self)

    def __init__(self, *args):
        _metamodel.LinearModelStepwiseAlgorithm_swiginit(self, _metamodel.new_LinearModelStepwiseAlgorithm(*args))
    __swig_destroy__ = _metamodel.delete_LinearModelStepwiseAlgorithm

# Register LinearModelStepwiseAlgorithm in _metamodel:
_metamodel.LinearModelStepwiseAlgorithm_swigregister(LinearModelStepwiseAlgorithm)
class LinearModelAlgorithm(MetaModelAlgorithm):
    r"""
    Class used to create a linear regression model.

    Parameters
    ----------
    XSample : 2-d sequence of float
        The input samples of a model.

    YSample : 2-d sequence of float
        The output samples of a model, must be of dimension 1.

    basis : :class:`~openturns.Basis`
        Optional.
        The :math:`\phi` basis .

    See Also
    --------
    LinearModelResult

    Notes
    -----
    This class fits a  linear regression model between a scalar variable :math:`Y` and some
    :math:`p` scalar regressors :math:`(X_1, \dots, X_p)`. The model is estimated from
    :math:`\sampleSize` experiences that have provided an output sample
    of :math:`Y` related to an input sample of the regressors :math:`\vect{X} = (X_1, \dots, X_p)`.

    Let :math:`\vect{Y} = (Y_1, \dots, Y_\sampleSize)` be
    the output sample and :math:`(\vect{X}^1, \dots, \vect{X}^\sampleSize)` the input
    sample, where :math:`\vect{X}^i = (X_1^i, \dots, X_p^i)`.

    The linear model can be defined with or without a functional basis. If no basis is
    specified, the model is:

    .. math::
        :label: modelNoBase

        Y = a_0 + \sum_{k=1}^{p} a_k X_k + \epsilon

    where :math:`a_0, a_1, ..., a_{p} \in \Rset` are scalar coefficients and
    :math:`\epsilon` a random
    variable with zero mean and constant variance :math:`\sigma^2` independent from
    the coefficients :math:`a_k`.

    Let the :math:`\hat{Y}_i` for :math:`1 \leq i \leq \sampleSize` be the fitted values, defined by:

    .. math::
        :label: fittedValue

        \hat{Y}_i = \hat{a}_0 + \sum_{k=1}^{p} \hat{a}_k X_k^i

    where :math:`\hat{\vect{a}} = (\hat{a}_0, \dots, \hat{a}_p)` is the estimate of  :math:`\vect{a}`.

    If a functional basis is specified, let :math:`p'` be its dimension and 
    :math:`\phi_j : \Rset^{p} \rightarrow \Rset` for :math:`j \in \{1, ..., p'\}`  be the :math:`j`-th basis function. The linear model is:

    .. math::
        :label: modelWithBase

        Y = \sum_{j=1}^{p'} a_j \phi_j(\vect{X}) + \epsilon

    where :math:`\vect{a} = (a_1, \dots, a_{p'})` and :math:`\epsilon` have the same properties as in the previous
    case.


    The fitted values :math:`\hat{Y}_i`  for :math:`1 \leq i \leq \sampleSize` are defined by:

    .. math::
        :label: fittedValue2

        \hat{Y}_i = \sum_{j=1}^{p'} \hat{a}_j \phi_j(\vect{X}^i)

    where :math:`\hat{\vect{a}} = (\hat{a}_1, \dots, \hat{a}_{p'})` is the estimate of the :math:`\vect{a}`.

    We define the residual of the :math:`i`-th experience by: 

    .. math::
        :label: residualDef

        \varepsilon_i & = Y_i -  \hat{Y}_i


    The algorithm still estimates the coefficients
    :math:`\vect{a}` as well as the variance :math:`\sigma^2`.
    The coefficients are evaluated using a linear least squares method,
    by default the `QR` method.
    User might also choose `SVD` or `Cholesky` by
    setting the `LinearModelAlgorithm-DecompositionMethod` key of the :class:`~openturns.ResourceMap`.
    Here are a few guidelines to choose the appropriate decomposition method:

    - The Cholesky can be safely used if the functional basis is orthogonal
      and the sample is drawn from the corresponding distribution,
      because this ensures that the columns of the design matrix are
      asymptotically orthogonal when the sample size increases.
      In this case, evaluating the Gram matrix does not increase
      the condition number.
    - Selecting the decomposition method can also be based on the sample size.

    Please read the :meth:`~openturns.LeastSquaresMethod.Build` help page
    for details on this topic.

    The :class:`~openturns.LinearModelAnalysis` class can be used for a detailed
    analysis of the linear model result.

    No scaling is involved in this method.
    The scaling of the data, if any, is the responsibility of the user of the algorithm.
    This may be useful if, for example, we use a linear model (without functional basis)
    with very different input magnitudes and use the Cholesky decomposition
    applied to the associated Gram matrix.
    In this case, the Cholesky method may fail to produce accurate results.

    Examples
    --------
    >>> import openturns as ot
    >>> func = ot.SymbolicFunction(
    ...     ['x1', 'x2', 'x3'],
    ...     ['x1 + x2 + sin(x2 * 2 * pi_)/5 + 1e-3 * x3^2']
    ... )
    >>> dimension = 3
    >>> distribution = ot.JointDistribution([ot.Normal()] * dimension)
    >>> inputSample = distribution.getSample(20)
    >>> outputSample = func(inputSample)
    >>> algo = ot.LinearModelAlgorithm(inputSample, outputSample)
    >>> algo.run()
    >>> result = algo.getResult()
    >>> design = result.getDesign()
    >>> gram = design.computeGram()
    >>> leverages = result.getLeverages()

    In order to access the projection matrix, we build the least squares method.

    >>> lsMethod = result.buildMethod()
    >>> projectionMatrix = lsMethod.getH()

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.LinearModelAlgorithm_getClassName(self)

    def __repr__(self):
        return _metamodel.LinearModelAlgorithm___repr__(self)

    def getBasis(self):
        r"""
        Accessor to the input basis.

        Returns
        -------
        basis : :class:`~openturns.Basis`
            The basis of the regression model.

        Notes
        -----
        If a functional basis has been provided in the constructor, then we get it back:
        :math:`(\phi_k)_{1 \leq k \leq p'}`.
        Otherwise, the functional basis is composed of the projections :math:`\phi_k : \Rset^p \rightarrow \Rset`
        such that :math:`\phi_k(\vect{x}) = x_k` for :math:`1 \leq k \leq p`, completed with the constant function:
        :math:`\phi_0 : \vect{x} \rightarrow 1`.
        """
        return _metamodel.LinearModelAlgorithm_getBasis(self)

    def run(self):
        r"""
        Compute the response surfaces.

        Notes
        -----
        It computes the response surfaces and creates a
        :class:`~openturns.MetaModelResult` structure containing all the results.
        """
        return _metamodel.LinearModelAlgorithm_run(self)

    def getResult(self):
        r"""
        Accessor to the result of the algorithm.

        Returns
        -------
        result : :class:`~openturns.LinearModelResult`
            All the results of the algorithm.
        """
        return _metamodel.LinearModelAlgorithm_getResult(self)

    def __init__(self, *args):
        _metamodel.LinearModelAlgorithm_swiginit(self, _metamodel.new_LinearModelAlgorithm(*args))
    __swig_destroy__ = _metamodel.delete_LinearModelAlgorithm

# Register LinearModelAlgorithm in _metamodel:
_metamodel.LinearModelAlgorithm_swigregister(LinearModelAlgorithm)
class LinearModelAnalysis(openturns.common.PersistentObject):
    r"""
    Analyse a linear model.

    Parameters
    ----------
    linearModelResult : :class:`~openturns.LinearModelResult`
        A linear model result.

    See Also
    --------
    LinearModelResult

    Notes
    -----
    This class relies on a linear model result structure and analyses the results.

    By default, on graphs, labels of the 3 most significant points are displayed.
    This number can be changed by modifying the :class:`~openturns.ResourceMap` key
    (``LinearModelAnalysis-IdentifiersNumber``).

    The class has a pretty-print method which is triggered by
    the `print()` function.
    This prints the following results, where we focus on the properties
    of a satisfactory regression model.

    - Each row of the table of coefficients tests if one single coefficient is zero.
      For a single coefficient, if the p-value of the T-test is close to zero,
      we can reject the hypothesis that this coefficient is zero. See :meth:`getCoefficientsTScores`
      to get the scores
      and :meth:`getCoefficientsPValues` to get  the related p-values.
    - The :math:`R^2` score measures how the predicted output values are close to the
      observed values.
      If the :math:`R^2` is close to 1 (e.g. larger than 0.95), then the predictions are
      accurate on average. See :meth:`~openturns.LinearModelResult.getRSquared`.
      Furthermore, the adjusted :math:`R^2` value, denoted by :math:`R_{ad}^2`, takes into account the data set
      size and the number of hyperparameters. See :meth:`~openturns.LinearModelResult.getAdjustedRSquared`.
    - The Fisher-test tests if all the coefficients are simultaneously zero.
      If the p-value is close to zero, then we can reject this hypothesis:
      there is at least one nonzero coefficient. See :meth:`getFisherScore` to get the scores
      and :meth:`getFisherPValue` to get related the p-values.
    - The normality tests check if the residuals are Gaussian.
      The normality assumption can be accepted (or, more precisely, cannot be
      rejected) if the p-value is larger than a threshold (e.g. 0.05). See 
      :meth:`getNormalityTestCramerVonMises`, :meth:`getNormalityTestResultAndersonDarling`,
      :meth:`getNormalityTestResultChiSquared()` and :meth:`getNormalityTestResultKolmogorovSmirnov`.

    The basics on regression theory are presented in :any:`regression_analysis`.
    The goodness of fit tests for normality are presented in :any:`graphical_fitting_test`,
    :any:`chi2_fitting_test`, :any:`kolmogorov_smirnov_test`, :any:`cramer_vonmises_test` and
    :any:`anderson_darling_test`.

    Examples
    --------
    >>> import openturns as ot
    >>> ot.RandomGenerator.SetSeed(0)
    >>> distribution = ot.Normal()
    >>> Xsample = distribution.getSample(30)
    >>> func = ot.SymbolicFunction(['x'], ['2 * x + 1'])
    >>> Ysample = func(Xsample) + ot.Normal().getSample(30)
    >>> algo = ot.LinearModelAlgorithm(Ysample, Xsample)
    >>> result = algo.getResult()
    >>> analysis = ot.LinearModelAnalysis(result)
    >>> # print(analysis)  # Pretty-print
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.LinearModelAnalysis_getClassName(self)

    def __repr__(self):
        return _metamodel.LinearModelAnalysis___repr__(self)

    def __str__(self, *args):
        return _metamodel.LinearModelAnalysis___str__(self, *args)

    def getLinearModelResult(self):
        r"""
        Accessor to the linear model result.

        Returns
        -------
        linearModelResult : :class:`~openturns.LinearModelResult`
            The  linear model result which has been passed to the constructor.
        """
        return _metamodel.LinearModelAnalysis_getLinearModelResult(self)

    def getCoefficientsTScores(self):
        r"""
        Accessor to the coefficients of linear expansion over their standard error.

        Returns
        -------
        tScores : :class:`~openturns.Point`
           The Student score of each coefficient estimate :math:`\hat{\vect{a}}`.

        Notes
        -----
        The T-test checks if the coefficient :math:`\hat{a}_k` is statistically different from zero and is used under the Gaussian assumption of the error :math:`\varepsilon`. See [rawlings2001]_ (section 4.5.2 *Special cases of the general form* page 122) for more details.

        For each coefficient estimate :math:`\hat{\vect{a}}`, the Student score :math:`t_k` is computed as: 

        .. math::
           :label: tScores

           t_k = \dfrac{\hat{a}_k}{\sigma(a_k)}

        where :math:`\sigma(a_k)` is the standard deviation of the distribution of the estimator :math:`\hat{a}_k`
        defined in :eq:`std_dev_estim`.

        """
        return _metamodel.LinearModelAnalysis_getCoefficientsTScores(self)

    def getCoefficientsPValues(self):
        r"""
        Accessor to the coefficients of the p values.

        Returns
        -------
        pValues : :class:`~openturns.Point`
            Student P-values of the coefficient estimates.

        Notes
        -----
        The T-test checks if the coefficient :math:`\hat{a}_k` is statistically different from zero  and is used under the Gaussian assumption of the error :math:`\varepsilon`.

        The p-values of each coefficient estimate is computed from the t-scores defined in :eq:`tScores` with
        respect to the :class:`~openturns.Student` distribution
        with :math:`dof` degrees of freedom defined in :eq:`dofWithBase` or :eq:`dofNoBase`.

        These p-values are used under the Gaussian assumption of the error :math:`\varepsilon`. If the p-value is close to zero, we can
        reject the hypothesis that this coefficient is zero. If the p-value is close to 1, we can
        accept the hypothesis that this coefficient is zero.

        If the residuals are not Gaussian, this test is not appropriate and should not be used.

        """
        return _metamodel.LinearModelAnalysis_getCoefficientsPValues(self)

    def getCoefficientsConfidenceInterval(self, level=0.95):
        r"""
        Accessor to the confidence interval of level :math:`\alpha` for the coefficients
        of the linear expansion.

        Parameters
        ----------
        alpĥa : float, :math:`0 \leq \alpha \leq 1`
            The confidence level :math:`\alpha`.

        Returns
        -------
        confidenceInterval : :class:`~openturns.Interval`
            The confidence interval.

        Notes
        -----
        Under the Gaussian assumption of the error, the confidence interval of the coefficient :math:`a_k` of level :math:`\alpha` is defined by:

        .. math::
           \left[\hat{a}_k \pm \sqrt{\left((\mat{\Psi}^t\mat{\Psi})^{-1} \right)_{k+1, k+1}}\hat{\sigma} t_{(1+\alpha)/2}\right]

        where:

        - :math:`t_{(1+\alpha)/2}` is the quantile of order :math:`(1+\alpha)/2` of the Student(:math:`dof`) distribution,
        - with :math:`dof` the degrees of freedom defined in :eq:`dofNoBase` or :eq:`dofWithBase`,
        - :math:`\mat{\Psi}` the design matrix defined in :eq:`designMatDef` or :eq:`designMatDef2`.

        The interval returned is multivariate and contains the intervals of all the coefficients.

        If the residuals are not Gaussian, this test is not appropriate and should not be used.

        """
        return _metamodel.LinearModelAnalysis_getCoefficientsConfidenceInterval(self, level)

    def getFisherScore(self):
        r"""
        Accessor to the Fisher statistics.

        Returns
        -------
        fisherScore : float
            The Fisher score of the model.

        Notes
        -----
        The Fisher-test tests if all the coefficients are simultaneously equal to zero  and is used under the Gaussian assumption of the error :math:`\varepsilon`.

        The Fisher score is computed as follows. Let be :math:`dofM` the degrees of freedom of the model, equal to the number of coefficients to estimate (:math:`p+1` of :math:`p'`). If the basis contains an intercept, then we subtract 1 from :math:`dofM`.

        Let :math:`dof` be the degrees of freedom defined in :eq:`dofNoBase` or :eq:`dofWithBase`.

        Let *SSR* be the Sum of Squared Residuals (sometimes called *SSE* as Sum of Squared Errors) defined by: 

        .. math::
           SSR = \sum_{i=1}^\sampleSize \varepsilon_i^2

        Let *SST* be the Sum of Squared Total defined by: 

        .. math::
           SST = \left| \begin{array}{ll}
               \sum_{i=1}^\sampleSize (Y_i - \bar{Y}_i)^2 & \mbox{if the basis contains an intercept} \\ 
               \sum_{i=1}^\sampleSize Y_i^2               & \mbox{if not.}
                        \end{array}
                 \right.

        where :math:`\bar{Y}_i = \dfrac{1}{\sampleSize} Y_i`.

        We denote by *SSM* the Sum of Squared Model defined by:

        .. math::
           SSM = SST - SSR

        Then, the Fisher score :math:`f` is defined by:

        .. math::
           :label: FisherScore

           f = \dfrac{SSM/dofM}{SSE/dof}

        """
        return _metamodel.LinearModelAnalysis_getFisherScore(self)

    def getFisherPValue(self):
        r"""
        Accessor to the Fisher p-values.

        Returns
        -------
        fisherPValue : float
            Fisher P-value of the model estimate.

        Notes
        -----
        The F-test tests if all the coefficients are simultaneously equal to zero  and is used under the Gaussian assumption of the error :math:`\varepsilon`.

        The Fisher p-value of each coefficient estimate is computed from the Fisher score defined in :eq:`FisherScore` with
        respect to the :class:`~openturns.FisherSnedecor` distribution parameterized by :math:`(dofM, dof)` where:

        - :math:`dofM` is the degrees of freedom of the model (equal to the number of coefficients to estimate (:math:`p+1` of :math:`p'`). If the basis contains an intercept, then we subtract 1 from :math:`dofM`.
        - :math:`dof` is the degrees of freedom defined in :eq:`dofNoBase` or :eq:`dofWithBase`.

        This p-value is used under the Gaussian assumption of the error :math:`\varepsilon`. It tests
        if all the coefficients are statistically useful to the model. If the p-value is close to zero, then we can reject this hypothesis: *there is at least one nonzero coefficient*.

        If the residuals are not Gaussian, this test is not appropriate and should not be used.
        """
        return _metamodel.LinearModelAnalysis_getFisherPValue(self)

    def getResidualsStandardError(self):
        r"""
        Accessor to the standard error of the residuals.

        Returns
        -------
        stdError : float
            The residuals standard deviation estimate.

        Notes
        -----
        The standard error is also called the *root mean squared error* or the *standard error of regression*. It is
        the residual standard deviation :math:`\hat{\sigma}` defined in :eq:`estimSigma2Noise` which is the unbiaised
        residuals variance.

        """
        return _metamodel.LinearModelAnalysis_getResidualsStandardError(self)

    def getNormalityTestResultKolmogorovSmirnov(self):
        r"""
        Performs Kolmogorov test.

        Returns
        -------
        testResult : :class:`~openturns.TestResult`
            Test result class.

        Notes
        -----
        We check if the residuals are Gaussian  thanks to :meth:`~openturns.FittingTest.Kolmogorov`.
        """
        return _metamodel.LinearModelAnalysis_getNormalityTestResultKolmogorovSmirnov(self)

    def getNormalityTestResultAndersonDarling(self):
        r"""
        Performs Anderson-Darling test.

        Returns
        -------
        testResult : :class:`~openturns.TestResult`
            Test result class.


        Notes
        -----
        We check if the residuals are Gaussian  thanks to :meth:`~openturns.NormalityTest.AndersonDarlingNormal`.
        """
        return _metamodel.LinearModelAnalysis_getNormalityTestResultAndersonDarling(self)

    def getNormalityTestResultChiSquared(self):
        r"""
        Performs Chi-Square test.

        Returns
        -------
        testResult : :class:`~openturns.TestResult`
            Test result class.

        Notes
        -----
        The Chi-Square test is a goodness of fit test which objective is to check the
        normality assumption (null hypothesis) of residuals (and thus the model).

        Usually, Chi-Square test applies for discrete distributions. Here we rely on
        the :meth:`~openturns.FittingTest.ChiSquared` to check the normality.

        """
        return _metamodel.LinearModelAnalysis_getNormalityTestResultChiSquared(self)

    def getNormalityTestCramerVonMises(self):
        r"""
        Performs Cramer-Von Mises test.

        Returns
        -------
        testResult : :class:`~openturns.TestResult`
            Test result class.


        Notes
        -----
        We check if the residuals are Gaussian thanks to :meth:`~openturns.NormalityTest.CramerVonMisesNormal`.
        """
        return _metamodel.LinearModelAnalysis_getNormalityTestCramerVonMises(self)

    def drawModelVsFitted(self):
        r"""
        Accessor to plot of model versus fitted values.

        Returns
        -------
        graph : :class:`~openturns.Graph`

        Notes
        -----
        The graph plots the sample :math:`(Y_i, \hat{Y}_i)` where :math:`Y_i` is the real value of experience :math:`i`
        and :math:`\hat{Y}_i` is the value fitted by the linear model, defined in :eq:`fittedValue` or :eq:`fittedValue2`.

        """
        return _metamodel.LinearModelAnalysis_drawModelVsFitted(self)

    def drawResidualsVsFitted(self):
        r"""
        Accessor to plot of residuals versus fitted values.

        Returns
        -------
        graph : :class:`~openturns.Graph`

        Notes
        -----
        The graph plots the sample :math:`(\varepsilon_i, \hat{Y}_i)` where :math:`\varepsilon_i` is the residual of experience :math:`i` defined in :eq:`residualDef`
        and :math:`\hat{Y}_i` is the value fitted by the linear model, defined in :eq:`fittedValue` or :eq:`fittedValue2`.

        """
        return _metamodel.LinearModelAnalysis_drawResidualsVsFitted(self)

    def drawScaleLocation(self):
        r"""
        Accessor to a Scale-Location plot of sqrt(abs(standardized residuals)) versus fitted values.

        Returns
        -------
        graph : :class:`~openturns.Graph`

        Notes
        -----
        The graph plots the sample :math:`(\hat{Y}_i, \sqrt{|\varepsilon_i^{st}|})` where :math:`\varepsilon_i^{st}` is the standardized residual of experience :math:`i` defined in :eq:`stdRes`
        and :math:`\hat{Y}_i` is the value fitted by the linear model, defined in :eq:`fittedValue` or :eq:`fittedValue2`.

        """
        return _metamodel.LinearModelAnalysis_drawScaleLocation(self)

    def drawQQplot(self):
        r"""
        Accessor to plot a Normal quantiles-quantiles plot of standardized residuals.

        Returns
        -------
        graph : :class:`~openturns.Graph`

        Notes
        -----
        The graph plots the empirical quantiles of the standardized residuals defined in :eq:`stdRes` versus
        the quantiles of the Normal distribution with zero mean and unit variance.

        """
        return _metamodel.LinearModelAnalysis_drawQQplot(self)

    def drawCookDistance(self):
        r"""
        Accessor to plot of Cook's distances versus row labels.

        Returns
        -------
        graph : :class:`~openturns.Graph`

        Notes
        -----
        The graph plots the Cook distance of each experience :math:`i` is defined in :eq:`cookDef`.
        The Cook's distance measures the impact of every individual data point on the linear regression. See [rawlings2001]_ (section 11.2.1, *Cook's D* page 362) for more details.
        """
        return _metamodel.LinearModelAnalysis_drawCookDistance(self)

    def drawResidualsVsLeverages(self):
        r"""
        Accessor to plot of residuals versus leverages that adds bands corresponding to Cook's distances of 0.5 and 1.

        Returns
        -------
        graph : :class:`~openturns.Graph`

        Notes
        -----
        This graph plots the residuals :math:`\varepsilon_i` defined in :eq:`residualDef` and the leverage :math:`\ell_i`  of experience :math:`i` defined in :eq:`leverageDef`.
        """
        return _metamodel.LinearModelAnalysis_drawResidualsVsLeverages(self)

    def drawCookVsLeverages(self):
        r"""
        Accessor to plot of Cook's distances versus leverage/(1-leverage). 

        Returns
        -------
        graph : :class:`~openturns.Graph`

        Notes
        -----
        This graph plots the Cook distance defined in :eq:`cookDef` and the the ration :math:`\ell_i/(1-\ell_i)` where :math:`\ell_i` is the leverage of experience :math:`i` defined in :eq:`leverageDef`.
        """
        return _metamodel.LinearModelAnalysis_drawCookVsLeverages(self)

    def __init__(self, *args):
        _metamodel.LinearModelAnalysis_swiginit(self, _metamodel.new_LinearModelAnalysis(*args))
    __swig_destroy__ = _metamodel.delete_LinearModelAnalysis

# Register LinearModelAnalysis in _metamodel:
_metamodel.LinearModelAnalysis_swigregister(LinearModelAnalysis)

import math

def __LinearModelAnalysis_repr_html(self):
    """Get HTML representation."""
    def format_pvalue(pValue):
        fmtLargePValue = openturns.common.ResourceMap.GetAsString("LinearModelAnalysis-LargePValueFormat")
        fmtSmallPValue = openturns.common.ResourceMap.GetAsString("LinearModelAnalysis-SmallPValueFormat")
        if pValue == 0.0:
            pValueStr = "0.0"
        elif pValue > 1.e-3:
            pValueStr = fmtLargePValue.format(pValue)
        else:
            pValueStr = fmtSmallPValue.format(pValue)
        return pValueStr

    html = ""
    lmResult = self.getLinearModelResult()
    coefficients = lmResult.getCoefficients()
    basisSize = coefficients.getSize()
    hasIntercept = lmResult.hasIntercept()
    standardErrors = lmResult.getCoefficientsStandardErrors()
    tscores = self.getCoefficientsTScores()
    pValues = self.getCoefficientsPValues()
    names = lmResult.getCoefficientsNames()
    dof = lmResult.getDegreesOfFreedom()
    n = lmResult.getSampleResiduals().getSize()
    maximumNameLength = openturns.common.ResourceMap.GetAsUnsignedInteger("LinearModelAnalysis-PrintEllipsisThreshold")

# Print the basis
    html += "<strong>Basis</strong>\n"
    html += "<br>\n"
    html += f"{lmResult.getFormula()}"
    html += "<br>\n"

# Table of coefficients
    html += "<strong>Coefficients</strong>\n"
    html += "<br>\n"
# Header
    html += "<table>\n"
    html += "  <tr>\n"
    html += f"    <th>Index</th>\n"
    html += f"    <th>Function</th>\n"
    html += f"    <th>Estimate</th>\n"
    html += f"    <th>Std Error</th>\n"
    html += f"    <th>t value</th>\n"
    html += f"    <th>Pr(>|t|)</th>\n"
    html += "  </tr>\n"
# Content
    for i in range(pValues.getSize()):
        if len(names[i]) > maximumNameLength:
            fullName = names[i]
            printedName = fullName[0:maximumNameLength] + "..."
        else:
            printedName = names[i]
        html += "  <tr>\n"
        html += f"    <td>{i}</td>\n"
        html += f"    <td>{printedName}</td>\n"
        html += f"    <td>{coefficients[i]:.4e}</td>\n"
        html += f"    <td>{standardErrors[i]:.4e}</td>\n"
        html += f"    <td>{tscores[i]:.4e}</td>\n"
        html += f"    <td>{format_pvalue(pValues[i])}</td>\n"
        html += "  </tr>\n"

    html += "</table>\n"
    html += "<br>\n"

# Print statistics
    html += "<ul>\n"
    stdError = self.getResidualsStandardError()
    html += f"  <li>Residual standard error: {stdError:.4e} " \
            f"on {dof} degrees of freedom </li>\n"

# In case of only intercept in the basis, no more print
    if (basisSize == 1 and hasIntercept):
        html += "</ul>\n"
        return html

    fisherScore = self.getFisherScore()
    fisherPValue = self.getFisherPValue()
    html += f"  <li>F-statistic: {fisherScore:.4e}, "  \
            f"p-value: {format_pvalue(fisherPValue)}\n";

#  R-squared & Adjusted R-squared tests
    test1 = lmResult.getRSquared();
    html += f"  <li>Multiple R-squared: {test1:.4f}</li>\n"
    test2 = lmResult.getAdjustedRSquared();
    html += f"  <li>Adjusted R-squared:  {test2:.4f}</li>\n"
    html += "</ul>\n"

# Normality test of the residuals
    html += "<strong>Normality test of the residuals</strong>\n"
    html += "<br>\n"
    normalitytest1 = self.getNormalityTestResultAndersonDarling().getPValue()
    normalitytest2 = self.getNormalityTestResultChiSquared().getPValue()
    normalitytest3 = self.getNormalityTestResultKolmogorovSmirnov().getPValue()
    normalitytest4 = self.getNormalityTestCramerVonMises().getPValue()
    html += "<table>\n"
    html += "  <tr>\n"
    html += f"    <th>Normality test</th>\n"
    html += f"    <th>p-value</th>\n"
    html += "  </tr>\n"
    html += "  <tr>\n"
    html += f"    <td>Anderson-Darling</td>\n"
    html += f"    <td>{format_pvalue(normalitytest1)}</td>\n"
    html += "  </tr>\n"
    html += "  <tr>\n"
    html += f"    <td>ChiSquared</td>\n"
    html += f"    <td>{format_pvalue(normalitytest2)}</td>\n"
    html += "  </tr>\n"
    html += "  <tr>\n"
    html += f"    <td>Kolmogorov-Smirnov</td>\n"
    html += f"    <td>{format_pvalue(normalitytest3)}</td>\n"
    html += "  </tr>\n"
    html += "  <tr>\n"
    html += f"    <td>Cramer-Von Mises</td>\n"
    html += f"    <td>{format_pvalue(normalitytest4)}</td>\n"
    html += "  </tr>\n"
    html += "</table>\n"
    return html

LinearModelAnalysis._repr_html_ = __LinearModelAnalysis_repr_html


class PythonRandomVector:
    """
    Allow one to overload RandomVector from Python.

    Parameters
    ----------
    dim : positive int
        Vector dimension.
        Default is 0.

    See also
    --------
    RandomVector

    Examples
    --------
    >>> import openturns as ot
    >>> ot.RandomGenerator.SetSeed(0)

    Overload RandomVector from Python:

    >>> class RVEC(ot.PythonRandomVector):
    ...    def __init__(self):
    ...        super(RVEC, self).__init__(2)
    ...        self.setDescription(['R', 'S'])
    ...
    ...    def getRealization(self):
    ...        X = [ot.RandomGenerator.Generate(), 2 + ot.RandomGenerator.Generate()]
    ...        return X
    ...
    ...    def getSample(self, size):
    ...        X = []
    ...        for i in range(size):
    ...            X.append([ot.RandomGenerator.Generate(), 2 + ot.RandomGenerator.Generate()])
    ...        return X
    ...
    ...    def getMean(self):
    ...        return [0.5, 2.5]
    ...
    ...    def getCovariance(self):
    ...        return [[0.0833333, 0.], [0., 0.0833333]]

    Use the overloaded class:

    >>> R = RVEC()
    >>> # Instance creation
    >>> myRV = ot.RandomVector(R)
    >>> # Realization
    >>> print(myRV.getRealization())
    [0.629877,2.88281]
    >>> # Sample
    >>> print(myRV.getSample(5))
    0 : [ 0.135276  2.0325    ]
    1 : [ 0.347057  2.96942   ]
    2 : [ 0.92068   2.50304   ]
    3 : [ 0.0632061 2.29276   ]
    4 : [ 0.714382  2.38336   ]
    >>> # Mean
    >>> print(myRV.getMean())
    [0.5,2.5]
    >>> # Covariance
    >>> print(myRV.getCovariance())
    [[ 0.0833333 0         ]
     [ 0         0.0833333 ]]

    Random vectors can admit parameters.

    In the following example, we define a `RandomVector`
    to sample from a normal multivariate normal distribution
    truncated to a ball.
    We implement the `setParameter` method to define the ball's center.

    >>> class NormalTruncatedToBall(ot.PythonRandomVector):
    ...    def __init__(self, dim, max_dist):
    ...        super().__init__(dim)
    ...        self._center = ot.Point(dim)
    ...        self._normal = ot.Normal(dim)
    ...        self._max_dist = max_dist
    ...        self.setParameter(ot.Point(dim))
    ...
    ...    def getRealization(self):
    ...        dist = ot.SpecFunc.Infinity
    ...        while dist>self._max_dist:
    ...            candidate = self._normal.getRealization()
    ...            dist = (candidate - self._center).norm()
    ...        return candidate
    ...
    ...    def setParameter(self, center): # the parameter influences sampling
    ...        self._center = center
    ...
    ...    def getParameter(self): # implemented for the sake of consistency
    ...        return self._center
    ...
    ...    def getParameterDescription(self): # optional
    ...        return ["center_{}".format(i) for i in range(self.getDimension())]

    Define an instance of this `RandomVector` and set the parameter:

    >>> myRV = ot.RandomVector(NormalTruncatedToBall(2, 1.5))
    >>> myRV.setParameter([1.3, 0.6])

    Get a sample and plot it:

    >>> sample = myRV.getSample(100)
    >>> graph = ot.Graph("Sample from a PythonRandomVector", "", "", True, '')
    >>> cloud = ot.Cloud(sample)
    >>> graph.add(cloud)
    >>> from openturns.viewer import View
    >>> view = View(graph)

    """
    def __init__(self, dim=0):
# Warning: these names are used in PythonRandomVector class. Synchronize the files if changed
        self.__dim = dim
        self.__desc = ['x' + str(i) for i in range(dim)]

    def __str__(self):
        return f"PythonRandomVector -> {self.__desc} #{self.__dim}"

    def __repr__(self):
        return self.__str__()

    def getDimension(self):
        """
        Get the dimension.

        Returns
        -------
        dim : positive int
            Dimension of the RandomVector.
        """
        return self.__dim

    def setDescription(self, desc):
        """
        Set the description.

        Parameters
        ----------
        desc : sequence of str
            *desc* describes the components of the RandomVector.
            Its size must be equal to the dimension of the RandomVector.
        """
        if (len(desc) != self.__dim):
            raise ValueError('Description size does NOT match dimension')
        self.__desc = desc

    def getDescription(self):
        """
        Get the description.

        Returns
        -------
        desc : :class:`~openturns.Description`
            *desc* describes the components of the RandomVector.
        """
        return self.__desc


class _RandomVectorImplementationTypedInterfaceObject(openturns.common.InterfaceObject):
    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __repr__ = _swig_repr

    def __init__(self, *args):
        _metamodel._RandomVectorImplementationTypedInterfaceObject_swiginit(self, _metamodel.new__RandomVectorImplementationTypedInterfaceObject(*args))

    def getImplementation(self):
        r"""
        Accessor to the underlying implementation.

        Returns
        -------
        impl : Implementation
            A copy of the underlying implementation object.
        """
        return _metamodel._RandomVectorImplementationTypedInterfaceObject_getImplementation(self)

    def setName(self, name):
        r"""
        Accessor to the object's name.

        Parameters
        ----------
        name : str
            The name of the object.
        """
        return _metamodel._RandomVectorImplementationTypedInterfaceObject_setName(self, name)

    def getName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        name : str
            The name of the object.
        """
        return _metamodel._RandomVectorImplementationTypedInterfaceObject_getName(self)

    def __eq__(self, other):
        return _metamodel._RandomVectorImplementationTypedInterfaceObject___eq__(self, other)

    def __ne__(self, other):
        return _metamodel._RandomVectorImplementationTypedInterfaceObject___ne__(self, other)
    __swig_destroy__ = _metamodel.delete__RandomVectorImplementationTypedInterfaceObject

# Register _RandomVectorImplementationTypedInterfaceObject in _metamodel:
_metamodel._RandomVectorImplementationTypedInterfaceObject_swigregister(_RandomVectorImplementationTypedInterfaceObject)
class RandomVector(_RandomVectorImplementationTypedInterfaceObject):
    r"""
    Random vectors.

    Parameters
    ----------
    distribution : :class:`~openturns.Distribution`
        Distribution of the :class:`~openturns.UsualRandomVector` to define.

    Notes
    -----
    A :class:`~openturns.RandomVector` provides at least a way to generate realizations.

    See also
    --------
    UsualRandomVector, CompositeRandomVector, CompoundRandomVector,
    ConstantRandomVector, FunctionalChaosRandomVector, ThresholdEvent,
    PythonRandomVector
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.RandomVector_getClassName(self)

    def __repr__(self):
        return _metamodel.RandomVector___repr__(self)

    def __str__(self, *args):
        return _metamodel.RandomVector___str__(self, *args)

    def setDescription(self, description):
        r"""
        Accessor to the description of the RandomVector.

        Parameters
        ----------
        description : str or sequence of str
            Describes the components of the RandomVector.
        """
        return _metamodel.RandomVector_setDescription(self, description)

    def getDescription(self):
        r"""
        Accessor to the description of the RandomVector.

        Returns
        -------
        description : :class:`~openturns.Description`
            Describes the components of the RandomVector.
        """
        return _metamodel.RandomVector_getDescription(self)

    def isComposite(self):
        r"""
        Accessor to know if the RandomVector is a composite one.

        Returns
        -------
        isComposite : bool
            Indicates if the RandomVector is of type Composite or not.
        """
        return _metamodel.RandomVector_isComposite(self)

    def getDimension(self):
        r"""
        Accessor to the dimension of the RandomVector.

        Returns
        -------
        dimension : positive int
            Dimension of the RandomVector.
        """
        return _metamodel.RandomVector_getDimension(self)

    def getRealization(self):
        r"""
        Compute one realization of the RandomVector.

        Returns
        -------
        realization : :class:`~openturns.Point`
            Sequence of values randomly determined from the RandomVector definition.
            In the case of an event: one realization of the event (considered as a
            Bernoulli variable) which is a boolean value (1 for the realization of the
            event and 0 else).

        See also
        --------
        openturns.RandomVector.getSample

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal([0.0, 0.0], [1.0, 1.0], ot.CorrelationMatrix(2))
        >>> randomVector = ot.RandomVector(distribution)
        >>> ot.RandomGenerator.SetSeed(0)
        >>> print(randomVector.getRealization())
        [0.608202,-1.26617]
        >>> print(randomVector.getRealization())
        [-0.438266,1.20548]
        """
        return _metamodel.RandomVector_getRealization(self)

    def getFrozenRealization(self, fixedPoint):
        r"""
        Compute realizations of the RandomVector.

        In the case of a :class:`~openturns.CompositeRandomVector`
        or an event of some kind, this method returns
        the value taken by the random vector if the root cause
        takes the value given as argument.

        Parameters
        ----------
        fixedPoint : :class:`~openturns.Point`
            Point chosen as the root cause of the random vector.

        Returns
        -------
        realization : :class:`~openturns.Point`
            The realization corresponding to the chosen root cause.

        See also
        --------
        openturns.RandomVector.getRealization
        openturns.RandomVector.getFrozenSample

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal()
        >>> randomVector = ot.RandomVector(distribution)
        >>> f = ot.SymbolicFunction('x', 'x')
        >>> compositeRandomVector = ot.CompositeRandomVector(f, randomVector)
        >>> event = ot.ThresholdEvent(compositeRandomVector, ot.Less(), 0.0)
        >>> print(event.getFrozenRealization([0.2]))
        [0]
        >>> print(event.getFrozenRealization([-0.1]))
        [1]
        """
        return _metamodel.RandomVector_getFrozenRealization(self, fixedPoint)

    def getSample(self, size):
        r"""
        Compute realizations of the RandomVector.

        Parameters
        ----------
        n : int, :math:`n \geq 0`
            Number of realizations needed.

        Returns
        -------
        realizations : :class:`~openturns.Sample`
            n sequences of values randomly determined from the RandomVector definition.
            In the case of an event: n realizations of the event (considered as a
            Bernoulli variable) which are boolean values (1 for the realization of the
            event and 0 else).

        See also
        --------
        openturns.RandomVector.getRealization

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal([0.0, 0.0], [1.0, 1.0], ot.CorrelationMatrix(2))
        >>> randomVector = ot.RandomVector(distribution)
        >>> ot.RandomGenerator.SetSeed(0)
        >>> print(randomVector.getSample(3))
            [ X0        X1        ]
        0 : [  0.608202 -1.26617  ]
        1 : [ -0.438266  1.20548  ]
        2 : [ -2.18139   0.350042 ]
        """
        return _metamodel.RandomVector_getSample(self, size)

    def getFrozenSample(self, fixedSample):
        r"""
        Compute realizations of the RandomVector.

        In the case of a :class:`~openturns.CompositeRandomVector`
        or an event of some kind, this method returns
        the different values taken by the random vector when the root cause
        takes the values given as argument.

        Parameters
        ----------
        fixedSample : :class:`~openturns.Sample`
            Sample of root causes of the random vector.

        Returns
        -------
        sample : :class:`~openturns.Sample`
            Sample of the realizations corresponding to the chosen root causes.

        See also
        --------
        openturns.RandomVector.getSample
        openturns.RandomVector.getFrozenRealization

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal()
        >>> randomVector = ot.RandomVector(distribution)
        >>> f = ot.SymbolicFunction('x', 'x')
        >>> compositeRandomVector = ot.CompositeRandomVector(f, randomVector)
        >>> event = ot.ThresholdEvent(compositeRandomVector, ot.Less(), 0.0)
        >>> print(event.getFrozenSample([[0.2], [-0.1]]))
            [ y0 ]
        0 : [ 0  ]
        1 : [ 1  ]
        """
        return _metamodel.RandomVector_getFrozenSample(self, fixedSample)

    def getMarginal(self, *args):
        r"""
        Get the random vector corresponding to the :math:`i^{th}` marginal component(s).

        Parameters
        ----------
        i : int or list of ints, :math:`0\leq i < dim`
            Indicates the component(s) concerned. :math:`dim` is the dimension of the
            RandomVector.

        Returns
        -------
        vector :  :class:`~openturns.RandomVector`
            RandomVector restricted to the concerned components.

        Notes
        -----
        Let's note :math:`\vect{Y}=\Tr{(Y_1,\dots,Y_n)}` a random vector and
        :math:`I \in [1,n]` a set of indices. If :math:`\vect{Y}` is a
        :class:`~openturns.UsualRandomVector`, the subvector is defined by
        :math:`\tilde{\vect{Y}}=\Tr{(Y_i)}_{i \in I}`. If :math:`\vect{Y}` is a
        :class:`~openturns.CompositeRandomVector`, defined by
        :math:`\vect{Y}=f(\vect{X})` with :math:`f=(f_1,\dots,f_n)`,
        :math:`f_i` some scalar functions, the subvector is
        :math:`\tilde{\vect{Y}}=(f_i(\vect{X}))_{i \in I}`.

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal([0.0, 0.0], [1.0, 1.0], ot.CorrelationMatrix(2))
        >>> randomVector = ot.RandomVector(distribution)
        >>> ot.RandomGenerator.SetSeed(0)
        >>> print(randomVector.getMarginal(1).getRealization())
        [0.608202]
        >>> print(randomVector.getMarginal(1).getDistribution())
        Normal(mu = 0, sigma = 1)

        """
        return _metamodel.RandomVector_getMarginal(self, *args)

    def getMean(self):
        r"""
        Accessor to the mean of the RandomVector.

        Returns
        -------
        mean : :class:`~openturns.Point`
            Mean of the considered :class:`~openturns.UsualRandomVector`.

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal([0.0, 0.5], [1.0, 1.5], ot.CorrelationMatrix(2))
        >>> randomVector = ot.RandomVector(distribution)
        >>> ot.RandomGenerator.SetSeed(0)
        >>> print(randomVector.getMean())
        [0,0.5]
        """
        return _metamodel.RandomVector_getMean(self)

    def getCovariance(self):
        r"""
        Accessor to the covariance of the RandomVector.

        Returns
        -------
        covariance : :class:`~openturns.CovarianceMatrix`
            Covariance of the considered :class:`~openturns.UsualRandomVector`.

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal([0.0, 0.5], [1.0, 1.5], ot.CorrelationMatrix(2))
        >>> randomVector = ot.RandomVector(distribution)
        >>> ot.RandomGenerator.SetSeed(0)
        >>> print(randomVector.getCovariance())
        [[ 1    0    ]
         [ 0    2.25 ]]
        """
        return _metamodel.RandomVector_getCovariance(self)

    def getAntecedent(self):
        r"""
        Accessor to the antecedent RandomVector in case of a composite RandomVector.

        Returns
        -------
        antecedent : :class:`~openturns.RandomVector`
            Antecedent RandomVector :math:`\vect{X}` in case of a
            :class:`~openturns.CompositeRandomVector` such as:
            :math:`\vect{Y}=f(\vect{X})`.
        """
        return _metamodel.RandomVector_getAntecedent(self)

    def getFunction(self):
        r"""
        Accessor to the Function in case of a composite RandomVector.

        Returns
        -------
        function : :class:`~openturns.Function`
            Function used to define a :class:`~openturns.CompositeRandomVector` as the
            image through this function of the antecedent :math:`\vect{X}`:
            :math:`\vect{Y}=f(\vect{X})`.
        """
        return _metamodel.RandomVector_getFunction(self)

    def getDistribution(self):
        r"""
        Accessor to the distribution of the RandomVector.

        Returns
        -------
        distribution : :class:`~openturns.Distribution`
            Distribution of the considered :class:`~openturns.UsualRandomVector`.

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal([0.0, 0.0], [1.0, 1.0], ot.CorrelationMatrix(2))
        >>> randomVector = ot.RandomVector(distribution)
        >>> ot.RandomGenerator.SetSeed(0)
        >>> print(randomVector.getDistribution())
        Normal(mu = [0,0], sigma = [1,1], R = [[ 1 0 ]
         [ 0 1 ]])
        """
        return _metamodel.RandomVector_getDistribution(self)

    def getOperator(self):
        r"""
        Accessor to the comparison operator of the Event.

        Returns
        -------
        operator : :class:`~openturns.ComparisonOperator`
            Comparison operator used to define the :class:`~openturns.RandomVector`.
        """
        return _metamodel.RandomVector_getOperator(self)

    def getThreshold(self):
        r"""
        Accessor to the threshold of the Event.

        Returns
        -------
        threshold : float
            Threshold of the :class:`~openturns.RandomVector`.
        """
        return _metamodel.RandomVector_getThreshold(self)

    def getDomain(self):
        r"""
        Accessor to the domain of the Event.

        Returns
        -------
        domain : :class:`~openturns.Domain`
            Describes the domain of an event.
        """
        return _metamodel.RandomVector_getDomain(self)

    def getParameter(self):
        r"""
        Accessor to the parameter of the distribution.

        Returns
        -------
        parameter : :class:`~openturns.Point`
            Parameter values.
        """
        return _metamodel.RandomVector_getParameter(self)

    def setParameter(self, parameters):
        r"""
        Accessor to the parameter of the distribution.

        Parameters
        ----------
        parameter : sequence of float
            Parameter values.
        """
        return _metamodel.RandomVector_setParameter(self, parameters)

    def getParameterDescription(self):
        r"""
        Accessor to the parameter description of the distribution.

        Returns
        -------
        description : :class:`~openturns.Description`
            Parameter names.
        """
        return _metamodel.RandomVector_getParameterDescription(self)

    def isEvent(self):
        r"""
        Whether the random vector is an event.

        Returns
        -------
        isEvent : bool
            Whether it takes it values in {0, 1}.
        """
        return _metamodel.RandomVector_isEvent(self)

    def intersect(self, other):
        r"""
        Intersection of two events.

        Parameters
        ----------
        event : :class:`~openturns.RandomVector`
            A composite event

        Returns
        -------
        event : :class:`~openturns.RandomVector`
            Intersection event
        """
        return _metamodel.RandomVector_intersect(self, other)

    def join(self, other):
        r"""
        Union of two events.

        Parameters
        ----------
        event : :class:`~openturns.RandomVector`
            A composite event

        Returns
        -------
        event : :class:`~openturns.RandomVector`
            Union event
        """
        return _metamodel.RandomVector_join(self, other)

    def __init__(self, *args):
        _metamodel.RandomVector_swiginit(self, _metamodel.new_RandomVector(*args))
    __swig_destroy__ = _metamodel.delete_RandomVector

# Register RandomVector in _metamodel:
_metamodel.RandomVector_swigregister(RandomVector)
class CompositeRandomVector(openturns.randomvector.RandomVectorImplementation):
    r"""
    Random Vector obtained by applying a function.

    Allows one to define the random variable :math:`Y=f(X)` from a function :math:`f`
    and another random variable :math:`X`.

    Parameters
    ----------
    f : :class:`~openturns.Function`
        Function to apply to the antecedent.
    X : :class:`~openturns.RandomVector`
        Random vector of the antecedent.

    Examples
    --------
    >>> import openturns as ot
    >>> X = ot.RandomVector(ot.Normal())
    >>> f = ot.SymbolicFunction(['x'], ['x^2*sin(x)'])
    >>> Y = ot.CompositeRandomVector(f, X)

    Draw a sample:

    >>> sample = Y.getSample(5)
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.CompositeRandomVector_getClassName(self)

    def __repr__(self):
        return _metamodel.CompositeRandomVector___repr__(self)

    def isComposite(self):
        r"""
        Accessor to know if the RandomVector is a composite one.

        Returns
        -------
        isComposite : bool
            Indicates if the RandomVector is of type Composite or not.
        """
        return _metamodel.CompositeRandomVector_isComposite(self)

    def getDimension(self):
        r"""
        Accessor to the dimension of the RandomVector.

        Returns
        -------
        dimension : positive int
            Dimension of the RandomVector.
        """
        return _metamodel.CompositeRandomVector_getDimension(self)

    def getRealization(self):
        r"""
        Compute one realization of the RandomVector.

        Returns
        -------
        realization : :class:`~openturns.Point`
            Sequence of values randomly determined from the RandomVector definition.
            In the case of an event: one realization of the event (considered as a
            Bernoulli variable) which is a boolean value (1 for the realization of the
            event and 0 else).

        See also
        --------
        openturns.RandomVector.getSample

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal([0.0, 0.0], [1.0, 1.0], ot.CorrelationMatrix(2))
        >>> randomVector = ot.RandomVector(distribution)
        >>> ot.RandomGenerator.SetSeed(0)
        >>> print(randomVector.getRealization())
        [0.608202,-1.26617]
        >>> print(randomVector.getRealization())
        [-0.438266,1.20548]
        """
        return _metamodel.CompositeRandomVector_getRealization(self)

    def getFrozenRealization(self, fixedPoint):
        r"""
        Compute realizations of the RandomVector.

        In the case of a :class:`~openturns.CompositeRandomVector`
        or an event of some kind, this method returns
        the value taken by the random vector if the root cause
        takes the value given as argument.

        Parameters
        ----------
        fixedPoint : :class:`~openturns.Point`
            Point chosen as the root cause of the random vector.

        Returns
        -------
        realization : :class:`~openturns.Point`
            The realization corresponding to the chosen root cause.

        See also
        --------
        openturns.RandomVector.getRealization
        openturns.RandomVector.getFrozenSample

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal()
        >>> randomVector = ot.RandomVector(distribution)
        >>> f = ot.SymbolicFunction('x', 'x')
        >>> compositeRandomVector = ot.CompositeRandomVector(f, randomVector)
        >>> event = ot.ThresholdEvent(compositeRandomVector, ot.Less(), 0.0)
        >>> print(event.getFrozenRealization([0.2]))
        [0]
        >>> print(event.getFrozenRealization([-0.1]))
        [1]
        """
        return _metamodel.CompositeRandomVector_getFrozenRealization(self, fixedPoint)

    def getSample(self, size):
        r"""
        Compute realizations of the RandomVector.

        Parameters
        ----------
        n : int, :math:`n \geq 0`
            Number of realizations needed.

        Returns
        -------
        realizations : :class:`~openturns.Sample`
            n sequences of values randomly determined from the RandomVector definition.
            In the case of an event: n realizations of the event (considered as a
            Bernoulli variable) which are boolean values (1 for the realization of the
            event and 0 else).

        See also
        --------
        openturns.RandomVector.getRealization

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal([0.0, 0.0], [1.0, 1.0], ot.CorrelationMatrix(2))
        >>> randomVector = ot.RandomVector(distribution)
        >>> ot.RandomGenerator.SetSeed(0)
        >>> print(randomVector.getSample(3))
            [ X0        X1        ]
        0 : [  0.608202 -1.26617  ]
        1 : [ -0.438266  1.20548  ]
        2 : [ -2.18139   0.350042 ]
        """
        return _metamodel.CompositeRandomVector_getSample(self, size)

    def getFrozenSample(self, fixedSample):
        r"""
        Compute realizations of the RandomVector.

        In the case of a :class:`~openturns.CompositeRandomVector`
        or an event of some kind, this method returns
        the different values taken by the random vector when the root cause
        takes the values given as argument.

        Parameters
        ----------
        fixedSample : :class:`~openturns.Sample`
            Sample of root causes of the random vector.

        Returns
        -------
        sample : :class:`~openturns.Sample`
            Sample of the realizations corresponding to the chosen root causes.

        See also
        --------
        openturns.RandomVector.getSample
        openturns.RandomVector.getFrozenRealization

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal()
        >>> randomVector = ot.RandomVector(distribution)
        >>> f = ot.SymbolicFunction('x', 'x')
        >>> compositeRandomVector = ot.CompositeRandomVector(f, randomVector)
        >>> event = ot.ThresholdEvent(compositeRandomVector, ot.Less(), 0.0)
        >>> print(event.getFrozenSample([[0.2], [-0.1]]))
            [ y0 ]
        0 : [ 0  ]
        1 : [ 1  ]
        """
        return _metamodel.CompositeRandomVector_getFrozenSample(self, fixedSample)

    def getMarginal(self, *args):
        r"""
        Get the random vector corresponding to the :math:`i^{th}` marginal component(s).

        Parameters
        ----------
        i : int or list of ints, :math:`0\leq i < dim`
            Indicates the component(s) concerned. :math:`dim` is the dimension of the
            RandomVector.

        Returns
        -------
        vector :  :class:`~openturns.RandomVector`
            RandomVector restricted to the concerned components.

        Notes
        -----
        Let's note :math:`\vect{Y}=\Tr{(Y_1,\dots,Y_n)}` a random vector and
        :math:`I \in [1,n]` a set of indices. If :math:`\vect{Y}` is a
        :class:`~openturns.UsualRandomVector`, the subvector is defined by
        :math:`\tilde{\vect{Y}}=\Tr{(Y_i)}_{i \in I}`. If :math:`\vect{Y}` is a
        :class:`~openturns.CompositeRandomVector`, defined by
        :math:`\vect{Y}=f(\vect{X})` with :math:`f=(f_1,\dots,f_n)`,
        :math:`f_i` some scalar functions, the subvector is
        :math:`\tilde{\vect{Y}}=(f_i(\vect{X}))_{i \in I}`.

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal([0.0, 0.0], [1.0, 1.0], ot.CorrelationMatrix(2))
        >>> randomVector = ot.RandomVector(distribution)
        >>> ot.RandomGenerator.SetSeed(0)
        >>> print(randomVector.getMarginal(1).getRealization())
        [0.608202]
        >>> print(randomVector.getMarginal(1).getDistribution())
        Normal(mu = 0, sigma = 1)

        """
        return _metamodel.CompositeRandomVector_getMarginal(self, *args)

    def getAntecedent(self):
        r"""
        Accessor to the antecedent RandomVector in case of a composite RandomVector.

        Returns
        -------
        antecedent : :class:`~openturns.RandomVector`
            Antecedent RandomVector :math:`\vect{X}` in case of a
            :class:`~openturns.CompositeRandomVector` such as:
            :math:`\vect{Y}=f(\vect{X})`.
        """
        return _metamodel.CompositeRandomVector_getAntecedent(self)

    def getFunction(self):
        r"""
        Accessor to the Function in case of a composite RandomVector.

        Returns
        -------
        function : :class:`~openturns.Function`
            Function used to define a :class:`~openturns.CompositeRandomVector` as the
            image through this function of the antecedent :math:`\vect{X}`:
            :math:`\vect{Y}=f(\vect{X})`.
        """
        return _metamodel.CompositeRandomVector_getFunction(self)

    def getParameter(self):
        r"""
        Accessor to the parameter of the distribution.

        Returns
        -------
        parameter : :class:`~openturns.Point`
            Parameter values.
        """
        return _metamodel.CompositeRandomVector_getParameter(self)

    def setParameter(self, parameters):
        r"""
        Accessor to the parameter of the distribution.

        Parameters
        ----------
        parameter : sequence of float
            Parameter values.
        """
        return _metamodel.CompositeRandomVector_setParameter(self, parameters)

    def getParameterDescription(self):
        r"""
        Accessor to the parameter description of the distribution.

        Returns
        -------
        description : :class:`~openturns.Description`
            Parameter names.
        """
        return _metamodel.CompositeRandomVector_getParameterDescription(self)

    def __init__(self, *args):
        _metamodel.CompositeRandomVector_swiginit(self, _metamodel.new_CompositeRandomVector(*args))
    __swig_destroy__ = _metamodel.delete_CompositeRandomVector

# Register CompositeRandomVector in _metamodel:
_metamodel.CompositeRandomVector_swigregister(CompositeRandomVector)
class ThresholdEvent(RandomVector):
    r"""
    Random vector defined from a comparison operator and a threshold.

    The event occurs when the realization of the underlying random vector exceeds the threshold.

    Parameters
    ----------
    antecedent : :class:`~openturns.RandomVector` of dimension 1
        Output variable of interest.
    comparisonOperator : :class:`~openturns.ComparisonOperator`
        Comparison operator used to compare *antecedent* with *threshold*.
    threshold : float
        *threshold* we want to compare to *antecedent*.

    See also
    --------
    ProcessEvent, DomainEvent

    Notes
    -----
    An event is defined as follows:

    .. math::

        \cD_f = \{\vect{X} \in \Rset^n \, / \, g(\vect{X},\vect{d}) \le 0\}

    where :math:`\vect{X}` denotes a random input vector, representing the sources
    of uncertainties, :math:`\vect{d}` is a determinist vector, representing the
    fixed variables and :math:`g(\vect{X},\vect{d})` is the limit state function of
    the model.
    The probability content of the event :math:`\cD_f` is :math:`P_f`:

    .. math::

        P_f = \int_{g(\vect{X},\vect{d})\le 0}f_\vect{X}(\vect{x})\di{\vect{x}}

    Here, the event considered is made explicit directly from the limit state function
    :math:`g(\vect{X}\,,\,\vect{d})` : this is the classical structural reliability
    formulation. However, if the event is a threshold exceedance, it is useful to
    explicit the variable of interest :math:`Z=\tilde{g}(\vect{X}\,,\,\vect{d})`,
    evaluated from the model :math:`\tilde{g}(.)`. In that case, the event
    considered, associated to the threshold :math:`z_s` has the formulation:

    .. math::

        \cD_f = \{ \vect{X} \in \Rset^n \, / \, Z=\tilde{g}(\vect{X}\,,\,\vect{d}) > z_s \}

    and the limit state function is:

    .. math::

        g(\vect{X}\,,\,\vect{d}) &= z_s - Z \\
                                 &= z_s - \tilde{g}(\vect{X}\,,\,\vect{d})

    :math:`P_f` is the threshold exceedance probability, defined as:

    .. math::

        P_f &= P(Z \geq z_s) \\
            &= \int_{g(\vect{X}, \vect{d}) \le 0} \pdf\di{\vect{x}}

    Examples
    --------
    >>> import openturns as ot
    >>> dim = 2
    >>> X = ot.RandomVector(ot.Normal(dim))
    >>> model = ot.SymbolicFunction(['x1', 'x2'], ['x1+x2'])
    >>> Y = ot.CompositeRandomVector(model, X)
    >>> event = ot.ThresholdEvent(Y, ot.Less(), 1.0)

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.ThresholdEvent_getClassName(self)

    def __repr__(self):
        return _metamodel.ThresholdEvent___repr__(self)

    def __str__(self, *args):
        return _metamodel.ThresholdEvent___str__(self, *args)

    def __init__(self, *args):
        _metamodel.ThresholdEvent_swiginit(self, _metamodel.new_ThresholdEvent(*args))
    __swig_destroy__ = _metamodel.delete_ThresholdEvent

# Register ThresholdEvent in _metamodel:
_metamodel.ThresholdEvent_swigregister(ThresholdEvent)
class DomainEvent(CompositeRandomVector):
    r"""
    Event defined from a domain.

    The event occurs when a realization of the underlying random vector belongs to the domain.

    Parameters
    ----------
    antecedent : :class:`~openturns.RandomVector` of dimension 1
        Antecedent.
    domain : :class:`~openturns.Domain`
        Domain, of same dimension.

    See also
    --------
    ProcessEvent, ThresholdEvent

    Examples
    --------
    >>> import openturns as ot
    >>> ot.RandomGenerator.SetSeed(6)
    >>> dim = 2
    >>> X = ot.RandomVector(ot.Normal(dim))
    >>> model = ot.SymbolicFunction(['x1', 'x2'], ['x1+x2', '2*x1'])
    >>> Y = ot.CompositeRandomVector(model, X)
    >>> domain = ot.Interval(dim)
    >>> event = ot.DomainEvent(Y, domain)
    >>> sample = event.getSample(10)
    >>> sample.setDescription([''])
    >>> print(sample)
    0 : [ 0 ]
    1 : [ 0 ]
    2 : [ 0 ]
    3 : [ 0 ]
    4 : [ 0 ]
    5 : [ 0 ]
    6 : [ 0 ]
    7 : [ 1 ]
    8 : [ 0 ]
    9 : [ 0 ]
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.DomainEvent_getClassName(self)

    def __repr__(self):
        return _metamodel.DomainEvent___repr__(self)

    def getDimension(self):
        r"""
        Accessor to the dimension of the RandomVector.

        Returns
        -------
        dimension : positive int
            Dimension of the RandomVector.
        """
        return _metamodel.DomainEvent_getDimension(self)

    def getDomain(self):
        r"""
        Accessor to the domain of the Event.

        Returns
        -------
        domain : :class:`~openturns.Domain`
            Describes the domain of an event.
        """
        return _metamodel.DomainEvent_getDomain(self)

    def getRealization(self):
        r"""
        Compute one realization of the RandomVector.

        Returns
        -------
        realization : :class:`~openturns.Point`
            Sequence of values randomly determined from the RandomVector definition.
            In the case of an event: one realization of the event (considered as a
            Bernoulli variable) which is a boolean value (1 for the realization of the
            event and 0 else).

        See also
        --------
        openturns.RandomVector.getSample

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal([0.0, 0.0], [1.0, 1.0], ot.CorrelationMatrix(2))
        >>> randomVector = ot.RandomVector(distribution)
        >>> ot.RandomGenerator.SetSeed(0)
        >>> print(randomVector.getRealization())
        [0.608202,-1.26617]
        >>> print(randomVector.getRealization())
        [-0.438266,1.20548]
        """
        return _metamodel.DomainEvent_getRealization(self)

    def getFrozenRealization(self, fixedPoint):
        r"""
        Compute realizations of the RandomVector.

        In the case of a :class:`~openturns.CompositeRandomVector`
        or an event of some kind, this method returns
        the value taken by the random vector if the root cause
        takes the value given as argument.

        Parameters
        ----------
        fixedPoint : :class:`~openturns.Point`
            Point chosen as the root cause of the random vector.

        Returns
        -------
        realization : :class:`~openturns.Point`
            The realization corresponding to the chosen root cause.

        See also
        --------
        openturns.RandomVector.getRealization
        openturns.RandomVector.getFrozenSample

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal()
        >>> randomVector = ot.RandomVector(distribution)
        >>> f = ot.SymbolicFunction('x', 'x')
        >>> compositeRandomVector = ot.CompositeRandomVector(f, randomVector)
        >>> event = ot.ThresholdEvent(compositeRandomVector, ot.Less(), 0.0)
        >>> print(event.getFrozenRealization([0.2]))
        [0]
        >>> print(event.getFrozenRealization([-0.1]))
        [1]
        """
        return _metamodel.DomainEvent_getFrozenRealization(self, fixedPoint)

    def getSample(self, size):
        r"""
        Compute realizations of the RandomVector.

        Parameters
        ----------
        n : int, :math:`n \geq 0`
            Number of realizations needed.

        Returns
        -------
        realizations : :class:`~openturns.Sample`
            n sequences of values randomly determined from the RandomVector definition.
            In the case of an event: n realizations of the event (considered as a
            Bernoulli variable) which are boolean values (1 for the realization of the
            event and 0 else).

        See also
        --------
        openturns.RandomVector.getRealization

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal([0.0, 0.0], [1.0, 1.0], ot.CorrelationMatrix(2))
        >>> randomVector = ot.RandomVector(distribution)
        >>> ot.RandomGenerator.SetSeed(0)
        >>> print(randomVector.getSample(3))
            [ X0        X1        ]
        0 : [  0.608202 -1.26617  ]
        1 : [ -0.438266  1.20548  ]
        2 : [ -2.18139   0.350042 ]
        """
        return _metamodel.DomainEvent_getSample(self, size)

    def getFrozenSample(self, fixedSample):
        r"""
        Compute realizations of the RandomVector.

        In the case of a :class:`~openturns.CompositeRandomVector`
        or an event of some kind, this method returns
        the different values taken by the random vector when the root cause
        takes the values given as argument.

        Parameters
        ----------
        fixedSample : :class:`~openturns.Sample`
            Sample of root causes of the random vector.

        Returns
        -------
        sample : :class:`~openturns.Sample`
            Sample of the realizations corresponding to the chosen root causes.

        See also
        --------
        openturns.RandomVector.getSample
        openturns.RandomVector.getFrozenRealization

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal()
        >>> randomVector = ot.RandomVector(distribution)
        >>> f = ot.SymbolicFunction('x', 'x')
        >>> compositeRandomVector = ot.CompositeRandomVector(f, randomVector)
        >>> event = ot.ThresholdEvent(compositeRandomVector, ot.Less(), 0.0)
        >>> print(event.getFrozenSample([[0.2], [-0.1]]))
            [ y0 ]
        0 : [ 0  ]
        1 : [ 1  ]
        """
        return _metamodel.DomainEvent_getFrozenSample(self, fixedSample)

    def isEvent(self):
        r"""
        Whether the random vector is an event.

        Returns
        -------
        isEvent : bool
            Whether it takes it values in {0, 1}.
        """
        return _metamodel.DomainEvent_isEvent(self)

    def asComposedEvent(self):
        r"""
        If the random vector can be viewed as the composition of several :class:`~openturns.ThresholdEvent` objects,
        this method builds and returns the composition.
        Otherwise throws.

        Returns
        -------
        composed : :class:`~openturns.RandomVector`
            Composed event.
        """
        return _metamodel.DomainEvent_asComposedEvent(self)

    def __init__(self, *args):
        _metamodel.DomainEvent_swiginit(self, _metamodel.new_DomainEvent(*args))
    __swig_destroy__ = _metamodel.delete_DomainEvent

# Register DomainEvent in _metamodel:
_metamodel.DomainEvent_swigregister(DomainEvent)
class ProcessEvent(openturns.randomvector.RandomVectorImplementation):
    r"""
    Event defined from a process and a domain.

    The event occurs when the process enters the specified domain.

    Parameters
    ----------
    process : :class:`~openturns.Process`
        Process.
    domain : :class:`~openturns.Domain`
        Domain, of same dimension.

    See also
    --------
    DomainEvent, ThresholdEvent

    Examples
    --------
    >>> import openturns as ot
    >>> dim = 2
    >>> dist = ot.Normal(dim)
    >>> X = ot.WhiteNoise(dist)
    >>> domain = ot.Interval(dim)
    >>> event = ot.ProcessEvent(X, domain)
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.ProcessEvent_getClassName(self)

    def __repr__(self):
        return _metamodel.ProcessEvent___repr__(self)

    def getDimension(self):
        r"""
        Accessor to the dimension of the RandomVector.

        Returns
        -------
        dimension : positive int
            Dimension of the RandomVector.
        """
        return _metamodel.ProcessEvent_getDimension(self)

    def getDomain(self):
        r"""
        Accessor to the domain of the Event.

        Returns
        -------
        domain : :class:`~openturns.Domain`
            Describes the domain of an event.
        """
        return _metamodel.ProcessEvent_getDomain(self)

    def getProcess(self):
        r"""
        Get the stochastic process.

        Returns
        -------
        process : :class:`~openturns.Process`
            Stochastic process used to define the :class:`~openturns.RandomVector`.
        """
        return _metamodel.ProcessEvent_getProcess(self)

    def getRealization(self):
        r"""
        Compute one realization of the RandomVector.

        Returns
        -------
        realization : :class:`~openturns.Point`
            Sequence of values randomly determined from the RandomVector definition.
            In the case of an event: one realization of the event (considered as a
            Bernoulli variable) which is a boolean value (1 for the realization of the
            event and 0 else).

        See also
        --------
        openturns.RandomVector.getSample

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal([0.0, 0.0], [1.0, 1.0], ot.CorrelationMatrix(2))
        >>> randomVector = ot.RandomVector(distribution)
        >>> ot.RandomGenerator.SetSeed(0)
        >>> print(randomVector.getRealization())
        [0.608202,-1.26617]
        >>> print(randomVector.getRealization())
        [-0.438266,1.20548]
        """
        return _metamodel.ProcessEvent_getRealization(self)

    def isEvent(self):
        r"""
        Whether the random vector is an event.

        Returns
        -------
        isEvent : bool
            Whether it takes it values in {0, 1}.
        """
        return _metamodel.ProcessEvent_isEvent(self)

    def __init__(self, *args):
        _metamodel.ProcessEvent_swiginit(self, _metamodel.new_ProcessEvent(*args))
    __swig_destroy__ = _metamodel.delete_ProcessEvent

# Register ProcessEvent in _metamodel:
_metamodel.ProcessEvent_swigregister(ProcessEvent)
class CompoundRandomVector(openturns.randomvector.RandomVectorImplementation):
    r"""
    Conditional random vector.

    Helper class for defining the random vector :math:`\vect{X}` such that  :math:`\vect{X}|\vect{\Theta}` follows the distribution :math:`\mathcal{L}_{\vect{X}|\vect{\Theta}}`, with :math:`\vect{\Theta}` a random vector of dimension the dimension of :math:`\vect{\Theta}`.

    Parameters
    ----------
    conditionedDist : :class:`~openturns.Distribution`
        the distribution of :math:`\vect{X}|\vect{\Theta}`, whose parameters will be overwritten by :math:`\vect{\Theta}`.
    parametersRandomVector : :class:`~openturns.RandomVector`
        the parameters random vector :math:`\vect{\Theta}` of the `conditionedDist` distribution. 

    Notes
    -----
    Let :math:`\inputRV` be a random vector of dimension :math:`\inputDim` such that
    :math:`\vect{X}|\vect{\Theta}` follows the distribution :math:`\mathcal{L}_{\vect{X}|\vect{\Theta}}`,
    with :math:`\vect{\Theta}` a random vector following the distribution :math:`\mathcal{L}_{\vect{\Theta}}`.

    Then this class implements the random vector :math:`\inputRV`. Note that a :class:`~openturns.RandomVector` can only be sampled.

    There is no restriction on the random vector :math:`\vect{\Theta}`. It can be created from any multivariate distribution or
    as the output of a function :math:`f` applied to an input random vector :math:`\vect{Y}`: :math:`\vect{\Theta} = f(\vect{Y})`.

    Note that in some restricted cases, it is possible to create the distribution of :math:`\inputRV` using the class :class:`~openturns.CompoundDistribution`.

    Examples
    --------
    Create a random vector:

    >>> import openturns as ot
    >>> distXgivenT = ot.Exponential()
    >>> distGamma = ot.Uniform(1.0, 2.0)
    >>> distAlpha = ot.Uniform(0.0, 0.1)
    >>> distTheta = ot.JointDistribution([distGamma, distAlpha])
    >>> rvTheta = ot.RandomVector(distTheta)
    >>> rvX = ot.CompoundRandomVector(distXgivenT, rvTheta)

    Draw a sample:

    >>> sample = rvX.getSample(5)

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.CompoundRandomVector_getClassName(self)

    def __repr__(self):
        return _metamodel.CompoundRandomVector___repr__(self)

    def getDimension(self):
        r"""
        Accessor to the dimension of the RandomVector.

        Returns
        -------
        dimension : positive int
            Dimension of the RandomVector.
        """
        return _metamodel.CompoundRandomVector_getDimension(self)

    def getRealization(self, *args):
        r"""
        Compute one realization of the RandomVector.

        Returns
        -------
        realization : :class:`~openturns.Point`
            Sequence of values randomly determined from the RandomVector definition.
            In the case of an event: one realization of the event (considered as a
            Bernoulli variable) which is a boolean value (1 for the realization of the
            event and 0 else).

        See also
        --------
        openturns.RandomVector.getSample

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal([0.0, 0.0], [1.0, 1.0], ot.CorrelationMatrix(2))
        >>> randomVector = ot.RandomVector(distribution)
        >>> ot.RandomGenerator.SetSeed(0)
        >>> print(randomVector.getRealization())
        [0.608202,-1.26617]
        >>> print(randomVector.getRealization())
        [-0.438266,1.20548]
        """
        return _metamodel.CompoundRandomVector_getRealization(self, *args)

    def getDistribution(self):
        r"""
        Accessor to the distribution's conditioned distribution parameter `conditionedDistribution`.

        Returns
        -------
        conditionedDistribution : :class:`~openturns.Distribution`, the distribution of :math:`\vect{X}|\vect{\Theta}=\vect{\theta}`, where the parameters :math:`\vect{\theta}` are equal to the  values used to generate the last realization of :math:`\vect{X}`.

        """
        return _metamodel.CompoundRandomVector_getDistribution(self)

    def getRandomParameters(self):
        r"""
        Accessor to the distribution's random parameter `randomParameters`.

        Returns
        -------
        randomParameters : :class:`~openturns.RandomVector`, the random parameters :math:`\vect{\Theta}`.

        """
        return _metamodel.CompoundRandomVector_getRandomParameters(self)

    def getParameter(self):
        r"""
        Accessor to the parameter of the distribution.

        Returns
        -------
        parameter : :class:`~openturns.Point`
            Parameter values.
        """
        return _metamodel.CompoundRandomVector_getParameter(self)

    def setParameter(self, parameters):
        r"""
        Accessor to the parameter of the distribution.

        Parameters
        ----------
        parameter : sequence of float
            Parameter values.
        """
        return _metamodel.CompoundRandomVector_setParameter(self, parameters)

    def getParameterDescription(self):
        r"""
        Accessor to the parameter description of the distribution.

        Returns
        -------
        description : :class:`~openturns.Description`
            Parameter names.
        """
        return _metamodel.CompoundRandomVector_getParameterDescription(self)

    def __init__(self, *args):
        _metamodel.CompoundRandomVector_swiginit(self, _metamodel.new_CompoundRandomVector(*args))
    __swig_destroy__ = _metamodel.delete_CompoundRandomVector

# Register CompoundRandomVector in _metamodel:
_metamodel.CompoundRandomVector_swigregister(CompoundRandomVector)

def DeconditionedRandomVector(conditionedDist, parametersRandomVector):
    """
    Retro-compatibility alias for CompoundRandomVector.
    """
    openturns.common.Log.Warn('class DeconditionedRandomVector is deprecated in favor of CompoundRandomVector')
    return openturns.metamodel.CompoundRandomVector(conditionedDist, parametersRandomVector)

class StandardEvent(RandomVector):
    r"""
    Event defined in the standard space.

    Available constructor:
        StandardEvent(*antecedent, comparisonOperator, threshold*)

        StandardEvent(*event*)

    Parameters
    ----------
    antecedent : :class:`~openturns.RandomVector` of dimension 1
        Output variable of interest.
    comparisonOperator : :class:`~openturns.ComparisonOperator`
        Comparison operator used to compare *antecedent* with *threshold*.
    threshold : float
        *threshold* we want to compare to *antecedent*.
    event : :class:`~openturns.RandomVector`
        Physical event associated with the standard event to be created.

    Notes
    -----
    An event is defined as follows:

    .. math::

        \cD_f = \{\vect{X} \in \Rset^n \, / \, g(\vect{X},\vect{d}) \le 0\}

    where :math:`\vect{X}` denotes a random input vector, representing the sources
    of uncertainties, :math:`\vect{d}` is a determinist vector, representing the
    fixed variables and :math:`g(\vect{X},\vect{d})` is the limit state function of
    the model.

    One way to evaluate the probability content :math:`P_f` of the event :math:`\cD_f`:

    .. math::

        P_f = \int_{g(\vect{X},\vect{d})\le 0}f_\vect{X}(\vect{x})\di{\vect{x}}

    is to use an isoprobabilistic transformation to move from the physical space
    to a standard normal space (U-space) where distributions are spherical
    (invariant by rotation by definition), with zero mean, unit variance and unit
    correlation matrix. The usual isoprobabilistic transformations are the 
    Generalized Nataf transformation and Rosenblatt transformation.

    In that new U-space, the event can be expressed in terms of 
    the transformed limit state function of the model :math:`g`

    .. math::

        \cD_f = \{\vect{U} \in \Rset^n \, | \, g(\vect{U}\,,\,\vect{d}) \le 0\}

    See also
    --------
    Analytical, SORM, FORM, SORMResult, FORMResult, StrongMaximumTest, ImportanceSamplingExperiment

    Examples
    --------

    A StandardEvent created from a limit state function :

    >>> import openturns as ot
    >>> myFunction = ot.SymbolicFunction(['E', 'F', 'L', 'I'], ['-F*L^3/(3*E*I)'])
    >>> myDistribution = ot.Normal(4)
    >>> vect = ot.RandomVector(myDistribution)
    >>> output = ot.CompositeRandomVector(myFunction, vect)
    >>> myStandardEvent = ot.StandardEvent(output, ot.Less(), 1.0)

    A StandardEvent based on an event :

    >>> myEvent = ot.ThresholdEvent(output, ot.Less(), 1.0)
    >>> myStandardEvent = ot.StandardEvent(myEvent)

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __repr__ = _swig_repr

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.StandardEvent_getClassName(self)

    def __init__(self, *args):
        _metamodel.StandardEvent_swiginit(self, _metamodel.new_StandardEvent(*args))
    __swig_destroy__ = _metamodel.delete_StandardEvent

# Register StandardEvent in _metamodel:
_metamodel.StandardEvent_swigregister(StandardEvent)
class RandomVectorCollection(object):
    r"""
    Collection.

    Examples
    --------
    >>> import openturns as ot

    - Collection of **real values**:

    >>> ot.ScalarCollection(2)
    [0,0]
    >>> ot.ScalarCollection(2, 3.25)
    [3.25,3.25]
    >>> vector = ot.ScalarCollection([2.0, 1.5, 2.6])
    >>> vector
    [2,1.5,2.6]
    >>> vector[1] = 4.2
    >>> vector
    [2,4.2,2.6]
    >>> vector.add(3.8)
    >>> vector
    [2,4.2,2.6,3.8]

    - Collection of **complex values**:

    >>> ot.ComplexCollection(2)
    [(0,0),(0,0)]
    >>> ot.ComplexCollection(2, 3+4j)
    [(3,4),(3,4)]
    >>> vector = ot.ComplexCollection([2+3j, 1-4j, 3.0])
    >>> vector
    [(2,3),(1,-4),(3,0)]
    >>> vector[1] = 4+3j
    >>> vector
    [(2,3),(4,3),(3,0)]
    >>> vector.add(5+1j)
    >>> vector
    [(2,3),(4,3),(3,0),(5,1)]

    - Collection of **booleans**:

    >>> ot.BoolCollection(3)
    [0,0,0]
    >>> ot.BoolCollection(3, 1)
    [1,1,1]
    >>> vector = ot.BoolCollection([0, 1, 0])
    >>> vector
    [0,1,0]
    >>> vector[1] = 0
    >>> vector
    [0,0,0]
    >>> vector.add(1)
    >>> vector
    [0,0,0,1]

    - Collection of **distributions**:

    >>> print(ot.DistributionCollection(2))
    [Uniform(a = -1, b = 1),Uniform(a = -1, b = 1)]
    >>> print(ot.DistributionCollection(2, ot.Gamma(2.75, 1.0)))
    [Gamma(k = 2.75, lambda = 1, gamma = 0),Gamma(k = 2.75, lambda = 1, gamma = 0)]
    >>> vector = ot.DistributionCollection([ot.Normal(), ot.Uniform()])
    >>> print(vector)
    [Normal(mu = 0, sigma = 1),Uniform(a = -1, b = 1)]
    >>> vector[1] = ot.Uniform(-0.5, 1)
    >>> print(vector)
    [Normal(mu = 0, sigma = 1),Uniform(a = -0.5, b = 1)]
    >>> vector.add(ot.Gamma(2.75, 1.0))
    >>> print(vector)
    [Normal(mu = 0, sigma = 1),Uniform(a = -0.5, b = 1),Gamma(k = 2.75, lambda = 1, gamma = 0)]
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __swig_destroy__ = _metamodel.delete_RandomVectorCollection

    def clear(self):
        r"""
        Reset the collection to zero dimension.

        Examples
        --------
        >>> import openturns as ot
        >>> x = ot.Point(2)
        >>> x.clear()
        >>> x
        class=Point name=Unnamed dimension=0 values=[]
        """
        return _metamodel.RandomVectorCollection_clear(self)

    def __len__(self):
        return _metamodel.RandomVectorCollection___len__(self)

    def __eq__(self, rhs):
        return _metamodel.RandomVectorCollection___eq__(self, rhs)

    def __contains__(self, val):
        return _metamodel.RandomVectorCollection___contains__(self, val)

    def select(self, marginalIndices):
        r"""
        Selection from indices.

        Parameters
        ----------
        indices : sequence of int
            Indices to select

        Returns
        -------
        coll : sequence
            Sub-collection of values at the selection indices.
        """
        return _metamodel.RandomVectorCollection_select(self, marginalIndices)

    def __getitem__(self, i):
        return _metamodel.RandomVectorCollection___getitem__(self, i)

    def __setitem__(self, i, val):
        return _metamodel.RandomVectorCollection___setitem__(self, i, val)

    def __delitem__(self, i):
        return _metamodel.RandomVectorCollection___delitem__(self, i)

    def at(self, *args):
        r"""
        Access to an element of the collection.

        Parameters
        ----------
        index : positive int
            Position of the element to access.

        Returns
        -------
        element : type depends on the type of the collection
            Element of the collection at the position *index*.
        """
        return _metamodel.RandomVectorCollection_at(self, *args)

    def add(self, *args):
        r"""
        Append a component (in-place).

        Parameters
        ----------
        value : type depends on the type of the collection.
            The component to append.

        Examples
        --------
        >>> import openturns as ot
        >>> x = ot.Point(2)
        >>> x.add(1.)
        >>> print(x)
        [0,0,1]
        """
        return _metamodel.RandomVectorCollection_add(self, *args)

    def getSize(self):
        r"""
        Get the collection's dimension (or size).

        Returns
        -------
        n : int
            The number of components in the collection.
        """
        return _metamodel.RandomVectorCollection_getSize(self)

    def resize(self, newSize):
        r"""
        Change the size of the collection.

        Parameters
        ----------
        newSize : positive int
            New size of the collection.

        Notes
        -----
        If the new size is smaller than the older one, the last elements are thrown
        away, else the new elements are set to the default value of the element type.

        Examples
        --------
        >>> import openturns as ot
        >>> x = ot.Point(2, 4)
        >>> print(x)
        [4,4]
        >>> x.resize(1)
        >>> print(x)
        [4]
        >>> x.resize(4)
        >>> print(x)
        [4,0,0,0]
        """
        return _metamodel.RandomVectorCollection_resize(self, newSize)

    def isEmpty(self):
        r"""
        Tell if the collection is empty.

        Returns
        -------
        isEmpty : bool
            *True* if there is no element in the collection.

        Examples
        --------
        >>> import openturns as ot
        >>> x = ot.Point(2)
        >>> x.isEmpty()
        False
        >>> x.clear()
        >>> x.isEmpty()
        True
        """
        return _metamodel.RandomVectorCollection_isEmpty(self)

    def find(self, val):
        return _metamodel.RandomVectorCollection_find(self, val)

    def __repr__(self):
        return _metamodel.RandomVectorCollection___repr__(self)

    def __str__(self, *args):
        return _metamodel.RandomVectorCollection___str__(self, *args)

    def index(self, value):
        r"""
        Find the index of a given value.

        Parameters
        ----------
        val : collection value type
            The value to find

        Returns
        -------
        index : int
            The index of the first occurrence of the value.
            Throws when the value is not found.
        """
        return _metamodel.RandomVectorCollection_index(self, value)

    def __init__(self, *args):
        _metamodel.RandomVectorCollection_swiginit(self, _metamodel.new_RandomVectorCollection(*args))

# Register RandomVectorCollection in _metamodel:
_metamodel.RandomVectorCollection_swigregister(RandomVectorCollection)
class IntersectionEvent(openturns.randomvector.RandomVectorImplementation):
    r"""
    Event defined as the intersection of several events.

    The occurrence of all the events is necessary for the system event to occur (parallel system):

    .. math::

        E_{sys} = \bigcap_{i=1}^N E_i

    Parameters
    ----------
    coll : sequence of :class:`~openturns.RandomVector`
        Collection of events, evaluated from left to right.
        Ordering the least probable events first can help to avoid evaluating the last ones.
        In case the ranking of the probabilities of the events is unknown,
        it can be quickly estimated with (for example) a FORM analysis
        of each individual event.

    See also
    --------
    UnionEvent

    Examples
    --------
    >>> import openturns as ot
    >>> dim = 2
    >>> X = ot.RandomVector(ot.Normal(dim))
    >>> f1 = ot.SymbolicFunction(['x1', 'x2'], ['x1'])
    >>> f2 = ot.SymbolicFunction(['x1', 'x2'], ['x2'])
    >>> Y1 = ot.CompositeRandomVector(f1, X)
    >>> Y2 = ot.CompositeRandomVector(f2, X)
    >>> e1 = ot.ThresholdEvent(Y1, ot.Less(), 0.0)
    >>> e2 = ot.ThresholdEvent(Y2, ot.Greater(), 0.0)
    >>> event = ot.IntersectionEvent([e1, e2])

    Then it can be used for sampling (or with simulation algorithms):

    >>> p = event.getSample(1000).computeMean()

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.IntersectionEvent_getClassName(self)

    def __repr__(self):
        return _metamodel.IntersectionEvent___repr__(self)

    def getDimension(self):
        r"""
        Accessor to the dimension of the RandomVector.

        Returns
        -------
        dimension : positive int
            Dimension of the RandomVector.
        """
        return _metamodel.IntersectionEvent_getDimension(self)

    def setEventCollection(self, collection):
        r"""
        Accessor to sub events.

        Parameters
        ----------
        events : sequence of :class:`~openturns.RandomVector`
            List of sub events.
        """
        return _metamodel.IntersectionEvent_setEventCollection(self, collection)

    def getEventCollection(self):
        r"""
        Accessor to sub events.

        Returns
        -------
        events : :class:`~openturns.RandomVectorCollection`
            List of sub events.
        """
        return _metamodel.IntersectionEvent_getEventCollection(self)

    def getRealization(self):
        r"""
        Compute one realization of the RandomVector.

        Returns
        -------
        realization : :class:`~openturns.Point`
            Sequence of values randomly determined from the RandomVector definition.
            In the case of an event: one realization of the event (considered as a
            Bernoulli variable) which is a boolean value (1 for the realization of the
            event and 0 else).

        See also
        --------
        openturns.RandomVector.getSample

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal([0.0, 0.0], [1.0, 1.0], ot.CorrelationMatrix(2))
        >>> randomVector = ot.RandomVector(distribution)
        >>> ot.RandomGenerator.SetSeed(0)
        >>> print(randomVector.getRealization())
        [0.608202,-1.26617]
        >>> print(randomVector.getRealization())
        [-0.438266,1.20548]
        """
        return _metamodel.IntersectionEvent_getRealization(self)

    def getFrozenRealization(self, fixedPoint):
        r"""
        Compute realizations of the RandomVector.

        In the case of a :class:`~openturns.CompositeRandomVector`
        or an event of some kind, this method returns
        the value taken by the random vector if the root cause
        takes the value given as argument.

        Parameters
        ----------
        fixedPoint : :class:`~openturns.Point`
            Point chosen as the root cause of the random vector.

        Returns
        -------
        realization : :class:`~openturns.Point`
            The realization corresponding to the chosen root cause.

        See also
        --------
        openturns.RandomVector.getRealization
        openturns.RandomVector.getFrozenSample

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal()
        >>> randomVector = ot.RandomVector(distribution)
        >>> f = ot.SymbolicFunction('x', 'x')
        >>> compositeRandomVector = ot.CompositeRandomVector(f, randomVector)
        >>> event = ot.ThresholdEvent(compositeRandomVector, ot.Less(), 0.0)
        >>> print(event.getFrozenRealization([0.2]))
        [0]
        >>> print(event.getFrozenRealization([-0.1]))
        [1]
        """
        return _metamodel.IntersectionEvent_getFrozenRealization(self, fixedPoint)

    def getSample(self, size):
        r"""
        Compute realizations of the RandomVector.

        Parameters
        ----------
        n : int, :math:`n \geq 0`
            Number of realizations needed.

        Returns
        -------
        realizations : :class:`~openturns.Sample`
            n sequences of values randomly determined from the RandomVector definition.
            In the case of an event: n realizations of the event (considered as a
            Bernoulli variable) which are boolean values (1 for the realization of the
            event and 0 else).

        See also
        --------
        openturns.RandomVector.getRealization

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal([0.0, 0.0], [1.0, 1.0], ot.CorrelationMatrix(2))
        >>> randomVector = ot.RandomVector(distribution)
        >>> ot.RandomGenerator.SetSeed(0)
        >>> print(randomVector.getSample(3))
            [ X0        X1        ]
        0 : [  0.608202 -1.26617  ]
        1 : [ -0.438266  1.20548  ]
        2 : [ -2.18139   0.350042 ]
        """
        return _metamodel.IntersectionEvent_getSample(self, size)

    def getFrozenSample(self, fixedSample):
        r"""
        Compute realizations of the RandomVector.

        In the case of a :class:`~openturns.CompositeRandomVector`
        or an event of some kind, this method returns
        the different values taken by the random vector when the root cause
        takes the values given as argument.

        Parameters
        ----------
        fixedSample : :class:`~openturns.Sample`
            Sample of root causes of the random vector.

        Returns
        -------
        sample : :class:`~openturns.Sample`
            Sample of the realizations corresponding to the chosen root causes.

        See also
        --------
        openturns.RandomVector.getSample
        openturns.RandomVector.getFrozenRealization

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal()
        >>> randomVector = ot.RandomVector(distribution)
        >>> f = ot.SymbolicFunction('x', 'x')
        >>> compositeRandomVector = ot.CompositeRandomVector(f, randomVector)
        >>> event = ot.ThresholdEvent(compositeRandomVector, ot.Less(), 0.0)
        >>> print(event.getFrozenSample([[0.2], [-0.1]]))
            [ y0 ]
        0 : [ 0  ]
        1 : [ 1  ]
        """
        return _metamodel.IntersectionEvent_getFrozenSample(self, fixedSample)

    def isEvent(self):
        r"""
        Whether the random vector is an event.

        Returns
        -------
        isEvent : bool
            Whether it takes it values in {0, 1}.
        """
        return _metamodel.IntersectionEvent_isEvent(self)

    def isComposite(self):
        r"""
        Accessor to know if the RandomVector is a composite one.

        Returns
        -------
        isComposite : bool
            Indicates if the RandomVector is of type Composite or not.
        """
        return _metamodel.IntersectionEvent_isComposite(self)

    def getAntecedent(self):
        r"""
        Accessor to the antecedent random vector.

        Returns
        -------
        antecedent : :class:`~openturns.RandomVector`
            Defined as the root cause.
        """
        return _metamodel.IntersectionEvent_getAntecedent(self)

    def asComposedEvent(self):
        r"""
        If the random vector can be viewed as the composition of several :class:`~openturns.ThresholdEvent` objects,
        this method builds and returns the composition.
        Otherwise throws.

        Returns
        -------
        composed : :class:`~openturns.RandomVector`
            Composed event.
        """
        return _metamodel.IntersectionEvent_asComposedEvent(self)

    def __init__(self, *args):
        _metamodel.IntersectionEvent_swiginit(self, _metamodel.new_IntersectionEvent(*args))
    __swig_destroy__ = _metamodel.delete_IntersectionEvent

# Register IntersectionEvent in _metamodel:
_metamodel.IntersectionEvent_swigregister(IntersectionEvent)
class UnionEvent(openturns.randomvector.RandomVectorImplementation):
    r"""
    Event defined as the union of several events.

    An occurrence of one single event :math:`E_i` yields the occurrence of the system event (series system):

    .. math::

        E_{sys} = \bigcup_{i=1}^N E_i

    Parameters
    ----------
    coll : sequence of :class:`~openturns.RandomVector`
        Collection of events, evaluated from left to right.
        Ordering the most probable events first can help to avoid evaluating the last ones.
        In case the ranking of the probabilities of the events is unknown,
        it can be quickly estimated with (for example) a FORM analysis
        of each individual event.

    See also
    --------
    IntersectionEvent

    Examples
    --------
    >>> import openturns as ot
    >>> dim = 2
    >>> X = ot.RandomVector(ot.Normal(dim))
    >>> f1 = ot.SymbolicFunction(['x1', 'x2'], ['x1'])
    >>> f2 = ot.SymbolicFunction(['x1', 'x2'], ['x2'])
    >>> Y1 = ot.CompositeRandomVector(f1, X)
    >>> Y2 = ot.CompositeRandomVector(f2, X)
    >>> e1 = ot.ThresholdEvent(Y1, ot.Less(), 0.0)
    >>> e2 = ot.ThresholdEvent(Y2, ot.Greater(), 0.0)
    >>> event = ot.UnionEvent([e1, e2])

    Then it can be used for sampling (or with simulation algorithms):

    >>> p = event.getSample(1000).computeMean()

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.UnionEvent_getClassName(self)

    def __repr__(self):
        return _metamodel.UnionEvent___repr__(self)

    def getDimension(self):
        r"""
        Accessor to the dimension of the RandomVector.

        Returns
        -------
        dimension : positive int
            Dimension of the RandomVector.
        """
        return _metamodel.UnionEvent_getDimension(self)

    def setEventCollection(self, collection):
        r"""
        Accessor to sub events.

        Parameters
        ----------
        events : sequence of :class:`~openturns.RandomVector`
            List of sub events.
        """
        return _metamodel.UnionEvent_setEventCollection(self, collection)

    def getEventCollection(self):
        r"""
        Accessor to sub events.

        Returns
        -------
        events : :class:`~openturns.RandomVectorCollection`
            List of sub events.
        """
        return _metamodel.UnionEvent_getEventCollection(self)

    def getRealization(self):
        r"""
        Compute one realization of the RandomVector.

        Returns
        -------
        realization : :class:`~openturns.Point`
            Sequence of values randomly determined from the RandomVector definition.
            In the case of an event: one realization of the event (considered as a
            Bernoulli variable) which is a boolean value (1 for the realization of the
            event and 0 else).

        See also
        --------
        openturns.RandomVector.getSample

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal([0.0, 0.0], [1.0, 1.0], ot.CorrelationMatrix(2))
        >>> randomVector = ot.RandomVector(distribution)
        >>> ot.RandomGenerator.SetSeed(0)
        >>> print(randomVector.getRealization())
        [0.608202,-1.26617]
        >>> print(randomVector.getRealization())
        [-0.438266,1.20548]
        """
        return _metamodel.UnionEvent_getRealization(self)

    def getFrozenRealization(self, fixedPoint):
        r"""
        Compute realizations of the RandomVector.

        In the case of a :class:`~openturns.CompositeRandomVector`
        or an event of some kind, this method returns
        the value taken by the random vector if the root cause
        takes the value given as argument.

        Parameters
        ----------
        fixedPoint : :class:`~openturns.Point`
            Point chosen as the root cause of the random vector.

        Returns
        -------
        realization : :class:`~openturns.Point`
            The realization corresponding to the chosen root cause.

        See also
        --------
        openturns.RandomVector.getRealization
        openturns.RandomVector.getFrozenSample

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal()
        >>> randomVector = ot.RandomVector(distribution)
        >>> f = ot.SymbolicFunction('x', 'x')
        >>> compositeRandomVector = ot.CompositeRandomVector(f, randomVector)
        >>> event = ot.ThresholdEvent(compositeRandomVector, ot.Less(), 0.0)
        >>> print(event.getFrozenRealization([0.2]))
        [0]
        >>> print(event.getFrozenRealization([-0.1]))
        [1]
        """
        return _metamodel.UnionEvent_getFrozenRealization(self, fixedPoint)

    def getSample(self, size):
        r"""
        Compute realizations of the RandomVector.

        Parameters
        ----------
        n : int, :math:`n \geq 0`
            Number of realizations needed.

        Returns
        -------
        realizations : :class:`~openturns.Sample`
            n sequences of values randomly determined from the RandomVector definition.
            In the case of an event: n realizations of the event (considered as a
            Bernoulli variable) which are boolean values (1 for the realization of the
            event and 0 else).

        See also
        --------
        openturns.RandomVector.getRealization

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal([0.0, 0.0], [1.0, 1.0], ot.CorrelationMatrix(2))
        >>> randomVector = ot.RandomVector(distribution)
        >>> ot.RandomGenerator.SetSeed(0)
        >>> print(randomVector.getSample(3))
            [ X0        X1        ]
        0 : [  0.608202 -1.26617  ]
        1 : [ -0.438266  1.20548  ]
        2 : [ -2.18139   0.350042 ]
        """
        return _metamodel.UnionEvent_getSample(self, size)

    def getFrozenSample(self, fixedSample):
        r"""
        Compute realizations of the RandomVector.

        In the case of a :class:`~openturns.CompositeRandomVector`
        or an event of some kind, this method returns
        the different values taken by the random vector when the root cause
        takes the values given as argument.

        Parameters
        ----------
        fixedSample : :class:`~openturns.Sample`
            Sample of root causes of the random vector.

        Returns
        -------
        sample : :class:`~openturns.Sample`
            Sample of the realizations corresponding to the chosen root causes.

        See also
        --------
        openturns.RandomVector.getSample
        openturns.RandomVector.getFrozenRealization

        Examples
        --------
        >>> import openturns as ot
        >>> distribution = ot.Normal()
        >>> randomVector = ot.RandomVector(distribution)
        >>> f = ot.SymbolicFunction('x', 'x')
        >>> compositeRandomVector = ot.CompositeRandomVector(f, randomVector)
        >>> event = ot.ThresholdEvent(compositeRandomVector, ot.Less(), 0.0)
        >>> print(event.getFrozenSample([[0.2], [-0.1]]))
            [ y0 ]
        0 : [ 0  ]
        1 : [ 1  ]
        """
        return _metamodel.UnionEvent_getFrozenSample(self, fixedSample)

    def isEvent(self):
        r"""
        Whether the random vector is an event.

        Returns
        -------
        isEvent : bool
            Whether it takes it values in {0, 1}.
        """
        return _metamodel.UnionEvent_isEvent(self)

    def isComposite(self):
        r"""
        Accessor to know if the RandomVector is a composite one.

        Returns
        -------
        isComposite : bool
            Indicates if the RandomVector is of type Composite or not.
        """
        return _metamodel.UnionEvent_isComposite(self)

    def getAntecedent(self):
        r"""
        Accessor to the antecedent random vector.

        Returns
        -------
        antecedent : :class:`~openturns.RandomVector`
            Defined as the root cause.
        """
        return _metamodel.UnionEvent_getAntecedent(self)

    def asComposedEvent(self):
        r"""
        If the random vector can be viewed as the composition of several :class:`~openturns.ThresholdEvent` objects,
        this method builds and returns the composition.
        Otherwise throws.

        Returns
        -------
        composed : :class:`~openturns.RandomVector`
            Composed event.
        """
        return _metamodel.UnionEvent_asComposedEvent(self)

    def __init__(self, *args):
        _metamodel.UnionEvent_swiginit(self, _metamodel.new_UnionEvent(*args))
    __swig_destroy__ = _metamodel.delete_UnionEvent

# Register UnionEvent in _metamodel:
_metamodel.UnionEvent_swigregister(UnionEvent)
class FunctionalChaosRandomVector(CompositeRandomVector):
    r"""
    Functional chaos random vector.

    Allows one to simulate a variable through a chaos decomposition,
    and retrieve its mean and covariance analytically from the chaos coefficients.

    Parameters
    ----------
    functionalChaosResult : :class:`~openturns.FunctionalChaosResult`
        A result from a functional chaos decomposition.

    Notes
    -----
    This class can be used to get probabilistic properties of a
    functional chaos expansion or polynomial chaos expansion (PCE).
    For example, we can get the output mean or the output covariance matrix
    using the coefficients of the expansion.

    Moreover, we can use this class to simulate random observations
    of the output.
    We consider the same notations as in the :class:`~openturns.FunctionalChaosAlgorithm`
    class.
    The functional chaos decomposition of *h* is:

    .. math::

        h = \model \circ T^{-1} = \sum_{k=0}^{\infty} \vect{a}_k \Psi_k 


    which can be truncated to the finite set :math:`\cK \subset \Nset`:

    .. math::

        \widetilde{h} =  \sum_{k \in \cK} \vect{a}_k \Psi_k.

    The approximation :math:`\widetilde{h}` can be used to build an efficient random 
    generator of :math:`Y` based on the random vector :math:`\standardRV`,
    using the equation:

    .. math::

        \widetilde{Y} = \widetilde{h}(\standardRV).

    This equation can be used to simulate independent random observations
    from the PCE.
    This can be done by simulating independent observations from
    the distribution of the standardized random vector :math:`\standardRV`,
    which are then pushed forward through the expansion.

    See also
    --------
    FunctionalChaosAlgorithm, FunctionalChaosResult

    Examples
    --------
    First, we create the PCE.

    >>> import openturns as ot
    >>> ot.RandomGenerator.SetSeed(0)
    >>> inputDimension = 1
    >>> model = ot.SymbolicFunction(['x'], ['x * sin(x)'])
    >>> distribution = ot.JointDistribution([ot.Uniform()] * inputDimension)
    >>> polyColl = [0.0] * inputDimension
    >>> for i in range(distribution.getDimension()):
    ...     polyColl[i] = ot.StandardDistributionPolynomialFactory(distribution.getMarginal(i))
    >>> enumerateFunction = ot.LinearEnumerateFunction(inputDimension)
    >>> productBasis = ot.OrthogonalProductPolynomialFactory(polyColl, enumerateFunction)
    >>> degree = 4
    >>> indexMax = enumerateFunction.getBasisSizeFromTotalDegree(degree)
    >>> adaptiveStrategy = ot.FixedStrategy(productBasis, indexMax)
    >>> samplingSize = 50
    >>> experiment = ot.MonteCarloExperiment(distribution, samplingSize)
    >>> inputSample = experiment.generate()
    >>> outputSample = model(inputSample)
    >>> projectionStrategy = ot.LeastSquaresStrategy()
    >>> algo = ot.FunctionalChaosAlgorithm(inputSample, outputSample, \
    ...     distribution, adaptiveStrategy, projectionStrategy)
    >>> algo.run()
    >>> functionalChaosResult = algo.getResult()

    Secondly, we get the probabilistic properties of the PCE.
    We can get an estimate of the
    mean of the output of the physical model.

    >>> functionalChaosRandomVector = ot.FunctionalChaosRandomVector(functionalChaosResult)
    >>> mean = functionalChaosRandomVector.getMean()
    >>> print(mean)
    [0.301168]

    We can get an estimate of the covariance matrix
    of the output of the physical model.

    >>> covariance = functionalChaosRandomVector.getCovariance()
    >>> print(covariance)
    [[ 0.0663228 ]]

    We can finally generate observations from the PCE random
    vector.

    >>> simulatedOutputSample = functionalChaosRandomVector.getSample(5)
    >>> print(simulatedOutputSample)
        [ v0         ]
    0 : [ 0.302951   ]
    1 : [ 0.0664952  ]
    2 : [ 0.0257105  ]
    3 : [ 0.00454319 ]
    4 : [ 0.149589   ]
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.FunctionalChaosRandomVector_getClassName(self)

    def __repr__(self):
        return _metamodel.FunctionalChaosRandomVector___repr__(self)

    def getMean(self):
        r"""
        Accessor to the mean of the functional chaos expansion.

        Let :math:`\inputDim \in \Nset` be the dimension of the input random vector, 
        let :math:`\outputDim \in \Nset` be the dimension of the output random vector,
        and let :math:`P + 1 \in \Nset` be the size of the basis.
        We consider the following functional chaos expansion:

        .. math::

              \widetilde{\outputRV} = \sum_{k = 0}^P \vect{a}_k \psi_k(\standardRV)

        where :math:`\widetilde{\outputRV} \in \Rset^{\outputDim}` is the approximation of the output 
        random variable :math:`\outputRV` by the expansion, 
        :math:`\left\{\vect{a}_k \in \Rset^{\outputDim}\right\}_{k = 0, ..., P}` are the coefficients, 
        :math:`\left\{\psi_k: \Rset^{\inputDim} \rightarrow \Rset\right\}_{k = 0, ..., P}` are the 
        orthonormal functions in the basis, 
        and :math:`\standardRV \in \Rset^{\inputDim}` is the standardized random input vector.
        The previous equation can be equivalently written as follows:

        .. math::

              \widetilde{Y}_i = \sum_{k = 0}^P a_{ki} \psi_k(\standardRV)

        for :math:`i = 1, ..., \outputDim`
        where :math:`a_{ki} \in \Rset` is the :math:`i`-th component of the
        :math:`k`-th coefficient in the expansion:

        .. math::

              \vect{a}_k = \begin{pmatrix}a_{k, 1} \\ \vdots\\ a_{k, \outputDim} \end{pmatrix}.

        The mean of the functional chaos expansion is the first coefficient
        in the expansion:

        .. math::

              \Expect{\widetilde{\outputRV}} = \vect{a}_0.

        Returns
        -------
        mean : :class:`~openturns.Point`, dimension :math:`\outputDim`
            The mean of the functional chaos expansion.

        Examples
        --------

        >>> from openturns.usecases import ishigami_function
        >>> import openturns as ot
        >>> im = ishigami_function.IshigamiModel()
        >>> sampleSize = 300
        >>> inputTrain = im.distribution.getSample(sampleSize)
        >>> outputTrain = im.model(inputTrain)
        >>> multivariateBasis = ot.OrthogonalProductPolynomialFactory([im.X1, im.X2, im.X3])
        >>> selectionAlgorithm = ot.LeastSquaresMetaModelSelectionFactory()
        >>> projectionStrategy = ot.LeastSquaresStrategy(selectionAlgorithm)
        >>> totalDegree = 10
        >>> enumerateFunction = multivariateBasis.getEnumerateFunction()
        >>> basisSize = enumerateFunction.getBasisSizeFromTotalDegree(totalDegree)
        >>> adaptiveStrategy = ot.FixedStrategy(multivariateBasis, basisSize)
        >>> chaosAlgo = ot.FunctionalChaosAlgorithm(
        ...     inputTrain, outputTrain, im.distribution, adaptiveStrategy, projectionStrategy
        ... )
        >>> chaosAlgo.run()
        >>> chaosResult = chaosAlgo.getResult()
        >>> randomVector = ot.FunctionalChaosRandomVector(chaosResult)
        >>> mean = randomVector.getMean()
        >>> print('mean=', mean[0])
        mean= 3.50...
        """
        return _metamodel.FunctionalChaosRandomVector_getMean(self)

    def getCovariance(self):
        r"""
        Accessor to the covariance of the functional chaos expansion.

        Let :math:`\inputDim \in \Nset` be the dimension of the input random vector, 
        let :math:`\outputDim \in \Nset` be the dimension of the output random vector.
        and let :math:`P + 1 \in \Nset` be the size of the basis.
        We consider the following functional chaos expansion:

        .. math::

              \widetilde{\outputRV} = \sum_{k = 0}^P \vect{a}_k \psi_k(\standardRV)

        where
        :math:`\widetilde{\outputRV} \in \Rset^{\outputDim}` is the approximation of the output 
        random variable :math:`\outputRV` by the expansion, 
        :math:`\left\{\vect{a}_k \in \Rset^{\outputDim}\right\}_{k = 0, ..., P}` are the coefficients, 
        :math:`\left\{\psi_k: \Rset^{\inputDim} \rightarrow \Rset\right\}_{k = 0, ..., P}` are the 
        orthonormal functions in the basis, 
        and :math:`\standardRV \in \Rset^{\inputDim}` is the standardized random input vector.
        The previous equation can be equivalently written as follows:

        .. math::

              \widetilde{Y}_i = \sum_{k = 0}^P a_{k, i} \psi_k(\standardRV)

        for :math:`i = 1, ..., \outputDim`
        where :math:`a_{ki} \in \Rset` is the :math:`i`-th component of the
        :math:`k`-th coefficient in the expansion:

        .. math::

              \vect{a}_k = \begin{pmatrix}a_{k, 1} \\ \vdots\\ a_{k, \outputDim} \end{pmatrix}.

        The covariance matrix of the functional chaos expansion is
        the matrix :math:`\matcov \in \Rset^{\outputDim \times \outputDim}`, where each
        component is:

        .. math::

              c_{ij} = \Cov{\widetilde{Y}_i, \widetilde{Y}_j}

        for :math:`i,j = 1, ..., \outputDim`.
        The covariance can be computed using the coefficients of the 
        expansion:

        .. math::

              \Cov{\widetilde{Y}_i, \widetilde{Y}_j} = \sum_{k = 1}^P a_{k, i} a_{k, j}

        for :math:`i,j = 1, ..., \outputDim`.
        This covariance involves all the coefficients, except the first one.
        The diagonal of the covariance matrix is the marginal variance:

        .. math::

              \Var{\widetilde{Y}_i} = \sum_{k = 1}^P a_{k, i}^2

        for :math:`i = 1, ..., \outputDim`.

        Returns
        -------
        covariance : :class:`~openturns.CovarianceMatrix`, dimension :math:`\outputDim \times \outputDim`
            The covariance of the functional chaos expansion.

        Examples
        --------

        >>> from openturns.usecases import ishigami_function
        >>> import openturns as ot
        >>> import math
        >>> im = ishigami_function.IshigamiModel()
        >>> sampleSize = 300
        >>> inputTrain = im.distribution.getSample(sampleSize)
        >>> outputTrain = im.model(inputTrain)
        >>> multivariateBasis = ot.OrthogonalProductPolynomialFactory([im.X1, im.X2, im.X3])
        >>> selectionAlgorithm = ot.LeastSquaresMetaModelSelectionFactory()
        >>> projectionStrategy = ot.LeastSquaresStrategy(selectionAlgorithm)
        >>> totalDegree = 10
        >>> enumerateFunction = multivariateBasis.getEnumerateFunction()
        >>> basisSize = enumerateFunction.getBasisSizeFromTotalDegree(totalDegree)
        >>> adaptiveStrategy = ot.FixedStrategy(multivariateBasis, basisSize)
        >>> chaosAlgo = ot.FunctionalChaosAlgorithm(
        ...     inputTrain, outputTrain, im.distribution, adaptiveStrategy, projectionStrategy
        ... )
        >>> chaosAlgo.run()
        >>> chaosResult = chaosAlgo.getResult()
        >>> randomVector = ot.FunctionalChaosRandomVector(chaosResult)
        >>> covarianceMatrix = randomVector.getCovariance()
        >>> print('covarianceMatrix=', covarianceMatrix[0, 0])
        covarianceMatrix= 13.8...
        >>> outputDimension = outputTrain.getDimension()
        >>> stdDev = ot.Point([math.sqrt(covarianceMatrix[i, i]) for i in range(outputDimension)])
        >>> print('stdDev=', stdDev[0])
        stdDev= 3.72...
        """
        return _metamodel.FunctionalChaosRandomVector_getCovariance(self)

    def getFunctionalChaosResult(self):
        r"""
        Accessor to the functional chaos result.

        Returns
        -------
        functionalChaosResult : :class:`~openturns.FunctionalChaosResult`
            The result from a functional chaos decomposition.
        """
        return _metamodel.FunctionalChaosRandomVector_getFunctionalChaosResult(self)

    def __init__(self, *args):
        _metamodel.FunctionalChaosRandomVector_swiginit(self, _metamodel.new_FunctionalChaosRandomVector(*args))
    __swig_destroy__ = _metamodel.delete_FunctionalChaosRandomVector

# Register FunctionalChaosRandomVector in _metamodel:
_metamodel.FunctionalChaosRandomVector_swigregister(FunctionalChaosRandomVector)
class FunctionalChaosValidation(MetaModelValidation):
    r"""
    Validate a functional chaos metamodel.

    Parameters
    ----------
    result : :class:`~openturns.FunctionalChaosResult`
        A functional chaos result obtained from a polynomial chaos expansion.

    splitter : :class:`~openturns.SplitterImplementation`, optional
        The cross-validation method.
        The default is :class:`~openturns.LeaveOneOutSplitter`.

    See also
    --------
    FunctionalChaosAlgorithm, FunctionalChaosResult

    Notes
    -----
    A `FunctionalChaosValidation` object is used for the validation of a functional chaos expansion.
    It is based on the fast (analytical) leave-one-out and fast K-Fold
    cross-validation methods presented in :any:`cross_validation`.

    Analytical cross-validation can only be performed accurately if some
    conditions are met.

    - This can only be done if the coefficients of the expansion are estimated
      using least squares regression: if the expansion is computed from integration,
      then an exception is produced.
    - This can only be done if the coefficients of the expansion are estimated
      using full expansion, without model selection: if the expansion is computed
      with model selection, then an exception is produced by default.
      This is because model selection leads to supposedly improved coefficients,
      so that the hypotheses required to estimate the mean squared error
      using the cross-validation method are not satisfied anymore.
      As a consequence, using the analytical formula without taking model selection into
      account leads to a biased, overly optimistic, mean squared
      error.
      More precisely, the analytical formula produces a MSE which is lower
      than the true one on average.
      Model selection is involved in the expansion if the
      :class:`~openturns.LeastSquaresMetaModelSelectionFactory`
      or :class:`~openturns.CleaningStrategy` classes are involved.
      If the :class:`~openturns.PenalizedLeastSquaresAlgorithmFactory` class
      is used, then no model selection is involved and the analytical
      cross-validation methods can be used.
      If model selection is involved, the naive methods based on the
      :class:`~openturns.LeaveOneOutSplitter` and :class:`~openturns.KFoldSplitter`
      classes can be used, but this can be much slower than the
      analytical methods implemented here.
      In many cases, however, the order of magnitude of the estimate from the
      analytical formula applied to a sparse model is correct: the estimate of
      the MSE is only slightly lower than the true value.
      In order to enable the calculation of the analytical MSE estimator
      on a sparse model, please set the `FunctionalChaosValidation-ModelSelection`
      key of the :class:`~openturns.ResourceMap` to `True`: use this
      option at your own risks.

    We suggest to use leave-one-out (LOO) cross validation when possible,
    because it produces a more accurate estimate of the error than K-Fold does.
    If K-Fold is required, we suggest to use the largest possible value of :math:`k`.

    The predictions of the leave-one-one or K-Fold surrogate models
    are based on the hold-out method.
    For example, if we use the leave-one-out cross-validation method,
    the :math:`i`-th prediction is the prediction of the linear model
    trained using the hold-out sample where the :math:`i`-th observation
    was removed.
    This produces a sample of residuals which can be retrieved using
    the :meth:`~openturns.FunctionalChaosValidation.getResidualSample` method.
    The :meth:`~openturns.FunctionalChaosValidation.drawValidation` method performs
    similarly.

    If the weights of the observations are not equal, the analytical method
    may not necessarily provide an accurate estimator of the mean squared error (MSE).
    This is because LOO and K-Fold cross-validation do not take the weights
    into account.
    Since the :class:`~openturns.FunctionalChaosResult` object does not know
    if the weights are equal, no exception can be generated.

    If the sample was not produced from Monte Carlo, then the leave-one-out
    cross-validation method may not necessarily provide an accurate estimator
    of the MSE.
    Indeed, one assumption for cross validation using LOO or K-Fold is to have
    independent observations, which is required to state that the LOO sample MSE
    is an estimator of the true MSE.
    For example, using cross-validation on a quasi-Monte Carlo (QMC) experiment may
    not necessarily provide an accurate estimate of the MSE, because the
    internal structure of the QMC is broken by the different splits:
    the elementary volumes are not filled as expected anymore and the
    space-filling properties of the sequence are lost.

    Examples
    --------
    Create a polynomial chaos for the Ishigami function.
    We use the :class:`~openturns.PenalizedLeastSquaresAlgorithmFactory` class
    to specify the method to compute the coefficients.
    We may use the :class:`~openturns.LeastSquaresMetaModelSelectionFactory` class
    in order to create a sparse polynomial chaos expansion, but this
    prevents us from using the fast analytical formulas and get an
    accurate estimator of the MSE.

    >>> import openturns as ot
    >>> from math import pi
    >>> from openturns.usecases import ishigami_function
    >>> im = ishigami_function.IshigamiModel()
    >>> sampleSize = 500 
    >>> inputTrain = im.distribution.getSample(sampleSize)
    >>> outputTrain = im.model(inputTrain)
    >>> multivariateBasis = ot.OrthogonalProductPolynomialFactory([im.X1, im.X2, im.X3])
    >>> selectionAlgorithm = ot.PenalizedLeastSquaresAlgorithmFactory()
    >>> projectionStrategy = ot.LeastSquaresStrategy(inputTrain, outputTrain, selectionAlgorithm)
    >>> totalDegree = 8
    >>> enumerateFunction = multivariateBasis.getEnumerateFunction()
    >>> basisSize = enumerateFunction.getStrataCumulatedCardinal(totalDegree)
    >>> adaptiveStrategy = ot.FixedStrategy(multivariateBasis, basisSize)
    >>> chaosalgo = ot.FunctionalChaosAlgorithm(
    ...     inputTrain, outputTrain, im.distribution, adaptiveStrategy, projectionStrategy
    ... )
    >>> chaosalgo.run()
    >>> result = chaosalgo.getResult()

    Validate the polynomial chaos expansion using leave-one-out cross-validation.

    >>> splitterLOO = ot.LeaveOneOutSplitter(sampleSize)
    >>> validation = ot.FunctionalChaosValidation(result, splitterLOO)
    >>> r2Score = validation.computeR2Score()
    >>> print('R2 = ', r2Score[0])
    R2 =  0.99...

    Validate the polynomial chaos expansion using K-Fold cross-validation
    and set the :math:`k` parameter.

    >>> kParameter = 10
    >>> splitterKF = ot.KFoldSplitter(sampleSize, kParameter)
    >>> validation = ot.FunctionalChaosValidation(result, splitterKF)

    Draw the validation graph.

    >>> graph = validation.drawValidation()
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.FunctionalChaosValidation_getClassName(self)

    def __repr__(self):
        return _metamodel.FunctionalChaosValidation___repr__(self)

    def getFunctionalChaosResult(self):
        r"""
        Result accessor.

        Returns
        -------
        result : :class:`~openturns.FunctionalChaosResult`
            The result provided.
        """
        return _metamodel.FunctionalChaosValidation_getFunctionalChaosResult(self)

    def getSplitter(self):
        r"""
        Get the cross-validation method.

        Returns
        -------
        splitter : :class:`~openturns.SplitterImplementation`
            The cross-validation method.
        """
        return _metamodel.FunctionalChaosValidation_getSplitter(self)

    def __init__(self, *args):
        _metamodel.FunctionalChaosValidation_swiginit(self, _metamodel.new_FunctionalChaosValidation(*args))
    __swig_destroy__ = _metamodel.delete_FunctionalChaosValidation

# Register FunctionalChaosValidation in _metamodel:
_metamodel.FunctionalChaosValidation_swigregister(FunctionalChaosValidation)
class KrigingRandomVector(openturns.randomvector.UsualRandomVector):
    r"""
    KrigingRandom vector, a conditioned Gaussian process.

    Parameters
    ----------
    krigingResult : :class:`~openturns.KrigingResult`
        Structure that contains elements of computation of a kriging algorithm
    points : 1-d or 2-d sequence of float
        Sequence of values defining a :class:`~openturns.Point` or a :class:`~openturns.Sample`.

    Notes
    -----
    KrigingRandomVector helps to create Gaussian random vector, :math:`Y: \Rset^n \mapsto \Rset^d`, with stationary covariance function  :math:`\cC^{stat}: \Rset^n \mapsto \cM_{d \times d}(\Rset)`, conditionally to some observations.

    Let :math:`Y(x=x_1)=y_1,\cdots,Y(x=x_n)=y_n` be the observations of the Gaussian process. We assume the same Gaussian prior as in the :class:`~openturns.KrigingAlgorithm`:

    .. math::

        Y(\vect{x}) = \Tr{\vect{f}(\vect{x})} \vect{\beta} + Z(\vect{x})

    with :math:`\Tr{\vect{f}(\vect{x})} \vect{\beta}` a general linear model, :math:`Z(\vect{x})` a zero-mean Gaussian process with a stationary autocorrelation function :math:`\cC^{stat}`:

    .. math::

        \mathbb{E}[Z(\vect{x}), Z(\vect{\tilde{x}})] = \sigma^2 \cC^{stat}_{\theta}(\vect{x} - \vect{\tilde{x}})

    The objective is to generate realizations of the random vector :math:`Y`, on new points :math:`\vect{\tilde{x}}`, conditionally to these observations. For that purpose, :class:`~openturns.KrigingAlgorithm` build such a prior and stores results in a :class:`~openturns.KrigingResult` structure on a first step. This structure is given as input argument.

    Then, in a second step, both the prior and the covariance on input points :math:`\vect{\tilde{x}}`, conditionally to the previous observations, are evaluated (respectively :math:`Y(\vect{\tilde{x}})` and :math:`\cC^{stat}_{\theta}(\vect{\tilde{x}})`).

    Finally realizations are randomly generated by the Gaussian distribution :math:`\cN ( Y(\vect{\tilde{x}}), \cC^{stat}_{\theta}(\vect{\tilde{x}}) )`

    KrigingRandomVector class inherits from :class:`~openturns.UsualRandomVector`. Thus it stores the previous distribution and returns elements thanks to that distribution (realization, mean, covariance, sample...)

    Examples
    --------
    Create the model :math:`\cM: \Rset \mapsto \Rset` and the samples:

    >>> import openturns as ot
    >>> f = ot.SymbolicFunction(['x'],  ['x * sin(x)'])
    >>> sampleX = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0]]
    >>> sampleY = f(sampleX)

    Create the algorithm:

    >>> basis = ot.Basis([ot.SymbolicFunction(['x'], ['x']), ot.SymbolicFunction(['x'], ['x^2'])])
    >>> covarianceModel = ot.SquaredExponential([1.0])
    >>> covarianceModel.setActiveParameter([])
    >>> algo = ot.KrigingAlgorithm(sampleX, sampleY, covarianceModel, basis)
    >>> algo.run()

    Get the results:

    >>> result = algo.getResult()
    >>> rvector = ot.KrigingRandomVector(result, [[0.0]])

    Get a sample of the random vector:

    >>> sample = rvector.getSample(5)

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.KrigingRandomVector_getClassName(self)

    def __repr__(self):
        return _metamodel.KrigingRandomVector___repr__(self)

    def getRealization(self):
        r"""
        Compute a realization of the conditional Gaussian process (conditional on the learning set).

        The realization predicts the value on the given input *points*.

        Returns
        -------
        realization : :class:`~openturns.Point`
            Sequence of values of the Gaussian process.

        See also
        --------
        getSample
        """
        return _metamodel.KrigingRandomVector_getRealization(self)

    def getSample(self, size):
        r"""
        Compute a sample of realizations of the conditional Gaussian process (conditional on the learning set).

        The realization predicts the value on the given input *points*.

        Returns
        -------
        realizations : :class:`~openturns.Sample`
            2-d float sequence of values of the Gaussian process.

        See also
        --------
        getRealization
        """
        return _metamodel.KrigingRandomVector_getSample(self, size)

    def getKrigingResult(self):
        r"""
        Return the kriging result structure.

        Returns
        -------
        krigResult : :class:`~openturns.KrigingResult`
            The structure containing the elements of a KrigingAlgorithm.
        """
        return _metamodel.KrigingRandomVector_getKrigingResult(self)

    def __init__(self, *args):
        _metamodel.KrigingRandomVector_swiginit(self, _metamodel.new_KrigingRandomVector(*args))
    __swig_destroy__ = _metamodel.delete_KrigingRandomVector

# Register KrigingRandomVector in _metamodel:
_metamodel.KrigingRandomVector_swigregister(KrigingRandomVector)
class GaussianProcessFitterResult(MetaModelResult):
    r"""
    Gaussian process fitter result.

    Refer to :any:`gaussian_process_regression`.

    Parameters
    ----------
    inputSample, outputSample : :class:`~openturns.Sample`
        The samples :math:`(\vect{x}_k)_{1 \leq k \leq \sampleSize} \in \Rset^{\inputDim}` and :math:`(\vect{y}_k)_{1 \leq k \leq \sampleSize}\in \Rset^{\outputDim}`.
    metaModel : :class:`~openturns.Function`
        The metamodel: :math:`\metaModel`, defined in :eq:`metaModelGPF` by the trend function.
    regressionMatrix : :class:`~openturns.Matrix`
        The regression matrix, e.g the evaluation of the basis functions
        upon the input design sample.
    basis :  :class:`~openturns.Basis`
        Functional basis of size :math:`b` : :math:`(\varphi_j: \Rset^{\inputDim} \rightarrow \Rset)` for :math:`j \in [1, b]`.
        Its size should be equal to zero if the trend is not estimated.
    trendCoef : sequence of float
        The trend coefficients vectors :math:`(\vect{\beta}^1, \dots, \vect{\beta}^{\outputDim})`.
    covarianceModel : :class:`~openturns.CovarianceModel`
        The covariance model of the Gaussian process with its optimized parameters.
    optimalLogLikelihood : float
        The maximum log-likelihood corresponding to the model.
    linAlgMethod : int
        The used linear algebra method to fit the model:

        - ot.GaussianProcessFitterResult.LAPACK or 0: using `LAPACK` to fit the model,

        - ot.GaussianProcessFitterResult.HMAT or 1: using `HMAT` to fit the model.

    Notes
    -----
    The structure is usually created by the method :py:meth:`~openturns.GaussianProcessFitter.run` of the class
    :class:`~openturns.GaussianProcessFitter` and obtained with its method
    :py:meth:`~openturns.GaussianProcessFitter.getResult()`.

    Refer to :any:`gaussian_process_regression` (Step 1) to get all the notations and the theoretical aspects. We only detail here the notions related to the class.

    This class creates the metamodel
    :math:`\metaModel: \Rset^{\inputDim} \rightarrow \Rset^{\outputDim}` defined by the estimated trend
    function:

    .. math::
        :label: metaModelGPF

        \metaModel(\vect{x}) = \vect{\mu}(\vect{x}) = \left(
          \begin{array}{l}
            \mu_1(\vect{x}) \\
            \vdots  \\
            \mu_\outputDim(\vect{x})
           \end{array}
         \right)

    with :math:`\mu_\ell(\vect{x}) = \sum_{j=1}^{b} \beta_j^\ell \varphi_j(\vect{x})` and :math:`\varphi_j: \Rset^\inputDim \rightarrow \Rset` the trend functions for :math:`1 \leq j \leq b` and :math:`1 \leq \ell \leq \outputDim`.

    Examples
    --------
    Create the model :math:`\model: \Rset \mapsto \Rset` and the samples:

    >>> import openturns as ot
    >>> g = ot.SymbolicFunction(['x'],  ['x * sin(x)'])
    >>> sampleX = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]]
    >>> sampleY = g(sampleX)

    Create the algorithm:

    >>> basis = ot.Basis([ot.SymbolicFunction(['x'], ['x']), ot.SymbolicFunction(['x'], ['x^2'])])
    >>> covarianceModel = ot.GeneralizedExponential([2.0], 2.0)
    >>> algo = ot.GaussianProcessFitter(sampleX, sampleY, covarianceModel, basis)
    >>> algo.run()

    Get the result:

    >>> result = algo.getResult()

    Get the metamodel :math:`\metaModel(\vect{x}) = \vect{\mu}(\vect{x})`:

    >>> metaModel = result.getMetaModel()
    >>> graph = metaModel.draw(0.0, 7.0)
    >>> cloud = ot.Cloud(sampleX, sampleY)
    >>> cloud.setPointStyle('fcircle')
    >>> graph = ot.Graph()
    >>> graph.add(cloud)
    >>> graph.add(g.draw(0.0, 7.0))

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.GaussianProcessFitterResult_getClassName(self)
    LAPACK = _metamodel.GaussianProcessFitterResult_LAPACK
    HMAT = _metamodel.GaussianProcessFitterResult_HMAT

    def __repr__(self):
        return _metamodel.GaussianProcessFitterResult___repr__(self)

    def __str__(self, *args):
        return _metamodel.GaussianProcessFitterResult___str__(self, *args)

    def getBasis(self):
        r"""
        Accessor to the basis.

        Returns
        -------
        basis : :class:`~openturns.Basis`
            Functional basis to estimate the trend: :math:`(\varphi_j)_{1 \leq j \leq b}: \Rset^\inputDim \rightarrow \Rset`.

        Notes
        -----
        If the trend is not estimated, the basis is empty. The same basis is used for each marginal output.
        """
        return _metamodel.GaussianProcessFitterResult_getBasis(self)

    def getTrendCoefficients(self):
        r"""
        Accessor to the trend coefficients.

        Returns
        -------
        trendCoef : :class:`~openturns.Point`
            The trend coefficients vectors :math:`(\vect{\beta}^1, \dots, \vect{\beta}^{\outputDim})` as a :class:`~openturns.Point`.

        Notes
        -----
        As the same basis is used for each marginal output, each :math:`\vect{\beta}^\ell` vector is of dimension
        :math:`b`, the size of the functional basis.
        """
        return _metamodel.GaussianProcessFitterResult_getTrendCoefficients(self)

    def getCovarianceModel(self):
        r"""
        Accessor to the covariance model.

        Returns
        -------
        covModel : :class:`~openturns.CovarianceModel`
            The covariance model of the Gaussian process :math:`\vect{W}` with its optimized parameters.

        """
        return _metamodel.GaussianProcessFitterResult_getCovarianceModel(self)

    def getOptimalLogLikelihood(self):
        r"""
        Accessor to the optimal log-likelihood of the model.

        Returns
        -------
        optimalLogLikelihood : float
            The value of the log-likelihood corresponding to the model.

        """
        return _metamodel.GaussianProcessFitterResult_getOptimalLogLikelihood(self)

    def getLinearAlgebraMethod(self):
        r"""
        Accessor to the linear algebra method used to fit.

        Returns
        -------
        linAlgMethod : int
            The used linear algebra method to fit the model:

            - ot.GaussianProcessFitterResult.LAPACK or 0: using `LAPACK` to fit the model,

            - ot.GaussianProcessFitterResult.HMAT or 1: using `HMAT` to fit the model.

        """
        return _metamodel.GaussianProcessFitterResult_getLinearAlgebraMethod(self)

    def getRegressionMatrix(self):
        r"""
        Accessor to the regression matrix.

        Returns
        -------
        process : :class:`~openturns.Matrix`
            Returns the regression matrix.

        Notes
        -----
        The regression matrix, e.g the evaluation of the basis functions
        upon the input design sample. It contains :math:`\sampleSize` lines and as many column as
        the size of the functional basis. The column :math:`k` is defined as:

        .. math::

            \left(\varphi_k(\vect{x}_1), \dots,\varphi_k(\vect{x}_\sampleSize) \right).


        """
        return _metamodel.GaussianProcessFitterResult_getRegressionMatrix(self)

    def getCenteredProcess(self):
        r"""
        Accessor to the Gaussian process.

        Returns
        -------
        process : :class:`~openturns.GaussianProcess`
            The Gaussian process :math:`\vect{W}` with its the optimized parameters.

        """
        return _metamodel.GaussianProcessFitterResult_getCenteredProcess(self)

    def setNoise(self, noise):
        r"""
        Output sample noise variance accessor.

        Parameters
        ----------
        noise : sequence of :class:`~openturns.CovarianceMatrix`
            The noise covariance :math:`\mat{\Sigma_{\epsilon}}`.

        """
        return _metamodel.GaussianProcessFitterResult_setNoise(self, noise)

    def getNoise(self):
        r"""
        Output sample noise variance accessor.

        Returns
        -------
        noise : sequence of :class:`~openturns.CovarianceMatrix`
            The noise covariance for each output: :math:`\mat{\Sigma}_i^{noise} \in \cM_{\outputDim \times \outputDim}(\Rset)`.

        Notes
        -----
        The noise takes into account the fact that the output values of the function are not known precisely. This noise is modeled by normal distribution with zero mean and a covariance matrix :math:`\mat{\Sigma}_i^{noise}` as defined in :eq:`noise`.

        Refer to :any:`gaussian_process_regression` to understand how it acts on the likelihood of the Gaussian process.

        """
        return _metamodel.GaussianProcessFitterResult_getNoise(self)

    def getCholeskyFactor(self):
        r"""
        Accessor to the Cholesky factor of the covariance matrix.

        Returns
        -------
        L : :class:`~openturns.TriangularMatrix`
            Cholesky factor :math:`\mat{L}_{\vect{p}^*}` of the covariance matrix,
            which can be written :math:`\mat{L}_{\vect{p}^*} \mat{L}_{\vect{p}^*}^T`.
        """
        return _metamodel.GaussianProcessFitterResult_getCholeskyFactor(self)

    def getHMatCholeskyFactor(self):
        r"""
        Accessor to the Cholesky factor of the covariance matrix.

        Only available with HMat algebra.

        Returns
        -------
        L : :class:`~openturns.HMatrix`
            Cholesky factor :math:`\mat{L}_{\vect{p}^*}` of the covariance matrix,
            which can be written :math:`\mat{L}_{\vect{p}^*} \mat{L}_{\vect{p}^*}^T`.
        """
        return _metamodel.GaussianProcessFitterResult_getHMatCholeskyFactor(self)

    def setCholeskyFactor(self, covarianceCholeskyFactor, covarianceHMatrix):
        return _metamodel.GaussianProcessFitterResult_setCholeskyFactor(self, covarianceCholeskyFactor, covarianceHMatrix)

    def setStandardizedOutput(self, rho):
        r"""
        Accessor to the standardized output.

        Parameters
        ----------
        rho : sequence of float
            Standardized output vector.

        Notes
        -----
        The standardized output vector is defined as :math:`\mat{L}_{\vect{p}^*}^{-1}(\vect{y} - \vect{m}_{\vect{\beta}^*(\vect{p}^*)})`.
        """
        return _metamodel.GaussianProcessFitterResult_setStandardizedOutput(self, rho)

    def getStandardizedOutput(self):
        r"""
        Accessor to the standardized output.

        Returns
        -------
        rho : :class:`~openturns.Point`
            Standardized output vector.

        Notes
        -----
        The standardized output vector is defined as :math:`\mat{L}_{\vect{p}^*}^{-1}(\vect{y} - \vect{m}_{\vect{\beta}^*(\vect{p}^*)})`.
        """
        return _metamodel.GaussianProcessFitterResult_getStandardizedOutput(self)

    def __init__(self, *args):
        _metamodel.GaussianProcessFitterResult_swiginit(self, _metamodel.new_GaussianProcessFitterResult(*args))
    __swig_destroy__ = _metamodel.delete_GaussianProcessFitterResult

# Register GaussianProcessFitterResult in _metamodel:
_metamodel.GaussianProcessFitterResult_swigregister(GaussianProcessFitterResult)
class GaussianProcessFitter(MetaModelAlgorithm):
    r"""
    Fit gaussian process models

    Refer to :any:`gaussian_process_regression`.

    Parameters
    ----------
    inputSample, outputSample : :class:`~openturns.Sample` or 2d-array
        The samples :math:`(\vect{x}_k)_{1 \leq k \leq \sampleSize} \in \Rset^\inputDim` and :math:`(\vect{y}_k)_{1 \leq
        k \leq \sampleSize}\in \Rset^{\outputDim}`.

    covarianceModel : :class:`~openturns.CovarianceModel`
        Covariance model of the Gaussian process. See notes for the details.

    basis : :class:`~openturns.Basis`
        Functional basis to estimate the trend: :math:`(\varphi_j)_{1 \leq j \leq b}: \Rset^\inputDim \rightarrow \Rset`.

        The same basis is used for each marginal output.

        Default value is `Basis(0)`, i.e. no trend to estimate.

    Notes
    -----

    Refer to :any:`gaussian_process_regression` (Step 1) to get all the notations and the theoretical aspects.
    We only detail here the notions related to the class.

    We suppose we have a sample :math:`(\vect{x}_k, \vect{y}_k)_{1 \leq k \leq \sampleSize}`
    where :math:`\vect{y}_k = \model(\vect{x}_k)` for all :math:`k`, with :math:`\model:\Rset^\inputDim \mapsto
    \Rset^{\outputDim}` a given function.

    The class creates the Gaussian process  :math:`\vect{Y}(\omega, \vect{x})` such that the sample
    :math:`(\vect{y}_k)_{1 \leq k \leq \sampleSize}` is considered as its restriction  on
    :math:`(\vect{x}_k)_{1 \leq k \leq \sampleSize}`. It is defined by:

    .. math::

        \vect{Y}(\omega, \vect{x}) = \vect{\mu}(\vect{x}) + \vect{W}(\omega, \vect{x})

    where :math:`\vect{\mu} = (\mu_1, \dots, \mu_\outputDim)` with :math:`\mu_\ell(\vect{x}) = \sum_{j=1}^{b}
    \beta_j^\ell \varphi_j(\vect{x})` and :math:`\varphi_j: \Rset^\inputDim \rightarrow \Rset` the trend function
    basis for :math:`1 \leq j \leq b` and :math:`1 \leq \ell \leq \outputDim`.

    Furthermore, :math:`\vect{W}` is a Gaussian process of dimension :math:`\outputDim` with zero mean and a specified
    covariance model.

    The *GaussianProcessFitter* class estimates the coefficients :math:`\beta_j^\ell` and :math:`\vect{p}` 
    where :math:`\vect{p}` is the vector of the parameters of the covariance model  that has been declared as
    *active*: see
    :class:`openturns.CovarianceModel` to get details on the activation of the estimation of the other
    parameters.

    The estimation is done by maximizing the :any:`reduced log-likelihood of the model<logLikelihoodGPmodel>`.

    The default optimizer is :class:`~openturns.Cobyla` and can be changed thanks to the
    :meth:`setOptimizationAlgorithm` method.
    User could also change the default optimization solver by setting the entry 
    `GaussianProcessFitter-DefaultOptimizationAlgorithm` of :class:`~openturns.ResourceMap` to one of the
    :class:`~openturns.NLopt`
    solver names.

    It is also possible to proceed as follows:

    * ask for the reduced log-likelihood function thanks to the :meth:`getReducedLogLikelihoodFunction` method,
    * optimize it with respect to the parameters :math:`\vect{\theta}` and :math:`\vect{\sigma}` using any optimization
      algorithms
      (that can take into account some additional constraints if needed),
    * set the optimal parameter value into the covariance model used in the *GaussianProcessFitter*,
    * tell the algorithm not to optimize the parameter using the :meth:`setOptimizeParameters` method.

    A centered Gaussian noise :math:`\mat{\Sigma}_i^{\text{noise}} \in \cM_{\outputDim \times \outputDim}(\Rset)`
    can be taken into account for each output value with :func:`setNoise()`:

    .. math::
        :label: noise

        \vect{Y}_i = \vect{y}_i^{\text{true}} + \vect{\varepsilon}, \quad
        \vect{\varepsilon} \sim \cN \left(\vect{0}, \mat{\Sigma}_i^{\text{noise}}\right)


    where :math:`\vect{y}_i^{\text{true}}` is the true (and unknown) value of the model at :math:`\vect{x}_i`. Refer to
    :doc:`/auto_surrogate_modeling/gaussian_process_regression/plot_gpr_noise` to get an example.

    The behaviour of the reduction is controlled by the following keys in :class:`~openturns.ResourceMap`:

    - The boolean entry *GaussianProcessFitter-UseAnalyticalAmplitudeEstimate* to use the reduction associated to
      :math:`\sigma`.
      It has no effect if :math:`\outputDim > 1` or if :math:`\outputDim=1` and :math:`\sigma` is not part of :math:`\vect{p}`,
    - The boolean entry *GaussianProcessFitter-UnbiasedVariance* allows one to use the *unbiased* estimate of
      :math:`\sigma` where :math:`\dfrac{1}{\sampleSize}` is replaced by :math:`\dfrac{1}{\sampleSize-\outputDim}`
      in the optimality condition for :math:`\sigma`.
    - Like other machine learning techniques, heteregeneous data (i.e., data defined with different orders of magnitude)
      can have an impact on the training process of Gaussian Process Fitter.
      The boolean entry *GaussianProcessFitter-OptimizationNormalization* decides whether
      to internally scale the hyperparameters during the optimization using a min-max transformation:
      :math:`\theta\prime = \frac{\theta - \theta_{min}}{\theta_{max} - \theta_{min}}`
      The input data itself is not directly normalized to avoid introducing an additional transformation to the metamodel.
      see also :doc:`/auto_surrogate_modeling/gaussian_process_regression/plot_gpr_normalization`

    With huge samples, the `hierarchical matrix <http://en.wikipedia.org/wiki/Hierarchical_matrix>`_
    implementation could be used if `hmat-oss` support has been enabled.

    This implementation, which is based on a compressed representation of an approximated covariance matrix
    (and its Cholesky factor), has a better complexity both in terms of memory requirements
    and floating point operations. To use it, the entry `GaussianProcessFitter-LinearAlgebra` of the
    :class:`openturns.ResourceMap` class should be
    instancied to `HMAT`. Default value of the key is `LAPACK`.

    Examples
    --------
    Create the model :math:`\model: \Rset \mapsto \Rset` and the samples:

    >>> import openturns as ot
    >>> g = ot.SymbolicFunction(['x'], ['x + x * sin(x)'])
    >>> inputSample = ot.Sample([[1.0], [3.0], [5.0], [6.0], [7.0], [8.0]])
    >>> outputSample = g(inputSample)

    Create the algorithm:

    >>> g1 = ot.SymbolicFunction(['x'], ['sin(x)'])
    >>> g2 = ot.SymbolicFunction(['x'], ['x'])
    >>> g3 = ot.SymbolicFunction(['x'], ['cos(x)'])
    >>> basis = ot.Basis([g1, g2, g3])
    >>> covarianceModel = ot.SquaredExponential([1.0])
    >>> covarianceModel.setActiveParameter([])
    >>> algo = ot.GaussianProcessFitter(inputSample, outputSample, covarianceModel, basis)
    >>> algo.run()

    Get the resulting  metamodel which is the trend function of the Gaussian process:

    >>> result = algo.getResult()
    >>> metamodel = result.getMetaModel()

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.GaussianProcessFitter_getClassName(self)

    def __repr__(self):
        return _metamodel.GaussianProcessFitter___repr__(self)

    def run(self):
        r"""
        Compute the response surface.

        Notes
        -----
        It computes the response surface and creates a
        :class:`~openturns.GaussianProcessFitterResult` structure containing all the results.
        """
        return _metamodel.GaussianProcessFitter_run(self)

    def getResult(self):
        r"""
        Get the results of the metamodel computation.

        Returns
        -------
        result : :class:`~openturns.GaussianProcessFitterResult`
            Structure containing all the results obtained after computation
            and created by the method :py:meth:`run`.

        """
        return _metamodel.GaussianProcessFitter_getResult(self)

    def getReducedLogLikelihoodFunction(self):
        r"""
        Accessor to the log-likelihood function that writes as argument of the covariance's model parameters.

        Returns
        -------
        logLikelihood : :class:`~openturns.Function`
            The log-likelihood function degined in :eq:`logLikelihoodGP` as a function of the active parameters of the covariance model.

        Notes
        -----
        The log-likelihood function may be useful for some postprocessing: maximization using external optimizers for example.


        Examples
        --------
        Create the model :math:`\model: \Rset \mapsto \Rset` and the samples:

        >>> import openturns as ot
        >>> g = ot.SymbolicFunction(['x0'], ['x0 * sin(x0)'])
        >>> inputSample = ot.Sample([[1.0], [3.0], [5.0], [6.0], [7.0], [8.0]])
        >>> outputSample = g(inputSample)

        Create the algorithm:

        >>> basis = ot.ConstantBasisFactory().build()
        >>> covarianceModel = ot.SquaredExponential(1)
        >>> algo = ot.GaussianProcessFitter(inputSample, outputSample, covarianceModel, basis)
        >>> algo.run()

        Get the log-likelihood function:

        >>> likelihoodFunction = algo.getReducedLogLikelihoodFunction()

        """
        return _metamodel.GaussianProcessFitter_getReducedLogLikelihoodFunction(self)

    def getOptimizationAlgorithm(self):
        r"""
        Accessor to solver used to optimize the covariance model parameters.

        Returns
        -------
        algorithm : :class:`~openturns.OptimizationAlgorithm`
            Solver used to optimize the covariance model parameters.
            Default optimizer is :class:`~openturns.Cobyla`
        """
        return _metamodel.GaussianProcessFitter_getOptimizationAlgorithm(self)

    def setOptimizationAlgorithm(self, solver):
        r"""
        Accessor to the solver used to optimize the covariance model parameters.

        Parameters
        ----------
        algorithm : :class:`~openturns.OptimizationAlgorithm`
            Solver used to optimize the covariance model parameters.
        """
        return _metamodel.GaussianProcessFitter_setOptimizationAlgorithm(self, solver)

    def getOptimizeParameters(self):
        r"""
        Accessor to the covariance model parameters optimization flag.

        Returns
        -------
        optimizeParameters : bool
            Whether to optimize the covariance model parameters.
        """
        return _metamodel.GaussianProcessFitter_getOptimizeParameters(self)

    def setOptimizeParameters(self, optimizeParameters):
        r"""
        Accessor to the covariance model parameters optimization flag.

        Parameters
        ----------
        optimizeParameters : bool
            Whether to optimize the covariance model parameters.
        """
        return _metamodel.GaussianProcessFitter_setOptimizeParameters(self, optimizeParameters)

    def setOptimizationBounds(self, optimizationBounds):
        r"""
        Optimization bounds accessor.

        Parameters
        ----------
        bounds : :class:`~openturns.Interval`
            Bounds for covariance model parameter optimization.

        Notes
        -----
        Parameters involved by this method are:

         - Scale parameters,
         - Amplitude parameters if output dimension is greater than one or
           analytical sigma disabled,
         - Additional parameters.

        Lower & upper bounds are defined in resource map.
        Default lower upper bounds value for all parameters is
        :math:`10^{-2}` and defined thanks to the
        `GaussianProcessFitter-DefaultOptimizationLowerBound`
        resource map key.

        For scale parameters, default bounds are set as a factor of the difference between the max and min values of `X`
        for each coordinate of the input sample `X` thanks to the `GaussianProcessFitter-OptimizationLowerBoundScaleFactor`
        and `GaussianProcessFitter-OptimizationUpperBoundScaleFactor` :class:`~openturns.ResourceMap` entries.

        Finally for other parameters (amplitude,...), default upper bound is set
        to :math:`100` (corresponding resource map key is
        `GaussianProcessFitter-DefaultOptimizationUpperBound`)

        """
        return _metamodel.GaussianProcessFitter_setOptimizationBounds(self, optimizationBounds)

    def getOptimizationBounds(self):
        r"""
        Optimization bounds accessor.

        Returns
        -------
        bounds : :class:`~openturns.Interval`
            Bounds for covariance model parameter optimization.
        """
        return _metamodel.GaussianProcessFitter_getOptimizationBounds(self)

    def getKeepCholeskyFactor(self):
        r"""
        Keep Cholesky factor accessor.

        Returns
        -------
        keepCholesky : bool
            Tells whether we keep or not the final Cholesky factor.
        """
        return _metamodel.GaussianProcessFitter_getKeepCholeskyFactor(self)

    def setKeepCholeskyFactor(self, keepCholeskyFactor):
        r"""
        Keep Cholesky factor setter.

        Parameters
        ----------
        keepCholesky : bool
            Tells whether we keep or not the final Cholesky factor.
        """
        return _metamodel.GaussianProcessFitter_setKeepCholeskyFactor(self, keepCholeskyFactor)

    def setMethod(self, method):
        r"""
         Accessor to the linear algebra method.

        Parameters
        ----------
        linAlgMethod : int
            The used linear algebra method to fit the model:

            - ot.GaussianProcessFitterResult.LAPACK or 0: using `LAPACK` to fit the model,

            - ot.GaussianProcessFitterResult.HMAT or 1: using `HMAT` to fit the model.
        """
        return _metamodel.GaussianProcessFitter_setMethod(self, method)

    def getMethod(self):
        r"""
         Accessor to the linear algebra method.

        Returns
        -------
        linAlgMethod : int
            The used linear algebra method to fit the model:

            - ot.GaussianProcessFitterResult.LAPACK or 0: using `LAPACK` to fit the model,

            - ot.GaussianProcessFitterResult.HMAT or 1: using `HMAT` to fit the model.
        """
        return _metamodel.GaussianProcessFitter_getMethod(self)

    def setNoise(self, *args):
        r"""
        Output sample noise variance accessor.

        Parameters
        ----------
        noise : sequence of :class:`~openturns.CovarianceMatrix` or sequence of float
            The noise covariance for each output: :math:`\mat{\Sigma}_i^{noise} \in \cM_{\outputDim \times \outputDim}(\Rset)`.

        Notes
        -----
        The noise takes into account the fact that the output values of the function are not known precisely. This noise is
        modeled by normal distribution with zero mean and a covariance matrix :math:`\mat{\Sigma}_i^{noise}` as defined in
        :any:`gaussian_process_regression`.

        If the output dimension :math:`\outputDim = 1`, each matrix :math:`\mat{\Sigma}_i^{noise}` is reduced to a scalar 
        and the noise can be specified with a sequence of float.

        Refer to :any:`gaussian_process_regression` to understand how it acts on the likelihood of the Gaussian process.

        """
        return _metamodel.GaussianProcessFitter_setNoise(self, *args)

    def getNoise(self):
        r"""
        Output sample noise variance accessor.

        Returns
        -------
        noise : sequence of :class:`~openturns.CovarianceMatrix`
            The noise covariance for each output: :math:`\mat{\Sigma}_i^{noise} \in \cM_{\outputDim \times \outputDim}(\Rset)`.

        Notes
        -----
        The noise takes into account the fact that the output values of the function are not known precisely. This noise is
        modeled by normal distribution with zero mean and a covariance matrix :math:`\mat{\Sigma}_i^{noise}` as defined in
        :any:`gaussian_process_regression`.

        Refer to :any:`gaussian_process_regression` to understand how it acts on the likelihood of the Gaussian process.

        """
        return _metamodel.GaussianProcessFitter_getNoise(self)

    def __init__(self, *args):
        _metamodel.GaussianProcessFitter_swiginit(self, _metamodel.new_GaussianProcessFitter(*args))
    __swig_destroy__ = _metamodel.delete_GaussianProcessFitter

# Register GaussianProcessFitter in _metamodel:
_metamodel.GaussianProcessFitter_swigregister(GaussianProcessFitter)
class GaussianProcessRegressionResult(MetaModelResult):
    r"""
    Gaussian process regression (aka kriging) result.

    Refer to :any:`gaussian_process_regression`.

    Parameters
    ----------
    gpfitResult : :class:`~openturns.GaussianProcessFitterResult`
        Structure result of a gaussian process fitter.
    covarianceCoefficients : 2-d sequence of float
        The :math:`\vect{\gamma}` defined in :eq:`gammaDefinition`.

    Notes
    -----
    The structure is usually created by the method :py:meth:`~openturns.GaussianProcessRegression.run`, and obtained thanks to the `getResult()` method.

    Refer to the documentation of :class:`~openturns.GaussianProcessRegression` to get details on
    the notations.

    Examples
    --------
    Create the model :math:`\model: \Rset \mapsto \Rset` and the samples:

    >>> import openturns as ot
    >>> g = ot.SymbolicFunction(['x'],  ['x * sin(x)'])
    >>> sampleX = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]]
    >>> sampleY = g(sampleX)

    Create the algorithm:

    >>> basis = ot.Basis([ot.SymbolicFunction(['x'], ['x']), ot.SymbolicFunction(['x'], ['x^2'])])
    >>> covarianceModel = ot.GeneralizedExponential([2.0], 2.0)
    >>> fit_algo = ot.GaussianProcessFitter(sampleX, sampleY, covarianceModel, basis)
    >>> fit_algo.run()

    Create the interpolating Gaussian process approximation:

    >>> algo = ot.GaussianProcessRegression(fit_algo.getResult())
    >>> algo.run()

    Get the resulting interpolating metamodel :math:`\metaModel`:

    >>> result = algo.getResult()
    >>> metaModel = result.getMetaModel()

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.GaussianProcessRegressionResult_getClassName(self)

    def __repr__(self):
        return _metamodel.GaussianProcessRegressionResult___repr__(self)

    def __str__(self, *args):
        return _metamodel.GaussianProcessRegressionResult___str__(self, *args)

    def getBasis(self):
        r"""
        Accessor to the collection of basis.

        Returns
        -------
        basis : :class:`~openturns.Basis`
            Functional basis to estimate the trend: :math:`(\varphi_j)_{1 \leq j \leq b}: \Rset^\inputDim
            \rightarrow \Rset`.

        Notes
        -----
        If the trend is not estimated, the basis is empty. The same basis is used for each marginal output.
        """
        return _metamodel.GaussianProcessRegressionResult_getBasis(self)

    def getTrendCoefficients(self):
        r"""
        Accessor to the trend coefficients.

        Returns
        -------
        trendCoef : :class:`~openturns.Point`
            The trend coefficients vectors :math:`(\vect{\beta}^1, \dots, \vect{\beta}^{\outputDim})`

        Notes
        -----
        As the same basis is used for each marginal output, each :math:`\vect{\beta}^\ell` vector is of dimension
        :math:`b`, the size of the functional basis.

        """
        return _metamodel.GaussianProcessRegressionResult_getTrendCoefficients(self)

    def getCovarianceModel(self):
        r"""
        Accessor to the covariance model.

        Returns
        -------
        covModel : :class:`~openturns.CovarianceModel`
            The covariance model of the Gaussian process :math:`\vect{W}`.

        """
        return _metamodel.GaussianProcessRegressionResult_getCovarianceModel(self)

    def getOptimalLogLikelihood(self):
        r"""
        Accessor to the optimal log-likelihood of the model.

        Returns
        -------
        optimalLogLikelihood : float
            The value of the log-likelihood corresponding to the model.

        """
        return _metamodel.GaussianProcessRegressionResult_getOptimalLogLikelihood(self)

    def getLinearAlgebraMethod(self):
        r"""
        Accessor to the linear algebra method used to fit.

        Returns
        -------
        linAlgMethod : int
            The used linear algebra method to fit the model:

            - ot.GaussianProcessFitterResult.LAPACK or 0: using `LAPACK` to fit the model,

            - ot.GaussianProcessFitterResult.HMAT or 1: using `HMAT` to fit the model.

        """
        return _metamodel.GaussianProcessRegressionResult_getLinearAlgebraMethod(self)

    def getRegressionMatrix(self):
        r"""
        Accessor to the regression matrix.

        Returns
        -------
        process : :class:`~openturns.Matrix`
            Returns the regression matrix.

        Notes
        -----
        The regression matrix, e.g the evaluation of the basis function
        upon the input design sample. It contains :math:`\sampleSize \times \outputDim` lines and as many column as
        the size of the functional basis. The column :math:`k` is defined as:

        .. math::

            \left(\varphi_k(\vect{x}_1), \dots,\varphi_k(\vect{x}_\sampleSize) \right).


        """
        return _metamodel.GaussianProcessRegressionResult_getRegressionMatrix(self)

    def getCenteredProcess(self):
        r"""
        Accessor to the Gaussian process.

        Returns
        -------
        process : :class:`~openturns.GaussianProcess`
            The Gaussian process :math:`\vect{W}` with its the optimized parameters.

        """
        return _metamodel.GaussianProcessRegressionResult_getCenteredProcess(self)

    def getCovarianceCoefficients(self):
        r"""
        Accessor to the covariance coefficients.

        Returns
        -------
        covCoeff : :class:`~openturns.Sample`
            The :math:`\vect{\gamma}` defined in :eq:`gammaDefinition`.

        """
        return _metamodel.GaussianProcessRegressionResult_getCovarianceCoefficients(self)

    def getGaussianProcessFitterResult(self):
        r"""
        Accessor to the fitting result.

        Returns
        -------
        result : :class:`~openturns.GaussianProcessFitterResult`
            The fitting result.

        """
        return _metamodel.GaussianProcessRegressionResult_getGaussianProcessFitterResult(self)

    def __init__(self, *args):
        _metamodel.GaussianProcessRegressionResult_swiginit(self, _metamodel.new_GaussianProcessRegressionResult(*args))
    __swig_destroy__ = _metamodel.delete_GaussianProcessRegressionResult

# Register GaussianProcessRegressionResult in _metamodel:
_metamodel.GaussianProcessRegressionResult_swigregister(GaussianProcessRegressionResult)
class GaussianProcessRegression(MetaModelAlgorithm):
    r"""
    Gaussian process regression algorithm.

    Available constructors:
        GaussianProcessRegression(*gprFitterResult*)

        GaussianProcessRegression(*inputSample, outputSample, covarianceModel, trendFunction*)

    Parameters
    ----------
    gprFitterResult : :class:`~openturns.GaussianProcessFitterResult`
        The result class built by :class:`~openturns.GaussianProcessFitter`.
    inputSample, outputSample : 2-d sequence of float
        The samples :math:`(\vect{x}_k)_{1 \leq k \leq \sampleSize} \in \Rset^{\inputDim}` and :math:`(\vect{y}_k)_{1 \leq k \leq \sampleSize} \in \Rset^{\outputDim}` upon which the meta-model is built.
    covarianceModel : :class:`~openturns.CovarianceModel`
        The covariance model used for the underlying Gaussian process approximation.
    trendFunction : :class:`~openturns.Function`
        The trend function.

    Notes
    -----

    Refer to :any:`gaussian_process_regression` (step 2) to get all the notations and the theoretical aspects. We only detail here the notions related to the class.

    We suppose we have a sample :math:`(\vect{x}_k, \vect{y}_k)_{1 \leq k \leq \sampleSize}` where :math:`\vect{y}_k = \model(\vect{x}_k)` for all *k*, with :math:`\model:\Rset^{\inputDim} \mapsto \Rset^{\outputDim}` the model.

    The underlying Gaussian process approximation :math:`\vect{Y}` can be fulfilled with two different ways: 

    * Within the first constructor: we suppose that the Gaussian process approximation has already been
      calibrated using the class :class:`~openturns.GaussianProcessFitter`;
    * Within the second constructor: all the elements defining the Gaussian process approximation are specified
      separately: the data set, the covariance model and the trend function.

    The objective of the *GaussianProcessRegression* is to condition the Gaussian process approximation :math:`\vect{Y}` to the data set: thus, we make the Gaussian process approximation become interpolating over the dataset.

    In all cases, no estimation of the underlying Gaussian process approximation :math:`\vect{Y}` is performed. Refer to :class:`~openturns.GaussianProcessFitter` to get more details on the notation. The Gaussian process :math:`\vect{Y}` is defined by:

    .. math::

        \vect{Y}(\omega, \vect{x}) = \vect{\mu}(\vect{x}) + \vect{W}(\omega, \vect{x})

    where :math:`\vect{\mu} : \Rset^\inputDim \rightarrow \Rset^{\outputDim}` is the trend function and :math:`\vect{W}` is a Gaussian process of dimension :math:`\outputDim` with zero mean and a specified covariance function.

    The Gaussian Process Regression denoted by :math:`\vect{Z}` is the Gaussian process :math:`\vect{Y}` conditioned to the data
    set:

    .. math::

        \vect{Z}(\omega, \vect{x}) = \vect{Y}(\omega, \vect{x})\, | \,  \cC

    where :math:`\cC` is the condition :math:`\vect{Y}(\omega, \vect{x}_k) = \vect{y}_k` for
    :math:`1 \leq k \leq \sampleSize`.

    Then, :math:`\vect{Z}` is a Gaussian process, which mean and covariance function are defined in :eq:`expectationGPR` and
    :eq:`covarianceGPR_point`.

    The Gaussian Process Regression metamodel :math:`\metaModel` is defined by the mean of :math:`\vect{Z}`. Its expression is
    detailed in :eq:`GPRmetamodel`.

    In order to get services related to the conditional covariance, use the class :class:`~openturns.GaussianProcessConditionalCovariance`.

    Examples
    --------
    Create the model :math:`\model: \Rset \mapsto \Rset` and the samples:

    >>> import openturns as ot
    >>> g = ot.SymbolicFunction(['x'],  ['x * sin(x)'])
    >>> sampleX = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0]]
    >>> sampleY = g(sampleX)

    Create the algorithm:

    >>> basis = ot.Basis([ot.SymbolicFunction(['x'], ['x']), ot.SymbolicFunction(['x'], ['x^2'])])
    >>> covarianceModel = ot.SquaredExponential([1.0])
    >>> covarianceModel.setActiveParameter([])
    >>> fit_algo = ot.GaussianProcessFitter(sampleX, sampleY, covarianceModel, basis)
    >>> fit_algo.run()

    Get the resulting interpolating metamodel :math:`\metaModel`:

    >>> fit_result = fit_algo.getResult()
    >>> algo = ot.GaussianProcessRegression(fit_result)
    >>> algo.run()
    >>> result = algo.getResult()
    >>> metamodel = result.getMetaModel()

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.GaussianProcessRegression_getClassName(self)

    def __repr__(self):
        return _metamodel.GaussianProcessRegression___repr__(self)

    def run(self):
        r"""
        Compute the response surface.

        Notes
        -----
        It computes the Gaussian Process interpolating approximation and creates a
        :class:`~openturns.GaussianProcessRegressionResult` structure containing all the results.
        """
        return _metamodel.GaussianProcessRegression_run(self)

    def getResult(self):
        r"""
        Get the results of the metamodel computation.

        Returns
        -------
        result : :class:`~openturns.GaussianProcessRegressionResult`
            Structure containing all the results obtained, created by the method :py:meth:`run`.

        """
        return _metamodel.GaussianProcessRegression_getResult(self)

    def __init__(self, *args):
        _metamodel.GaussianProcessRegression_swiginit(self, _metamodel.new_GaussianProcessRegression(*args))
    __swig_destroy__ = _metamodel.delete_GaussianProcessRegression

# Register GaussianProcessRegression in _metamodel:
_metamodel.GaussianProcessRegression_swigregister(GaussianProcessRegression)
class GaussianProcessConditionalCovariance(openturns.common.PersistentObject):
    r"""
    Conditional covariance post processing of a Gaussian Process Regression result.

    Parameters
    ----------
    gprResult :  :class:`~openturns.GaussianProcessRegressionResult`
        The result class built by :class:`~openturns.GaussianProcessRegression`.

    Notes
    -----
    Refer to :any:`gaussian_process_regression` (step 3) to get all the notations and the theoretical aspects. We only detail here the notions related to the class.

    We suppose we have a sample :math:`(\vect{x}_k, \vect{y}_k)_{1 \leq k \leq \sampleSize}` where :math:`\vect{y}_k = \model(\vect{x}_k)` for all *k*, with :math:`\model:\Rset^{\inputDim} \mapsto \Rset^{\outputDim}` the model. The  Gaussian process approximation :math:`\vect{Y}` is defined by:

    .. math::

        \vect{Y}(\omega, \vect{x}) = \vect{\mu}(\vect{x}) + \vect{W}(\omega, \vect{x})

    where :math:`\vect{\mu} : \Rset^\inputDim \rightarrow \Rset^outputDim` is the trend function and :math:`\vect{W}` is a Gaussian process of dimension :math:`\outputDim` with zero mean and a specified covariance function. The Gaussian process regression denoted by :math:`\vect{Z}` is defined by:

    .. math::

        \vect{Z}(\omega, \vect{x}) = \vect{Y}(\omega, \vect{x})\, | \,  \cC

    where :math:`\cC` is the condition :math:`\vect{Y}(\omega, \vect{x}_k) = \vect{y}_k` for
    :math:`1 \leq k \leq \sampleSize`.

    The class provides services related to the conditional covariance of the Gaussian process regression :math:`\vect{Z}`.

    Examples
    --------
    Create the model :math:`g: \Rset \mapsto \Rset` and the samples:

    >>> import openturns as ot
    >>> trend = ot.SymbolicFunction(['x'],  ['1'])
    >>> sampleX = [[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]]
    >>> sampleY = trend(sampleX)

    Create the algorithm:

    >>> covarianceModel = ot.SquaredExponential([1.0])
    >>> covarianceModel.setActiveParameter([])

    >>> algo = ot.GaussianProcessRegression(sampleX, sampleY, covarianceModel, trend)
    >>> algo.run()
    >>> result = algo.getResult()
    >>> condCov = ot.GaussianProcessConditionalCovariance(result)
    >>> c = condCov([1.1])

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.GaussianProcessConditionalCovariance_getClassName(self)

    def __repr__(self):
        return _metamodel.GaussianProcessConditionalCovariance___repr__(self)

    def __str__(self, *args):
        return _metamodel.GaussianProcessConditionalCovariance___str__(self, *args)

    def getConditionalMean(self, *args):
        r"""
        Compute the conditional mean of the Gaussian process on a point or a sample of points.

        Parameters
        ----------
        x : sequence of float
            The point :math:`\vect{x}` where the conditional mean of the output has to be evaluated.
        sampleX : 2-d sequence of float
             The sample :math:`(\vect{\xi}_1, \dots, \vect{\xi}_N)` where the conditional mean of the output has to be evaluated (*N* can be equal to 1).

        Returns
        -------
        condMean : :class:`~openturns.Point`
            The conditional mean the Gaussian process regression :math:`\vect{Z}` defined in :eq:`GPRdef` at point :math:`\vect{x}` or on the sample :math:`(\vect{\xi}_1, \dots, \vect{\xi}_N)`:

            .. math::

                \left(
                  \begin{array}{l}
                    \Expect{\vect{Z}(\omega, \vect{\xi}_1)}\\
                    \dots  \\
                    \Expect{\vect{Z}(\omega, \vect{\xi}_N)}
                  \end{array}
                \right)

            This vector is in :math:`\Rset^{N \times \outputDim}`.

        """
        return _metamodel.GaussianProcessConditionalCovariance_getConditionalMean(self, *args)

    def getConditionalCovariance(self, *args):
        r"""
        Compute the conditional covariance of the Gaussian process on a point (or several points).

        Parameters
        ----------
        x : sequence of float
            The point :math:`\vect{x}` where the conditional covariance of the output has to be evaluated.
        sampleX : 2-d sequence of float
             The sample :math:`(\vect{\xi}_1, \dots, \vect{\xi}_N)` where the conditional covariance of the output has to be evaluated (*N* can be equal to 1).

        Returns
        -------
        condCov : :class:`~openturns.CovarianceMatrix`
            The conditional covariance of the Gaussian process regression  :math:`\vect{Z}` defined in :eq:`GPRdef` at point :math:`\vect{x}` is defined in :eq:`covarianceGPR_point`. When computed on the sample :math:`(\vect{\xi}_1, \dots, \vect{\xi}_N)`, the covariance matrix is defined in :eq:`covarianceGPR_sample`.
        """
        return _metamodel.GaussianProcessConditionalCovariance_getConditionalCovariance(self, *args)

    def getDiagonalCovarianceCollection(self, xi):
        r"""
        Compute the conditional covariance of the Gaussian process on a sample.

        Parameters
        ----------
        sampleX : 2-d sequence of float
             The sample :math:`(\vect{\xi}_1, \dots, \vect{\xi}_N)` where the conditional marginal covariance of the output has to be evaluated (*N* can be equal to 1).

        Returns
        -------
        condCov : :class:`~openturns.CovarianceMatrixCollection`
            The collection of conditional covariance matrices :math:`\Cov{\vect{Z}(\omega, \vect{\xi}_i)}
            = \mat{\Sigma_{ii}}` for :math:`1 \leq i \leq N` defined in :eq:`covarianceGPR_sample`.

        Notes
        -----
        Each element of the collection corresponds to the conditional covariance with respect to the input learning set
        (e.g. a pointwise evaluation of the `getDiagonalCovariance`). The returned collection is
        of size :math:`N` and contains matrices in :math:`\cM_{\outputDim, \outputDim}(\Rset)`.
        """
        return _metamodel.GaussianProcessConditionalCovariance_getDiagonalCovarianceCollection(self, xi)

    def getDiagonalCovariance(self, xi):
        r"""
        Compute the diagonal conditional covariance of the Gaussian process on a point.

        Parameters
        ----------
        x : sequence of float
            The point :math:`\vect{x}` where the conditional marginal covariance of the output has to be evaluated.

        Returns
        -------
        condCov : :class:`~openturns.CovarianceMatrix`
            The conditional covariance :math:`\Cov{\vect{Y}(\omega, \vect{x})\, | \,  \cC}` at point :math:`\vect{x}`.
        """
        return _metamodel.GaussianProcessConditionalCovariance_getDiagonalCovariance(self, xi)

    def getConditionalMarginalVariance(self, *args):
        r"""
        Compute the conditional variance of the Gaussian process on a point (or several points).

        Parameters
        ----------
        x : sequence of float
            The point :math:`\vect{x}` where the conditional variance of the output has to be evaluated.
        sampleX : 2-d sequence of float
             The sample :math:`(\vect{\xi}_1, \dots, \vect{\xi}_N)` where the conditional variance of the output has to be evaluated (*N* can be equal to 1).
        marginalIndex : int
            Marginal of interest (for multiple outputs).

            Default value is 0 (first component).
        marginalIndices : sequence of int
            Marginals of interest (for multiple outputs).

        Returns
        -------
        var : float
              The variance of the specified marginal of the Gaussian process regression  :math:`\vect{Z}`
              defined in :eq:`GPRdef` at the specified point.

        varPoint : sequence of float
            The marginal variances of each marginal of interest computed at each given point.


        Notes
        -----
        If only one  marginal :math:`k`  of interest  and one point  :math:`\vect{x}` have been specified,
        the method returns :math:`\Var{Z_k(\omega, \vect{x})}` where :math:`\vect{Z}` is the Gaussian
        process regression  defined in :eq:`GPRdef`.

        If several marginal of interest :math:`(k_1, \dots, k_M)` or several points :math:`(\vect{\xi}_1,
        \dots, \vect{\xi}_N)` have been specified, the method returns the concatenation of
        sequence of variances :math:`(\Var{Z_{k_1}(\omega, \vect{\xi}_j)}, \dots, \Var{Z_{k_M}(\omega, \vect{\xi}_j)})` for each :math:`1 \leq j \leq N`.
        """
        return _metamodel.GaussianProcessConditionalCovariance_getConditionalMarginalVariance(self, *args)

    def __call__(self, *args):
        return _metamodel.GaussianProcessConditionalCovariance___call__(self, *args)

    def __init__(self, *args):
        _metamodel.GaussianProcessConditionalCovariance_swiginit(self, _metamodel.new_GaussianProcessConditionalCovariance(*args))
    __swig_destroy__ = _metamodel.delete_GaussianProcessConditionalCovariance

# Register GaussianProcessConditionalCovariance in _metamodel:
_metamodel.GaussianProcessConditionalCovariance_swigregister(GaussianProcessConditionalCovariance)
class LeastSquaresExpansion(FunctionalChaosAlgorithm):
    r"""
    L2 approximation on an orthonormal basis using least-squares and a fixed basis.

    Available constructors:
        LeastSquaresExpansion(*inputSample, outputSample, distribution*)

        LeastSquaresExpansion(*inputSample, weights, outputSample, distribution*)

        LeastSquaresExpansion(*inputSample, outputSample, distribution, basis, basisSize, methodName*)

        LeastSquaresExpansion(*inputSample, weights, outputSample, distribution, basis, basisSize, methodName*)

    Parameters
    ----------
    inputSample : 2-d sequence of float of size :math:`n>0`
        Input sample.
    weight : sequence of float of size :math:`n>0`, optional
        Input weights. By default, a uniform weight equals to :math:`1/n` is used.
    outputSample : 2-d sequence of floats of size :math:`n>0`
        Output sample.
    distribution : :class:`~openturns.Distribution`
        The distribution associated to the weighted sample *(inputSample, weights)*
    basis : :class:`~openturns.OrthogonalBasis`, optional
        The orthonormal basis of the vector space on which the approximation is built.
        By default, a basis is built using an hyperbolic enumerate function
        :class:`~openturns.HyperbolicAnisotropicEnumerateFunction` associated to the
        :math:`q-` norm specified by the `FunctionalChaosAlgorithm-QNorm` key in
        :class:`~openturns.ResourceMap`.
        The basis is obtained through a tensorization of the univariate orthonormal
        polynomial bases associated to each marginal distributions of *distribution*.
    basisSize : int, optional
        The size of the basis on which the approximation is built. If not given, it is
        given by the `FunctionalChaosAlgorithm-BasisSize` key in
        :class:`~openturns.ResourceMap` if this value is positive, or as the cardinal
        of the set of basis functions up to a degree given by the
        `FunctionalChaosAlgorithm-MaximumTotalDegree` key in
        :class:`~openturns.ResourceMap`.
    methodName : str, optional
        The decomposition method used to solve the least-squares problem, of
        type :class:`~openturns.LeastSquaresMethod`. If not given, it is given by the
        `LeastSquaresExpansion-DecompositionMethod` key in
        :class:`~openturns.ResourceMap`.

    See also
    --------
    IntegrationExpansion, FunctionalChaosAlgorithm, LeastSquaresMethod

    Examples
    --------
    Solves a functional linear least squares approximation using residual minimization with QR method:

    >>> import openturns as ot
    >>> g = ot.SymbolicFunction('x', 'sin(x)')
    >>> distribution = ot.Uniform(-2.0, 2.0)
    >>> inSample = distribution.getSample(10)
    >>> outSample = g(inSample)
    >>> basis = ot.OrthogonalProductPolynomialFactory([ot.LegendreFactory()])
    >>> basisSize = 5
    >>> algo = ot.LeastSquaresExpansion(inSample, outSample, distribution, basis, basisSize, 'QR')
    >>> algo.run()
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.LeastSquaresExpansion_getClassName(self)

    def run(self):
        r"""
        Compute the metamodel.

        Notes
        -----
        Evaluates the metamodel and stores all the results in a result structure.
        """
        return _metamodel.LeastSquaresExpansion_run(self)

    def getActiveFunctions(self):
        r"""
        Accessor to the active functions in the basis.

        Returns
        -------
        activeFunctions : sequence of `int`
            The indices of the functions used for the approximation in the basis.
        """
        return _metamodel.LeastSquaresExpansion_getActiveFunctions(self)

    def setActiveFunctions(self, activeFunctions):
        r"""
        Accessor to the active functions in the basis.

        Parameters
        ----------
        activeFunctions : sequence of `int`
            The indices of the functions used for the approximation in the basis.
        """
        return _metamodel.LeastSquaresExpansion_setActiveFunctions(self, activeFunctions)

    def __repr__(self):
        return _metamodel.LeastSquaresExpansion___repr__(self)

    def __str__(self, *args):
        return _metamodel.LeastSquaresExpansion___str__(self, *args)

    def setUseDomination(self, useDomination):
        r"""
        Domination method flag accessor.

        Parameters
        ----------
        useDomination : bool
            Whether to use the domination method.

        Notes
        -----
        The domination method consists in using the basis defined in the argument *adaptiveStrategy* (or its default
        implementation if not specified). No
        isoprobabilistic transformation is used. This basis it is not necessarily orthonormal with respect to
        the *inputDistribution*. As a result, the coefficients can be computed with a least squares method only
        (select class:`~openturns.LeastSquaresStrategy` for the *projectionStrategy*) and the Sobol' indices will not
        be computed.

        """
        return _metamodel.LeastSquaresExpansion_setUseDomination(self, useDomination)

    def __init__(self, *args):
        _metamodel.LeastSquaresExpansion_swiginit(self, _metamodel.new_LeastSquaresExpansion(*args))
    __swig_destroy__ = _metamodel.delete_LeastSquaresExpansion

# Register LeastSquaresExpansion in _metamodel:
_metamodel.LeastSquaresExpansion_swigregister(LeastSquaresExpansion)
class IntegrationExpansion(FunctionalChaosAlgorithm):
    r"""
    L2 approximation on an orthonormal basis using least-squares and a fixed basis.

    Available constructors:
        IntegrationExpansion(*inputSample, outputSample, distribution*)

        IntegrationExpansion(*inputSample, weights, outputSample, distribution*)

        IntegrationExpansion(*inputSample, outputSample, distribution, basis, basisSize*)

        IntegrationExpansion(*inputSample, weights, outputSample, distribution, basis, basisSize*)

    Parameters
    ----------
    inputSample : 2-d sequence of float of size :math:`n>0`
        Input sample.
    weight : sequence of float of size :math:`n>0`, optional
        Input weights. By default, a uniform weight equals to :math:`1/n` is used.
    outputSample : 2-d sequence of floats of size :math:`n>0`
        Output sample.
    distribution : :class:`~openturns.Distribution`
        The distribution associated to the weighted sample *(inputSample, weights)*
    basis : :class:`~openturns.OrthogonalBasis`, optional
        The orthonormal basis of the vector space on which the approximation is built.
        By default, a basis is built using an hyperbolic enumerate function
        :class:`~openturns.HyperbolicAnisotropicEnumerateFunction` associated to the
        :math:`q-` norm specified by the `FunctionalChaosAlgorithm-QNorm` key in
        :class:`~openturns.ResourceMap`.
        The basis is obtained through a tensorization of the univariate orthonormal
        polynomial bases associated to each marginal distributions of *distribution*.
    basisSize : int, optional
        The size of the basis on which the approximation is built. If not given, it is
        given by the `FunctionalChaosAlgorithm-BasisSize` key in
        :class:`~openturns.ResourceMap` if this value is positive, or as the cardinal
        of the set of basis functions up to a degree given by the
        `FunctionalChaosAlgorithm-MaximumTotalDegree` key in
        :class:`~openturns.ResourceMap`.

    See also
    --------
    LeastSquaresExpansion, FunctionalChaosAlgorithm, LeastSquaresMethod

    Examples
    --------
    Solves a functional least-squares approximation using a projection on an orthonormal basis:

    >>> import openturns as ot
    >>> g = ot.SymbolicFunction('x', 'sin(x)')
    >>> distribution = ot.Uniform(-2.0, 2.0)
    >>> inSample = distribution.getSample(10)
    >>> outSample = g(inSample)
    >>> basis = ot.OrthogonalProductPolynomialFactory([ot.LegendreFactory()])
    >>> basisSize = 5
    >>> algo = ot.IntegrationExpansion(inSample, outSample, distribution, basis, basisSize)
    >>> algo.run()
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.IntegrationExpansion_getClassName(self)

    def getActiveFunctions(self):
        r"""
        Accessor to the active functions in the basis.

        Returns
        -------
        activeFunctions : sequence of `int`
            The indices of the functions used for the approximation in the basis.
        """
        return _metamodel.IntegrationExpansion_getActiveFunctions(self)

    def setActiveFunctions(self, activeFunctions):
        r"""
        Accessor to the active functions in the basis.

        Parameters
        ----------
        activeFunctions : sequence of `int`
            The indices of the functions used for the approximation in the basis.
        """
        return _metamodel.IntegrationExpansion_setActiveFunctions(self, activeFunctions)

    def run(self):
        r"""
        Compute the metamodel.

        Notes
        -----
        Evaluates the metamodel and stores all the results in a result structure.
        """
        return _metamodel.IntegrationExpansion_run(self)

    def __repr__(self):
        return _metamodel.IntegrationExpansion___repr__(self)

    def __str__(self, *args):
        return _metamodel.IntegrationExpansion___str__(self, *args)

    def __init__(self, *args):
        _metamodel.IntegrationExpansion_swiginit(self, _metamodel.new_IntegrationExpansion(*args))
    __swig_destroy__ = _metamodel.delete_IntegrationExpansion

# Register IntegrationExpansion in _metamodel:
_metamodel.IntegrationExpansion_swigregister(IntegrationExpansion)
class _IndicesCollection2(object):
    r"""
    Collection.

    Examples
    --------
    >>> import openturns as ot

    - Collection of **real values**:

    >>> ot.ScalarCollection(2)
    [0,0]
    >>> ot.ScalarCollection(2, 3.25)
    [3.25,3.25]
    >>> vector = ot.ScalarCollection([2.0, 1.5, 2.6])
    >>> vector
    [2,1.5,2.6]
    >>> vector[1] = 4.2
    >>> vector
    [2,4.2,2.6]
    >>> vector.add(3.8)
    >>> vector
    [2,4.2,2.6,3.8]

    - Collection of **complex values**:

    >>> ot.ComplexCollection(2)
    [(0,0),(0,0)]
    >>> ot.ComplexCollection(2, 3+4j)
    [(3,4),(3,4)]
    >>> vector = ot.ComplexCollection([2+3j, 1-4j, 3.0])
    >>> vector
    [(2,3),(1,-4),(3,0)]
    >>> vector[1] = 4+3j
    >>> vector
    [(2,3),(4,3),(3,0)]
    >>> vector.add(5+1j)
    >>> vector
    [(2,3),(4,3),(3,0),(5,1)]

    - Collection of **booleans**:

    >>> ot.BoolCollection(3)
    [0,0,0]
    >>> ot.BoolCollection(3, 1)
    [1,1,1]
    >>> vector = ot.BoolCollection([0, 1, 0])
    >>> vector
    [0,1,0]
    >>> vector[1] = 0
    >>> vector
    [0,0,0]
    >>> vector.add(1)
    >>> vector
    [0,0,0,1]

    - Collection of **distributions**:

    >>> print(ot.DistributionCollection(2))
    [Uniform(a = -1, b = 1),Uniform(a = -1, b = 1)]
    >>> print(ot.DistributionCollection(2, ot.Gamma(2.75, 1.0)))
    [Gamma(k = 2.75, lambda = 1, gamma = 0),Gamma(k = 2.75, lambda = 1, gamma = 0)]
    >>> vector = ot.DistributionCollection([ot.Normal(), ot.Uniform()])
    >>> print(vector)
    [Normal(mu = 0, sigma = 1),Uniform(a = -1, b = 1)]
    >>> vector[1] = ot.Uniform(-0.5, 1)
    >>> print(vector)
    [Normal(mu = 0, sigma = 1),Uniform(a = -0.5, b = 1)]
    >>> vector.add(ot.Gamma(2.75, 1.0))
    >>> print(vector)
    [Normal(mu = 0, sigma = 1),Uniform(a = -0.5, b = 1),Gamma(k = 2.75, lambda = 1, gamma = 0)]
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __swig_destroy__ = _metamodel.delete__IndicesCollection2

    def clear(self):
        r"""
        Reset the collection to zero dimension.

        Examples
        --------
        >>> import openturns as ot
        >>> x = ot.Point(2)
        >>> x.clear()
        >>> x
        class=Point name=Unnamed dimension=0 values=[]
        """
        return _metamodel._IndicesCollection2_clear(self)

    def __len__(self):
        return _metamodel._IndicesCollection2___len__(self)

    def __eq__(self, rhs):
        return _metamodel._IndicesCollection2___eq__(self, rhs)

    def __contains__(self, val):
        return _metamodel._IndicesCollection2___contains__(self, val)

    def select(self, marginalIndices):
        r"""
        Selection from indices.

        Parameters
        ----------
        indices : sequence of int
            Indices to select

        Returns
        -------
        coll : sequence
            Sub-collection of values at the selection indices.
        """
        return _metamodel._IndicesCollection2_select(self, marginalIndices)

    def __getitem__(self, i):
        return _metamodel._IndicesCollection2___getitem__(self, i)

    def __setitem__(self, i, val):
        return _metamodel._IndicesCollection2___setitem__(self, i, val)

    def __delitem__(self, i):
        return _metamodel._IndicesCollection2___delitem__(self, i)

    def at(self, *args):
        r"""
        Access to an element of the collection.

        Parameters
        ----------
        index : positive int
            Position of the element to access.

        Returns
        -------
        element : type depends on the type of the collection
            Element of the collection at the position *index*.
        """
        return _metamodel._IndicesCollection2_at(self, *args)

    def add(self, *args):
        r"""
        Append a component (in-place).

        Parameters
        ----------
        value : type depends on the type of the collection.
            The component to append.

        Examples
        --------
        >>> import openturns as ot
        >>> x = ot.Point(2)
        >>> x.add(1.)
        >>> print(x)
        [0,0,1]
        """
        return _metamodel._IndicesCollection2_add(self, *args)

    def getSize(self):
        r"""
        Get the collection's dimension (or size).

        Returns
        -------
        n : int
            The number of components in the collection.
        """
        return _metamodel._IndicesCollection2_getSize(self)

    def resize(self, newSize):
        r"""
        Change the size of the collection.

        Parameters
        ----------
        newSize : positive int
            New size of the collection.

        Notes
        -----
        If the new size is smaller than the older one, the last elements are thrown
        away, else the new elements are set to the default value of the element type.

        Examples
        --------
        >>> import openturns as ot
        >>> x = ot.Point(2, 4)
        >>> print(x)
        [4,4]
        >>> x.resize(1)
        >>> print(x)
        [4]
        >>> x.resize(4)
        >>> print(x)
        [4,0,0,0]
        """
        return _metamodel._IndicesCollection2_resize(self, newSize)

    def isEmpty(self):
        r"""
        Tell if the collection is empty.

        Returns
        -------
        isEmpty : bool
            *True* if there is no element in the collection.

        Examples
        --------
        >>> import openturns as ot
        >>> x = ot.Point(2)
        >>> x.isEmpty()
        False
        >>> x.clear()
        >>> x.isEmpty()
        True
        """
        return _metamodel._IndicesCollection2_isEmpty(self)

    def find(self, val):
        return _metamodel._IndicesCollection2_find(self, val)

    def __repr__(self):
        return _metamodel._IndicesCollection2___repr__(self)

    def __str__(self, *args):
        return _metamodel._IndicesCollection2___str__(self, *args)

    def index(self, value):
        r"""
        Find the index of a given value.

        Parameters
        ----------
        val : collection value type
            The value to find

        Returns
        -------
        index : int
            The index of the first occurrence of the value.
            Throws when the value is not found.
        """
        return _metamodel._IndicesCollection2_index(self, value)

    def __init__(self, *args):
        _metamodel._IndicesCollection2_swiginit(self, _metamodel.new__IndicesCollection2(*args))

# Register _IndicesCollection2 in _metamodel:
_metamodel._IndicesCollection2_swigregister(_IndicesCollection2)
class FieldFunctionalChaosResult(openturns.common.PersistentObject):
    r"""
    Functional metamodel result.

    Parameters
    ----------
    inputKLResultCollection : sequence of :class:`~openturns.KarhunenLoeveResult`
        List of input fields decompositions.
    fceResult : :class:`~openturns.FunctionalChaosResult`
        Functional chaos decomposition.
    outputKLResultCollection : sequence of :class:`~openturns.KarhunenLoeveResult`
        List of output fields decompositions.

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.FieldFunctionalChaosResult_getClassName(self)

    def __repr__(self):
        return _metamodel.FieldFunctionalChaosResult___repr__(self)

    def getInputKLResultCollection(self):
        r"""
        Accessor to the input fields decompositions.

        Returns
        -------
        inputKLResultCollection : Collection of :class:`~openturns.KarhunenLoeveResult`
            List of input fields decompositions.
        """
        return _metamodel.FieldFunctionalChaosResult_getInputKLResultCollection(self)

    def getOutputKLResultCollection(self):
        r"""
        Accessor to the output fields decompositions.

        Returns
        -------
        outputKLResultCollection : Collection of :class:`~openturns.KarhunenLoeveResult`
            List of output fields decompositions.
        """
        return _metamodel.FieldFunctionalChaosResult_getOutputKLResultCollection(self)

    def getFCEResult(self):
        r"""
        Accessor to the chaos decomposition.

        Returns
        -------
        fceResult : :class:`~openturns.FunctionalChaosResult`
            Functional chaos decomposition.
        """
        return _metamodel.FieldFunctionalChaosResult_getFCEResult(self)

    def getInputBlockIndices(self):
        r"""
        Accessor to the input block indices.

        Returns
        -------
        blockIndices : :class:`~openturns.IndicesCollection`
            Independent components indices.
        """
        return _metamodel.FieldFunctionalChaosResult_getInputBlockIndices(self)

    def setInputBlockIndices(self, inputBlockIndices):
        r"""
        Accessor to the input block indices.

        Parameters
        ----------
        blockIndices : 2-d sequence of int
            Independent components indices.
        """
        return _metamodel.FieldFunctionalChaosResult_setInputBlockIndices(self, inputBlockIndices)

    def getOutputBlockIndices(self):
        r"""
        Accessor to the output block indices.

        Returns
        -------
        blockIndices : :class:`~openturns.IndicesCollection`
            Independent components indices.
        """
        return _metamodel.FieldFunctionalChaosResult_getOutputBlockIndices(self)

    def setOutputBlockIndices(self, outputBlockIndices):
        r"""
        Accessor to the output block indices.

        Parameters
        ----------
        blockIndices : 2-d sequence of int
            Independent components indices.
        """
        return _metamodel.FieldFunctionalChaosResult_setOutputBlockIndices(self, outputBlockIndices)

    def getFieldToPointMetaModel(self):
        r"""
        Accessor to the metamodel.

        Returns
        -------
        metamodel : :class:`~openturns.FieldToPointFunction`
            Metamodel function.
        """
        return _metamodel.FieldFunctionalChaosResult_getFieldToPointMetaModel(self)

    def getPointToFieldMetaModel(self):
        r"""
        Accessor to the metamodel.

        Returns
        -------
        metamodel : :class:`~openturns.PointToFieldFunction`
            Metamodel function.
        """
        return _metamodel.FieldFunctionalChaosResult_getPointToFieldMetaModel(self)

    def getFieldMetaModel(self):
        r"""
        Accessor to the metamodel.

        Returns
        -------
        metamodel : :class:`~openturns.FieldFunction`
            Metamodel function.
        """
        return _metamodel.FieldFunctionalChaosResult_getFieldMetaModel(self)

    def setMetaModel(self, *args):
        r"""
        Accessor to the metamodel.

        Parameters
        ----------
        metamodel : :class:`~openturns.FieldToPointFunction`
            Metamodel function.
        """
        return _metamodel.FieldFunctionalChaosResult_setMetaModel(self, *args)

    def setInputProcessSample(self, inputProcessSample):
        r"""
        Accessor to the input process sample.

        Parameters
        ----------
        inputProcessSample : :class:`~openturns.ProcessSample`
            Input process sample.
        """
        return _metamodel.FieldFunctionalChaosResult_setInputProcessSample(self, inputProcessSample)

    def getInputProcessSample(self):
        r"""
        Accessor to the input process sample.

        Returns
        -------
        inputProcessSample : :class:`~openturns.ProcessSample`
            Input process sample.
        """
        return _metamodel.FieldFunctionalChaosResult_getInputProcessSample(self)

    def setOutputProcessSample(self, outputProcessSample):
        r"""
        Accessor to the output process sample.

        Parameters
        ----------
        outputProcessSample : :class:`~openturns.ProcessSample`
            Output process sample.
        """
        return _metamodel.FieldFunctionalChaosResult_setOutputProcessSample(self, outputProcessSample)

    def getOutputProcessSample(self):
        r"""
        Accessor to the output process sample.

        Returns
        -------
        outputProcessSample : :class:`~openturns.ProcessSample`
            Output process sample.
        """
        return _metamodel.FieldFunctionalChaosResult_getOutputProcessSample(self)

    def setInputSample(self, inputSample):
        r"""
        Accessor to the input sample.

        Parameters
        ----------
        inputSample : :class:`~openturns.Sample`
            Input values.
        """
        return _metamodel.FieldFunctionalChaosResult_setInputSample(self, inputSample)

    def getInputSample(self):
        r"""
        Accessor to the input sample.

        Returns
        -------
        inputSample : :class:`~openturns.Sample`
            Input values.
        """
        return _metamodel.FieldFunctionalChaosResult_getInputSample(self)

    def setOutputSample(self, outputSample):
        r"""
        Accessor to the output sample.

        Parameters
        ----------
        outputSample : :class:`~openturns.Sample`
            Output values.
        """
        return _metamodel.FieldFunctionalChaosResult_setOutputSample(self, outputSample)

    def getOutputSample(self):
        r"""
        Accessor to the output sample.

        Returns
        -------
        outputSample : :class:`~openturns.Sample`
            Output values.
        """
        return _metamodel.FieldFunctionalChaosResult_getOutputSample(self)

    def setModesSample(self, modesSample):
        r"""
        Accessor to the modes sample.

        Parameters
        ----------
        modes : :class:`~openturns.Sample`
            Projected modes values.
        """
        return _metamodel.FieldFunctionalChaosResult_setModesSample(self, modesSample)

    def getModesSample(self):
        r"""
        Accessor to the modes sample.

        Returns
        -------
        modes : :class:`~openturns.Sample`
             Projected modes values.
        """
        return _metamodel.FieldFunctionalChaosResult_getModesSample(self)

    def __init__(self, *args):
        _metamodel.FieldFunctionalChaosResult_swiginit(self, _metamodel.new_FieldFunctionalChaosResult(*args))
    __swig_destroy__ = _metamodel.delete_FieldFunctionalChaosResult

# Register FieldFunctionalChaosResult in _metamodel:
_metamodel.FieldFunctionalChaosResult_swigregister(FieldFunctionalChaosResult)
class KarhunenLoeveResultCollection(object):
    r"""
    Collection.

    Examples
    --------
    >>> import openturns as ot

    - Collection of **real values**:

    >>> ot.ScalarCollection(2)
    [0,0]
    >>> ot.ScalarCollection(2, 3.25)
    [3.25,3.25]
    >>> vector = ot.ScalarCollection([2.0, 1.5, 2.6])
    >>> vector
    [2,1.5,2.6]
    >>> vector[1] = 4.2
    >>> vector
    [2,4.2,2.6]
    >>> vector.add(3.8)
    >>> vector
    [2,4.2,2.6,3.8]

    - Collection of **complex values**:

    >>> ot.ComplexCollection(2)
    [(0,0),(0,0)]
    >>> ot.ComplexCollection(2, 3+4j)
    [(3,4),(3,4)]
    >>> vector = ot.ComplexCollection([2+3j, 1-4j, 3.0])
    >>> vector
    [(2,3),(1,-4),(3,0)]
    >>> vector[1] = 4+3j
    >>> vector
    [(2,3),(4,3),(3,0)]
    >>> vector.add(5+1j)
    >>> vector
    [(2,3),(4,3),(3,0),(5,1)]

    - Collection of **booleans**:

    >>> ot.BoolCollection(3)
    [0,0,0]
    >>> ot.BoolCollection(3, 1)
    [1,1,1]
    >>> vector = ot.BoolCollection([0, 1, 0])
    >>> vector
    [0,1,0]
    >>> vector[1] = 0
    >>> vector
    [0,0,0]
    >>> vector.add(1)
    >>> vector
    [0,0,0,1]

    - Collection of **distributions**:

    >>> print(ot.DistributionCollection(2))
    [Uniform(a = -1, b = 1),Uniform(a = -1, b = 1)]
    >>> print(ot.DistributionCollection(2, ot.Gamma(2.75, 1.0)))
    [Gamma(k = 2.75, lambda = 1, gamma = 0),Gamma(k = 2.75, lambda = 1, gamma = 0)]
    >>> vector = ot.DistributionCollection([ot.Normal(), ot.Uniform()])
    >>> print(vector)
    [Normal(mu = 0, sigma = 1),Uniform(a = -1, b = 1)]
    >>> vector[1] = ot.Uniform(-0.5, 1)
    >>> print(vector)
    [Normal(mu = 0, sigma = 1),Uniform(a = -0.5, b = 1)]
    >>> vector.add(ot.Gamma(2.75, 1.0))
    >>> print(vector)
    [Normal(mu = 0, sigma = 1),Uniform(a = -0.5, b = 1),Gamma(k = 2.75, lambda = 1, gamma = 0)]
    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
    __swig_destroy__ = _metamodel.delete_KarhunenLoeveResultCollection

    def clear(self):
        r"""
        Reset the collection to zero dimension.

        Examples
        --------
        >>> import openturns as ot
        >>> x = ot.Point(2)
        >>> x.clear()
        >>> x
        class=Point name=Unnamed dimension=0 values=[]
        """
        return _metamodel.KarhunenLoeveResultCollection_clear(self)

    def __len__(self):
        return _metamodel.KarhunenLoeveResultCollection___len__(self)

    def __eq__(self, rhs):
        return _metamodel.KarhunenLoeveResultCollection___eq__(self, rhs)

    def __contains__(self, val):
        return _metamodel.KarhunenLoeveResultCollection___contains__(self, val)

    def select(self, marginalIndices):
        r"""
        Selection from indices.

        Parameters
        ----------
        indices : sequence of int
            Indices to select

        Returns
        -------
        coll : sequence
            Sub-collection of values at the selection indices.
        """
        return _metamodel.KarhunenLoeveResultCollection_select(self, marginalIndices)

    def __getitem__(self, i):
        return _metamodel.KarhunenLoeveResultCollection___getitem__(self, i)

    def __setitem__(self, i, val):
        return _metamodel.KarhunenLoeveResultCollection___setitem__(self, i, val)

    def __delitem__(self, i):
        return _metamodel.KarhunenLoeveResultCollection___delitem__(self, i)

    def at(self, *args):
        r"""
        Access to an element of the collection.

        Parameters
        ----------
        index : positive int
            Position of the element to access.

        Returns
        -------
        element : type depends on the type of the collection
            Element of the collection at the position *index*.
        """
        return _metamodel.KarhunenLoeveResultCollection_at(self, *args)

    def add(self, *args):
        r"""
        Append a component (in-place).

        Parameters
        ----------
        value : type depends on the type of the collection.
            The component to append.

        Examples
        --------
        >>> import openturns as ot
        >>> x = ot.Point(2)
        >>> x.add(1.)
        >>> print(x)
        [0,0,1]
        """
        return _metamodel.KarhunenLoeveResultCollection_add(self, *args)

    def getSize(self):
        r"""
        Get the collection's dimension (or size).

        Returns
        -------
        n : int
            The number of components in the collection.
        """
        return _metamodel.KarhunenLoeveResultCollection_getSize(self)

    def resize(self, newSize):
        r"""
        Change the size of the collection.

        Parameters
        ----------
        newSize : positive int
            New size of the collection.

        Notes
        -----
        If the new size is smaller than the older one, the last elements are thrown
        away, else the new elements are set to the default value of the element type.

        Examples
        --------
        >>> import openturns as ot
        >>> x = ot.Point(2, 4)
        >>> print(x)
        [4,4]
        >>> x.resize(1)
        >>> print(x)
        [4]
        >>> x.resize(4)
        >>> print(x)
        [4,0,0,0]
        """
        return _metamodel.KarhunenLoeveResultCollection_resize(self, newSize)

    def isEmpty(self):
        r"""
        Tell if the collection is empty.

        Returns
        -------
        isEmpty : bool
            *True* if there is no element in the collection.

        Examples
        --------
        >>> import openturns as ot
        >>> x = ot.Point(2)
        >>> x.isEmpty()
        False
        >>> x.clear()
        >>> x.isEmpty()
        True
        """
        return _metamodel.KarhunenLoeveResultCollection_isEmpty(self)

    def find(self, val):
        return _metamodel.KarhunenLoeveResultCollection_find(self, val)

    def __repr__(self):
        return _metamodel.KarhunenLoeveResultCollection___repr__(self)

    def __str__(self, *args):
        return _metamodel.KarhunenLoeveResultCollection___str__(self, *args)

    def index(self, value):
        r"""
        Find the index of a given value.

        Parameters
        ----------
        val : collection value type
            The value to find

        Returns
        -------
        index : int
            The index of the first occurrence of the value.
            Throws when the value is not found.
        """
        return _metamodel.KarhunenLoeveResultCollection_index(self, value)

    def __init__(self, *args):
        _metamodel.KarhunenLoeveResultCollection_swiginit(self, _metamodel.new_KarhunenLoeveResultCollection(*args))

# Register KarhunenLoeveResultCollection in _metamodel:
_metamodel.KarhunenLoeveResultCollection_swigregister(KarhunenLoeveResultCollection)
class FieldFunctionalChaosAlgorithm(openturns.common.PersistentObject):
    r"""Base class for field chaos."""

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.FieldFunctionalChaosAlgorithm_getClassName(self)

    def getBlockIndices(self):
        r"""
        Accessor to the output block indices.

        Returns
        -------
        blockIndices : :class:`~openturns.IndicesCollection`
            Independent output components indices.
        """
        return _metamodel.FieldFunctionalChaosAlgorithm_getBlockIndices(self)

    def getThreshold(self):
        r"""
        Accessor to the eigenvalues cutoff ratio.

        Returns
        -------
        s : float, :math:`\geq 0`
            The threshold :math:`s`.
        """
        return _metamodel.FieldFunctionalChaosAlgorithm_getThreshold(self)

    def setThreshold(self, threshold):
        r"""
        Accessor to the eigenvalues cutoff ratio.

        Parameters
        ----------
        s : float, :math:`\geq 0`
            The threshold :math:`s`.
        """
        return _metamodel.FieldFunctionalChaosAlgorithm_setThreshold(self, threshold)

    def getNbModes(self):
        r"""
        Accessor to the maximum number of modes to compute.

        Returns
        -------
        n : int
            The maximum number of modes to compute.
            The actual number of modes also depends on the threshold criterion.
        """
        return _metamodel.FieldFunctionalChaosAlgorithm_getNbModes(self)

    def setNbModes(self, nbModes):
        r"""
        Accessor to the maximum number of modes to compute.

        Parameters
        ----------
        n : int
            The maximum number of modes to compute.
            The actual number of modes also depends on the threshold criterion.
        """
        return _metamodel.FieldFunctionalChaosAlgorithm_setNbModes(self, nbModes)

    def getRecompress(self):
        r"""
        Accessor to the recompression flag.

        Returns
        -------
        recompress : bool
            Whether to recompress the output Karhunen-Loeve decompositions.
            This can only be enabled if the scale of the output variable blocks is the same.
        """
        return _metamodel.FieldFunctionalChaosAlgorithm_getRecompress(self)

    def setRecompress(self, recompress):
        r"""
        Accessor to the recompression flag.

        Parameters
        ----------
        recompress : bool
            Whether to recompress the output Karhunen-Loeve decompositions.
            The modes are truncated a second time according to a global eigen value
            bound across output decompositions.
            This can only be enabled if the scale of the output variable blocks is the same.
        """
        return _metamodel.FieldFunctionalChaosAlgorithm_setRecompress(self, recompress)

    def __repr__(self):
        return _metamodel.FieldFunctionalChaosAlgorithm___repr__(self)

    def getResult(self):
        r"""
        Result accessor.

        Returns
        -------
        result : :class:`openturns.FieldFunctionalChaosResult`
            Result class.
        """
        return _metamodel.FieldFunctionalChaosAlgorithm_getResult(self)

    def __init__(self, *args):
        _metamodel.FieldFunctionalChaosAlgorithm_swiginit(self, _metamodel.new_FieldFunctionalChaosAlgorithm(*args))
    __swig_destroy__ = _metamodel.delete_FieldFunctionalChaosAlgorithm

# Register FieldFunctionalChaosAlgorithm in _metamodel:
_metamodel.FieldFunctionalChaosAlgorithm_swigregister(FieldFunctionalChaosAlgorithm)
class FieldToPointFunctionalChaosAlgorithm(FieldFunctionalChaosAlgorithm):
    r"""
    Functional metamodel algorithm based on chaos decomposition.

    The present algorithm allows one to build a response surface of the application :math:`h` of the form:

    .. math::
        h: \left|
          \begin{array}{ccl}
             \cM_N \times (\Rset^d)^N & \rightarrow & \Rset^p \\
             \mat{X} & \mapsto & \vect{Y}
          \end{array}
        \right.

    The application :math:`h` is known from :math:`n` fields :math:`(\mat{X_1}, \dots, \mat{X_n})`
    of the associated input process :math:`\mat{X}`
    and :math:`n` vectors :math:`(\vect{Y_1},\dots,\vect{Y_n})`
    that fully characterize the output vector :math:`\vect{Y}`

    The linear projection function :math:`\pi_{ \vect{\lambda}, \vect{\varphi}}` of
    the Karhunen-Loeve decomposition by SVD is used to project the input fields,
    see :class:`~openturns.KarhunenLoeveSVDAlgorithm` for the notations.

    .. math::
        \pi_{\vect{\lambda}, \vect{\varphi}}: \left|
          \begin{array}{ccl}
            L^2(\cD, \Rset^d) & \rightarrow & \cS^{\Nset} \\
            f & \mapsto &\left(\dfrac{1}{\sqrt{\lambda_k}}\int_{\cD}f(\vect{t}) \vect{\varphi}_k(\vect{t})\, d\vect{t}\right)_{k \geq 1}
          \end{array}
        \right.

    The Karhunen-Loeve algorithm allows one to replace this integral by a specific weighted and finite sum
    and to write the projections of the j-th marginal of i-th input field :math:`\vect{X_i^j}` by multiplication
    with the projection matrix :math:`\mat{M^j} \in \Rset^{K_j} \times \Rset^{Nd}`:

    .. math::

        \mat{M_j} \vect{X_i^j} = \left( \begin{array}{l} \xi_1^j \\ \dots \\ \xi_{K_j}^j \end{array} \right)
        \in \Rset^{K_j}, \forall i \in [1, n], \forall j \in [1, d]

    with :math:`K_j` the retained number of modes in the decomposition of the j-th input.
    The projections of all the :math:`d` components of :math:`n` fields are assembled in the :math:`Q` matrix:

    .. math::

        \begin{align*}
            \mat{Q} = \mat{M} \mat{X} =
            \left(
              \begin{array}{l}
                \mat{M_1} \mat{X^1} \\
                \dots \\
                \mat{M_d} \mat{X^d}
              \end{array}
            \right) \in \Rset^{K_T} \times \Rset^n
         \end{align*}

    with :math:`K_T = \sum_{j=1}^d{K_j}` the total number of modes across input components.

    Then a functional chaos decomposition is built between the projected modes
    sample :math:`\mat{Q}` and the output samples :math:`\mat{Y}`,
    see :class:`~openturns.FunctionalChaosAlgorithm` for details.

    .. math::

        \tilde{g}(x) = \sum_{k=1}^{K_c} \beta_{\vect{\alpha}_k} \Psi_{\vect{\alpha}_k}(x)

    with :math:`K_c` the number of terms in the chaos decomposition.

    The final metamodel consists in the composition of the Karhunen-Loeve
    projections and the functional chaos metamodel.

    .. math::
        \tilde{h}: \left|
          \begin{array}{ccccl}
             \cM_N \times (\Rset^d)^N & \rightarrow & \Rset^{K_T} & \rightarrow & \Rset^p \\
             \mat{X} & \mapsto & \vect{Q} & \mapsto & \vect{Y}
          \end{array}
        \right.

    A limitation of this approach is that the projected modes sample has a dimension
    :math:`K_T` so the dimension of the input fields :math:`\mat{X_i}`
    and the associated number of modes must remain modest (curse of dimensionality).

    Parameters
    ----------
    x : :class:`~openturns.ProcessSample`
        Input process sample.
    y : :class:`~openturns.Sample`
        Output sample.

    See also
    --------
    FieldFunctionalChaosSobolIndices
    openturns.KarhunenLoeveAlgorithm
    openturns.FunctionalChaosAlgorithm

    Notes
    -----
    As the input process decomposition is done with the values decomposition approach,
    it is possible to control the number of modes retained per input,
    the idea being to avoid a large input dimension for the chaos decomposition step.
    As done in :class:`~openturns.KarhunenLoeveSVDAlgorithm`, the :func:`setThreshold`
    and :func:`setNbModes` methods allow one to control the spectrum ratio and maximum count.

    By default the input process data is assumed to not be centered, and the method
    :func:`setCenteredSample` allows one to skip centering of the data for both the
    computation of modes coefficients and inside the metamodel.

    In the case of homogeneous data (if variables have the same unit or scale),
    it is also possible to recompress the modes at the global level with :func:`setRecompress`.
    When enabled, the eigenvalues are gathered and sorted so as to find a global
    spectrum cut-off value by which the spectrum of each input is truncated.
    The default value can be set through the :class:`~openturns.ResourceMap` key
    *FieldFunctionalChaosAlgorithm-DefaultRecompress*.

    For the chaos metamodel step, it is possible to specify the basis size with
    the :class:`~openturns.ResourceMap` key *FunctionalChaosAlgorithm-BasisSize*.

    It is possible to group input variables by independent blocks with :func:`setBlockIndices`,
    this way Karhunen-Loeve process decompositions are done on each block rather
    than on each variable thus reducing the total number of modes and help reduce
    the chaos input dimension.

    Examples
    --------
    >>> import openturns as ot
    >>> ot.RandomGenerator.SetSeed(0)
    >>> mesh = ot.RegularGrid(0.0, 0.1, 20)
    >>> cov = ot.KroneckerCovarianceModel(ot.MaternModel([2.0], 1.5), ot.CovarianceMatrix(4))
    >>> X = ot.GaussianProcess(cov, mesh)
    >>> x = X.getSample(500)
    >>> y = [[m[0] + m[1] + m[2] - m[3] + m[0] * m[1] - m[2] * m[3] - 0.1 * m[0] * m[1] * m[2]] for m in [xi.computeMean() for xi in x]]
    >>> algo = ot.FieldToPointFunctionalChaosAlgorithm(x, y)
    >>> algo.setThreshold(4e-2)
    >>> # Temporarily lower the basis size for the sake of this example.
    >>> ot.ResourceMap.SetAsUnsignedInteger('FunctionalChaosAlgorithm-BasisSize', 100)
    >>> algo.run()
    >>> result = algo.getResult()
    >>> metamodel = result.getFieldToPointMetaModel()
    >>> y0hat = metamodel(x[0])
    >>> ot.ResourceMap.Reset()

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.FieldToPointFunctionalChaosAlgorithm_getClassName(self)

    def getInputProcessSample(self):
        r"""
        Accessor to the input sample.

        Returns
        -------
        inputSample : :class:`~openturns.ProcessSample`
            Input sample.
        """
        return _metamodel.FieldToPointFunctionalChaosAlgorithm_getInputProcessSample(self)

    def getOutputSample(self):
        r"""
        Accessor to the output sample.

        Returns
        -------
        outputSample : :class:`~openturns.Sample`
            Output sample.
        """
        return _metamodel.FieldToPointFunctionalChaosAlgorithm_getOutputSample(self)

    def setCenteredSample(self, centered):
        r"""
        Accessor to centered sample flag.

        Parameters
        ----------
        centered : bool
            Whether the input sample is centered.
            When set to True, it allows one to skip centering of the input process data.
        """
        return _metamodel.FieldToPointFunctionalChaosAlgorithm_setCenteredSample(self, centered)

    def getCenteredSample(self):
        r"""
        Accessor to centered sample flag.

        Parameters
        ----------
        centered : bool
            Whether the input sample is centered.
            When set to True, it allows one to skip centering of the input process data.
        """
        return _metamodel.FieldToPointFunctionalChaosAlgorithm_getCenteredSample(self)

    def setBlockIndices(self, blockIndices):
        r"""
        Accessor to the output block indices.

        Parameters
        ----------
        blockIndices : 2-d sequence of int
            Independent output components indices.
        """
        return _metamodel.FieldToPointFunctionalChaosAlgorithm_setBlockIndices(self, blockIndices)

    def __repr__(self):
        return _metamodel.FieldToPointFunctionalChaosAlgorithm___repr__(self)

    def run(self):
        r"""
        Compute the response surfaces.

        Notes
        -----
        It computes the response surfaces and creates a
        :class:`~openturns.MetaModelResult` structure containing all the results.
        """
        return _metamodel.FieldToPointFunctionalChaosAlgorithm_run(self)

    @staticmethod
    def BuildDistribution(modesSample):
        r"""
        Build the distribution of Karhunen-Loeve coefficients.

        This method aims at building a possibly parametric representation of
        Karhunen-Loeve coefficients based on their Gaussian or independent theoretical
        properties in order to build efficient metamodels.
        When this is not possible it falls back to non-parametric representations for
        the marginals and the dependence structure.

        Parameters
        ----------
        modesSample : :class:`~openturns.Sample`
            Karhunen-Loeve modes sample.

        Returns
        -------
        distribution : :class:`~openturns.Distribution`
            Distribution of coefficients.

        Notes
        -----
        The strategy for marginals is to test for a :class:`~openturns.Normal` hypothesis
        via the :py:meth:`~openturns.NormalityTest.CramerVonMisesNormal` test, else fallback to :class:`~openturns.Histogram`.

        For the dependence structure it tests for an :class:`~openturns.IndependentCopula`
        thanks to the :py:meth:`~openturns.HypothesisTest.Spearman` test, else fallback
        to the Normal or Beta copula (see :class:`~openturns.EmpiricalBernsteinCopula`)
        according to the :class:`~openturns.ResourceMap` key *FieldToPointFunctionalChaosAlgorithm-CopulaType*.
        """
        return _metamodel.FieldToPointFunctionalChaosAlgorithm_BuildDistribution(modesSample)

    def __init__(self, *args):
        _metamodel.FieldToPointFunctionalChaosAlgorithm_swiginit(self, _metamodel.new_FieldToPointFunctionalChaosAlgorithm(*args))
    __swig_destroy__ = _metamodel.delete_FieldToPointFunctionalChaosAlgorithm

# Register FieldToPointFunctionalChaosAlgorithm in _metamodel:
_metamodel.FieldToPointFunctionalChaosAlgorithm_swigregister(FieldToPointFunctionalChaosAlgorithm)
class FieldFunctionalChaosSobolIndices(openturns.common.PersistentObject):
    r"""
    Sobol indices from a functional decomposition.

    This class allows one to perform sensitivity analysis from field chaos decomposition.
    The process decomposition is done by Karhunen-Loeve and the modes interpolation
    is performed by functional chaos:

    .. math::

        \tilde{g}(x) = \sum_{k \in K_c} \beta_{\vect{\alpha}_k} \Psi_{\vect{\alpha}_k}(x)

    Let us expand the multi indices notation:

    .. math::

        \Psi_{\vect{\alpha}}(x) = \prod_{j=1}^{K_T} P^j_{\alpha_j}(x_j)

    with

    .. math::

        \vect{\alpha} \in \mathbb{N}^{K_T} = \{\underbrace{\alpha_1, \dots, \alpha_{K_1}}_{K_1},\dots,\underbrace{\alpha_{K_T-K_d}, \dots, \alpha_{K_T}}_{K_d}\}

    see :class:`~openturns.FunctionalChaosAlgorithm` for details.

    Sobol indices of the input field component :math:`j \in [1,d]` can be computed
    from the coefficients of the chaos decomposition that involve the
    matching Karhunen-Loeve coefficients.

    For the first order Sobol indices we sum over the multi-indices :math:`\vect{\alpha}_k`
    that are non-zero on the :math:`K_j` indices corresponding to the Karhunen-Loeve
    decomposition of j-th input and zero on the other :math:`K_T - K_j` indices (noted :math:`G_j`):

    .. math::

        S_j = \frac{\sum_{k=1, \vect{\alpha}_k \in G_j}^{K_c} \beta_{\vect{\alpha}_k}^2}{\sum_{k=1}^{K_c} \beta_{\vect{\alpha}_k}^2}

    For the total order Sobol indices we sum over the multi-indices :math:`\vect{\alpha}_k`
    that are non-zero on the :math:`K_j` indices corresponding to the Karhunen-Loeve
    decomposition of the j-th input (noted :math:`GT_j`):

    .. math::

        S_{T_j} = \frac{\sum_{k=1, \vect{\alpha}_k \in GT_j}^{K_c} \beta_{\vect{\alpha}_k}^2}{\sum_{k=1}^{K_c} \beta_{\vect{\alpha}_k}^2} 

    This generalizes to higher order indices.

    Parameters
    ----------
    result : :class:`openturns.FieldFunctionalChaosResult`
        Result.

    See also
    --------
    FieldToPointFunctionalChaosAlgorithm

    Examples
    --------
    >>> import openturns as ot
    >>> ot.RandomGenerator.SetSeed(0)
    >>> mesh = ot.RegularGrid(0.0, 0.1, 20)
    >>> cov = ot.KroneckerCovarianceModel(ot.MaternModel([2.0], 1.5), ot.CovarianceMatrix(4))
    >>> X = ot.GaussianProcess(cov, mesh)
    >>> x = X.getSample(500)
    >>> y = []
    >>> for xi in x:
    ...     m = xi.computeMean()
    ...     y.append([m[0] + m[1] + m[2] - m[3] + m[0] * m[1] - m[2] * m[3] - 0.1 * m[0] * m[1] * m[2]])
    >>> algo = ot.FieldToPointFunctionalChaosAlgorithm(x, y)
    >>> algo.setThreshold(4e-2)
    >>> # Temporarily lower the basis size for the sake of this example.
    >>> # We need to store the original size.
    >>> bs = ot.ResourceMap.GetAsUnsignedInteger('FunctionalChaosAlgorithm-BasisSize')
    >>> ot.ResourceMap.SetAsUnsignedInteger('FunctionalChaosAlgorithm-BasisSize', 100)
    >>> algo.run()
    >>> # The algorithm has been run with the lower basis size:
    >>> # we can now restore the original value.
    >>> ot.ResourceMap.SetAsUnsignedInteger('FunctionalChaosAlgorithm-BasisSize', bs)
    >>> result = algo.getResult()
    >>> sensitivity = ot.FieldFunctionalChaosSobolIndices(result)
    >>> sobol_1 = sensitivity.getFirstOrderIndices()
    >>> sobol_t = sensitivity.getTotalOrderIndices()

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.FieldFunctionalChaosSobolIndices_getClassName(self)

    def __repr__(self):
        return _metamodel.FieldFunctionalChaosSobolIndices___repr__(self)

    def getSobolIndex(self, *args):
        r"""
        Get a single Sobol index.

        Parameters
        ----------
        i : int or list of int
            Input index
        j : int, default=0
            Output index

        Returns
        -------
        s : float
            Sobol index
        """
        return _metamodel.FieldFunctionalChaosSobolIndices_getSobolIndex(self, *args)

    def getSobolTotalIndex(self, *args):
        r"""
        Get a single Sobol index.

        Parameters
        ----------
        i : int or list of int
            Input index
        j : int, default=0
            Output index

        Returns
        -------
        s : float
            Sobol index
        """
        return _metamodel.FieldFunctionalChaosSobolIndices_getSobolTotalIndex(self, *args)

    def getFirstOrderIndices(self, marginalIndex=0):
        r"""
        Get the first order Sobol indices.

        Parameters
        ----------
        j : int, default=0
            Output index

        Returns
        -------
        indices : :class:`~openturns.Point`
            First order Sobol indices
        """
        return _metamodel.FieldFunctionalChaosSobolIndices_getFirstOrderIndices(self, marginalIndex)

    def getTotalOrderIndices(self, marginalIndex=0):
        r"""
        Get the total order Sobol indices.

        Parameters
        ----------
        j : int, default=0
            Output index

        Returns
        -------
        indices : :class:`~openturns.Point`
            Total order Sobol indices
        """
        return _metamodel.FieldFunctionalChaosSobolIndices_getTotalOrderIndices(self, marginalIndex)

    def draw(self, marginalIndex=0):
        r"""
        Draw sensitivity indices.

        Parameters
        ----------
        marginalIndex : int, default=0
            Marginal index

        Returns
        -------
        graph : :class:`~openturns.Graph`
            A graph showing the first and total order indices per input.
        """
        return _metamodel.FieldFunctionalChaosSobolIndices_draw(self, marginalIndex)

    def __init__(self, *args):
        _metamodel.FieldFunctionalChaosSobolIndices_swiginit(self, _metamodel.new_FieldFunctionalChaosSobolIndices(*args))
    __swig_destroy__ = _metamodel.delete_FieldFunctionalChaosSobolIndices

# Register FieldFunctionalChaosSobolIndices in _metamodel:
_metamodel.FieldFunctionalChaosSobolIndices_swigregister(FieldFunctionalChaosSobolIndices)
class PointToFieldFunctionalChaosAlgorithm(FieldFunctionalChaosAlgorithm):
    r"""
    Functional metamodel algorithm based on chaos decomposition.

    The present algorithm makes it possible to build a response surface of the
    function :math:`h` defined by the equation:

    .. math::
        h: \left|
          \begin{array}{ccl}
             \Rset^p & \rightarrow & \cM_N \times (\Rset^d)^N \\
             \vect{X} & \mapsto & \mat{Y}
          \end{array}
        \right.

    with :math:`\cM_N` a mesh of :math:`\cD \subset \Rset^n`.

    The mapping :math:`h` is known from the :math:`N` vectors :math:`(\vect{X}_1, \dots, \vect{X}_N)`
    of the associated input random vector :math:`\vect{X}` and :math:`N` fields :math:`(\mat{Y}_1,\dots,\mat{Y}_N)`
    that fully characterize the output process :math:`\mat{Y}`.

    The linear projection function :math:`\pi_{ \vect{\lambda}, \vect{\varphi}}` of
    the Karhunen-Loeve decomposition by SVD is used to project the output fields
    (see :class:`~openturns.KarhunenLoeveSVDAlgorithm` and :class:`~openturns.KarhunenLoeveAlgorithm` for the notations):

    .. math::
        \pi_{\vect{\lambda}, \vect{\varphi}}: \left|
          \begin{array}{ccl}
            L^2(\cD, \Rset^d) & \rightarrow & \cS^{\Nset} \\
            f & \mapsto &\left(\dfrac{1}{\sqrt{\lambda_k}}\int_{\cD}f(\vect{t}) \vect{\varphi}_k(\vect{t})\, d\vect{t}\right)_{k \geq 1}
          \end{array}
        \right.

    where :math:`\cS^{\Nset}  = \left \{ (\zeta_k)_{k \geq 1} \in  \Rset^{\Nset} \, | \, \sum_{k=1}^{\infty}\lambda_k \zeta_k^2 < +\infty \right \}`.

    The Karhunen-Loeve algorithm allows one to replace this integral by a specific weighted and finite sum
    and to write the projections of the j-th marginal of i-th output field :math:`\mat{Y}_i^j` by multiplication
    with the projection matrix :math:`\mat{M}_j \in \Rset^{K_j} \times \Rset^{Nd}`:

    .. math::

        \mat{M}_j \mat{Y}_i^j = \left( \begin{array}{l} \xi_1^j \\ \vdots \\ \xi_{K_j}^j \end{array} \right)
        \in \Rset^{K_j}, \quad \forall i \in [1, n], \forall j \in [1, d]

    with :math:`K_j` the retained number of modes in the decomposition of the j-th output.
    The projections of all the :math:`d` components of :math:`n` fields are assembled in the :math:`\mat{Q}` matrix:

    .. math::

        \begin{align*}
            \mat{Q} = \mat{M} \mat{Y} =
            \left(
              \begin{array}{l}
                \mat{M}_1 \mat{Y}^1 \\
                \vdots \\
                \mat{M}_d \mat{Y}^d
              \end{array}
            \right) \in \Rset^{K_T} \times \Rset^n
         \end{align*}

    with :math:`K_T = \sum_{j=1}^d{K_j}` the total number of modes across output components.

    Then a functional chaos decomposition is built between the input samples :math:`\vect{X}`
    and the projected modes sample :math:`\mat{Q}`.
    The :class:`~openturns.ResourceMap` string entry `PointToFieldFunctionalChaosAlgorithm-Expansion`
    allows one to switch between :class:`~openturns.LeastSquaresExpansion` and :class:`~openturns.FunctionalChaosAlgorithm`.

    .. math::

        \tilde{g}(x) = \sum_{k=1}^{K_c} \beta_{\vect{\alpha}_k} \Psi_{\vect{\alpha}_k}(x)

    with :math:`K_c` the number of terms in the chaos decomposition.

    The final metamodel consists in the composition of the functional chaos metamodel
    and the Karhunen-Loeve projections.

    .. math::
        \tilde{h}: \left|
          \begin{array}{ccccl}
             \Rset^p & \rightarrow & \Rset^{K_T} & \rightarrow & \cM_N \times (\Rset^d)^N\\
             \vect{X} & \mapsto & \vect{Q} & \mapsto & \mat{Y}
          \end{array}
        \right.

    Here the projected modes sample has a dimension :math:`K_T` but being on the output side
    of the functional chaos expansion (FCE) this approach is not affected by the curse of dimensionality,
    it will just require as much FCE marginals runs.

    Parameters
    ----------
    x : :class:`~openturns.Sample`
        Input sample.
    y : :class:`~openturns.ProcessSample`
        Output process sample.
    distribution : :class:`~openturns.Distribution`
        Input distribution

    See Also
    --------
    FieldToPointFunctionalChaosAlgorithm
    FieldFunctionalChaosSobolIndices
    KarhunenLoeveAlgorithm
    FunctionalChaosAlgorithm

    Notes
    -----
    As the output process decomposition is done with the values decomposition approach,
    it is possible to control the number of modes retained per output,
    the idea being to avoid a large output dimension for the chaos decomposition step.
    As done in :class:`~openturns.KarhunenLoeveSVDAlgorithm`, the :func:`setThreshold`
    and :func:`setNbModes` methods allow one to control the spectrum ratio and maximum count.

    In the case of homogeneous data (if variables have the same unit or scale),
    it is also possible to recompress the modes at the global level with :func:`setRecompress`.
    When enabled, the eigenvalues are gathered and sorted so as to find a global
    spectrum cut-off value by which the spectrum of each output is truncated.
    The default value can be set through the :class:`~openturns.ResourceMap` key
    *FieldFunctionalChaosAlgorithm-DefaultRecompress*.

    For the chaos metamodel step, it is possible to specify the basis size with
    the :class:`~openturns.ResourceMap` key *FunctionalChaosAlgorithm-BasisSize*.

    It is possible to partition output variables into independent blocks with :func:`setBlockIndices`.
    This way Karhunen-Loeve process decompositions are done on each block rather
    than on all output variables at once (at the price of increased chaos decomposition output dimension)
    which then makes sensitivity analysis possible for each output variable
    or group of output variables.

    Examples
    --------
    >>> import openturns as ot
    >>> ot.RandomGenerator.SetSeed(0)
    >>> mesh = ot.RegularGrid(0.0, 0.1, 20)
    >>> X = ot.Normal(4)
    >>> x = X.getSample(50)
    >>> g = ot.SymbolicFunction(['t', 'x1', 'x2', 'x3', 'x4'], ['x1 + x2 * sin(t)', 'x2 + x3 * cos(t)', 'x4 * t'])
    >>> f = ot.VertexValuePointToFieldFunction(g, mesh)
    >>> y = f(x)
    >>> algo = ot.PointToFieldFunctionalChaosAlgorithm(x, y, X)
    >>> algo.setThreshold(4e-2)
    >>> # Temporarily lower the basis size for the sake of this example.
    >>> ot.ResourceMap.SetAsUnsignedInteger('FunctionalChaosAlgorithm-BasisSize', 100)
    >>> algo.run()
    >>> result = algo.getResult()
    >>> metamodel = result.getPointToFieldMetaModel()
    >>> y0hat = metamodel(x[0])
    >>> ot.ResourceMap.Reset()

    """

    thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")

    def getClassName(self):
        r"""
        Accessor to the object's name.

        Returns
        -------
        class_name : str
            The object class name (`object.__class__.__name__`).
        """
        return _metamodel.PointToFieldFunctionalChaosAlgorithm_getClassName(self)

    def getInputSample(self):
        r"""
        Accessor to the input sample.

        Returns
        -------
        inputSample : :class:`~openturns.Sample`
            Input sample.
        """
        return _metamodel.PointToFieldFunctionalChaosAlgorithm_getInputSample(self)

    def getOutputProcessSample(self):
        r"""
        Accessor to the output sample.

        Returns
        -------
        outputSample : :class:`~openturns.ProcessSample`
            Output sample.
        """
        return _metamodel.PointToFieldFunctionalChaosAlgorithm_getOutputProcessSample(self)

    def setBlockIndices(self, blockIndices):
        r"""
        Accessor to the output block indices.

        Parameters
        ----------
        blockIndices : 2-d sequence of int
            Independent output components indices.
        """
        return _metamodel.PointToFieldFunctionalChaosAlgorithm_setBlockIndices(self, blockIndices)

    def __repr__(self):
        return _metamodel.PointToFieldFunctionalChaosAlgorithm___repr__(self)

    def run(self):
        r"""
        Compute the response surfaces.

        Notes
        -----
        It computes the response surfaces and creates a
        :class:`~openturns.MetaModelResult` structure containing all the results.
        """
        return _metamodel.PointToFieldFunctionalChaosAlgorithm_run(self)

    def __init__(self, *args):
        _metamodel.PointToFieldFunctionalChaosAlgorithm_swiginit(self, _metamodel.new_PointToFieldFunctionalChaosAlgorithm(*args))
    __swig_destroy__ = _metamodel.delete_PointToFieldFunctionalChaosAlgorithm

# Register PointToFieldFunctionalChaosAlgorithm in _metamodel:
_metamodel.PointToFieldFunctionalChaosAlgorithm_swigregister(PointToFieldFunctionalChaosAlgorithm)

