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

"""otsubsetinverse module"""

from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
    raise RuntimeError("Python 2.7 or later required")

# Import the low-level C/C++ module
if __package__ or "." in __name__:
    from . import _otsubsetinverse
else:
    import _otsubsetinverse

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 == "thisown":
            self.this.own(value)
        elif name == "this":
            set(self, name, 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.diff
import openturns.optim
import openturns.experiment
import openturns.solver
import openturns.algo
import openturns.uncertainty
import openturns.model_copula
import openturns.randomvector
import openturns.dist_bundle1
import openturns.dist_bundle2
import openturns.weightedexperiment
import openturns.classification
import openturns.orthogonalbasis
import openturns.metamodel
import openturns.transformation
import openturns.analytical
import openturns.simulation
import openturns.stattests
import openturns.model_process
class SubsetInverseSamplingResult(openturns.simulation.ProbabilitySimulationResult):
    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 _otsubsetinverse.SubsetInverseSamplingResult_getClassName(self)

    def getCoefficientOfVariation(self):
        r"""
        Accessor to the coefficient of variation.

        Returns
        -------
        coefficient : float
            Coefficient of variation of the simulated sample which is equal to
            :math:`\sqrt{Var_e} / P_e` with :math:`Var_e` the variance estimate and
            :math:`P_e` the probability estimate.
        """
        return _otsubsetinverse.SubsetInverseSamplingResult_getCoefficientOfVariation(self)

    def __repr__(self):
        return _otsubsetinverse.SubsetInverseSamplingResult___repr__(self)

    def __init__(self, *args):
        _otsubsetinverse.SubsetInverseSamplingResult_swiginit(self, _otsubsetinverse.new_SubsetInverseSamplingResult(*args))
    __swig_destroy__ = _otsubsetinverse.delete_SubsetInverseSamplingResult

# Register SubsetInverseSamplingResult in _otsubsetinverse:
_otsubsetinverse.SubsetInverseSamplingResult_swigregister(SubsetInverseSamplingResult)

class SubsetInverseSampling(openturns.simulation.EventSimulation):
    r"""
    Subset inverse simulation.

    Parameters
    ----------
    event : :class:`~openturns.Event`
        Event we are computing the probability of. The threshold of the event is
        not used.
    targetProbability : float
        The wanted final probability.
    proposalRange : float, optional
        Proposal range length
    conditionalProbability : float, optional
        Value of :math:`P(F_i|F_{i-1})` between successive steps

    Notes
    -----
    The goal is to estimate the threshold of the following target probability :

    .. math::

        P_f = \int_{\mathcal D_f} f_{\uX}(\ux)\di{\ux}\\
            = \int_{\mathbb R^{n_X}} \mathbf{1}_{\{g(\ux,\underline{d}) \:\leq 0\: \}}f_{\uX}(\ux)\di{\ux}\\
            = \Prob {\{g(\uX,\underline{d}) \leq q\}}


    The idea of the subset simulation method is to replace simulating a
    rare failure event in the original probability space by a sequence of
    simulations of more frequent conditional events :math:`F_i` :

    .. math::

        F_1 \supset F_2 \supset \dots \supset F_m = F


    The original probability estimate rewrites :

    .. math::

        P_f = P(F_m) = P(\bigcap \limits_{i=1}^m F_i) = P(F_1) \prod_{i=2}^m P(F_i|F_{i-1})


    And each conditional subset failure region is chosen by setting the threshold
    :math:`g_i` so that :math:`P(F_i|F_{i-1})` leads to a conditional failure
    probability of order :math:`0.1` :

    .. math::

        F_i =\Prob {\{g(\uX,\underline{d}) \leq g_i\}}


    The conditional samples are generated by the means of Markov Chains,
    using the Metropolis Hastings algorithm.

    :math:`N` being the number of simulations per subset, and :math:`p_{0i}` the
    conditional probability of each subset event, and :math:`\gamma_i` the
    autocorrelation between Markov chain samples.

    .. math::

        \delta^2 = \sum_{i=1}^m \delta^2_i = \sum_{i=1}^m (1+\gamma_i) \frac{1-p_{0i}}{p_{0i}N}


    The first event :math:`F_1` not being conditional, :math:`\delta^2_1`
    expresses as the classic Monte Carlo c.o.v.

    Examples
    --------
    >>> import openturns as ot
    >>> import otsubsetinverse as otsi

    >>> ot.RandomGenerator.SetSeed(0)

    Create a performance function with an associated distribution.

    >>> limitState = ot.SymbolicFunction(['u1', 'u2'], ['u1-u2'])
    >>> dim = limitState.getInputDimension()
    >>> mean = ot.Point([7., 2.])
    >>> sigma = ot.Point(dim, 1.0)
    >>> R = ot.IdentityMatrix(dim)
    >>> myDistribution = ot.Normal(mean, sigma, R)
    >>> vect = ot.RandomVector(myDistribution)
    >>> output = ot.RandomVector(limitState, vect)

    Create an event with a fictional threshold value which will not be used.

    >>> myEvent = ot.Event(output, ot.Less(), 0.)

    Define the target probability for which the threshold will be computed.

    >>> targetProbability = 0.0002
    >>> mySS = otsi.SubsetInverseSampling(myEvent, targetProbability)
    >>> mySS.setMaximumOuterSampling(10000)
    >>> mySS.run()

    Get some results.

    >>> ResultSS = mySS.getResult()
    >>> print('Pf = {}'.format(ResultSS.getProbabilityEstimate()))
    Pf = 0.0002
    >>> print('Threshold = {}'.format(mySS.getThresholdPerStep()[-1]))
    Threshold = 0.0202715501987
    >>> print('Threshold confidence length = {}'.format(
    ...                         mySS.getThresholdConfidenceLength(0.90)))
    Threshold confidence length = 0.0244117131807

    See also
    --------
    openturns.Simulation
    """

    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 _otsubsetinverse.SubsetInverseSampling_getClassName(self)

    def getResult(self):
        r"""
        Accessor to the results.

        Returns
        -------
        results : :class:`~openturns.SimulationResult`
            Structure containing all the results obtained after simulation and created
            by the method :py:meth:`run`.
        """
        return _otsubsetinverse.SubsetInverseSampling_getResult(self)

    def setProposalRange(self, proposalRange):
        r"""
        Proposal range length accessor.

        Parameters
        ----------
        range : float
            Range length.
        """
        return _otsubsetinverse.SubsetInverseSampling_setProposalRange(self, proposalRange)

    def getProposalRange(self):
        r"""
        Proposal range length accessor.

        Returns
        -------
        range : float
            Range length.
        """
        return _otsubsetinverse.SubsetInverseSampling_getProposalRange(self)

    def setConditionalProbability(self, conditionalProbability):
        r"""
        Conditional probability accessor.

        Value of :math:`P(F_i|F_{i-1})` between successive steps.

        Parameters
        ----------
        prob : float
            Conditional probability value.
        """
        return _otsubsetinverse.SubsetInverseSampling_setConditionalProbability(self, conditionalProbability)

    def getConditionalProbability(self):
        r"""
        Conditional probability accessor.

        Value of :math:`P(F_i|F_{i-1})` between successive steps.

        Returns
        -------
        prob : float
            Conditional probability value.
        """
        return _otsubsetinverse.SubsetInverseSampling_getConditionalProbability(self)

    def setTargetProbability(self, targetProbability):
        r"""
        Final target probability accessor.

        Value of :math:`P(F_m)`.

        Parameters
        ----------
        prob : float
            Final target probability value.
        """
        return _otsubsetinverse.SubsetInverseSampling_setTargetProbability(self, targetProbability)

    def getTargetProbability(self):
        r"""
        Final target probability accessor.

        Value of :math:`P(F_m)`.

        Returns
        -------
        prob : float
            Final target probability value.
        """
        return _otsubsetinverse.SubsetInverseSampling_getTargetProbability(self)

    def getNumberOfSteps(self):
        r"""
        Subset steps number accesor.

        Returns
        -------
        n : int
            Number of subset steps.
        """
        return _otsubsetinverse.SubsetInverseSampling_getNumberOfSteps(self)

    def getThresholdConfidenceLength(self, *args):
        r"""
        Accessor to the confidence length of the threshold.

        Parameters
        ----------
        level : float, :math:`level \in ]0, 1[`
            Confidence level. By default, it is :math:`0.95`.

        Returns
        -------
        confidenceLength : float
            Length of the confidence interval at the confidence level *level*.
        """
        return _otsubsetinverse.SubsetInverseSampling_getThresholdConfidenceLength(self, *args)

    def getThresholdPerStep(self):
        r"""
        Threshold accessor.

        Returns
        -------
        threshold : :py:class:`openturns.Point`
            Threshold values.
        """
        return _otsubsetinverse.SubsetInverseSampling_getThresholdPerStep(self)

    def getGammaPerStep(self):
        r"""
        Autocorrelation accessor.

        Returns
        -------
        prob : :py:class:`openturns.Point`
            Autocorrelation values.
        """
        return _otsubsetinverse.SubsetInverseSampling_getGammaPerStep(self)

    def getCoefficientOfVariationPerStep(self):
        r"""
        Coefficient of variation per step accessor.

        Returns
        -------
        coef : :py:class:`openturns.Point`
            Coefficient of variation at each subset step.
        """
        return _otsubsetinverse.SubsetInverseSampling_getCoefficientOfVariationPerStep(self)

    def getProbabilityEstimatePerStep(self):
        r"""
        Probability estimate accessor.

        Returns
        -------
        prob : :py:class:`openturns.Point`
            Probability estimate values.
        """
        return _otsubsetinverse.SubsetInverseSampling_getProbabilityEstimatePerStep(self)

    def getThresholdCoefficientOfVariationPerStep(self):
        r"""
        Threshold coefficient of variation per step accessor.

        Returns
        -------
        coef : :py:class:`openturns.Point`
            Coefficient of variation at each subset step.
        """
        return _otsubsetinverse.SubsetInverseSampling_getThresholdCoefficientOfVariationPerStep(self)

    def setKeepEventSample(self, keepEventSample):
        r"""
        Sample storage accessor.

        Parameters
        ----------
        prob : bool
            Whether to keep the event samples.
        """
        return _otsubsetinverse.SubsetInverseSampling_setKeepEventSample(self, keepEventSample)

    def getEventInputSample(self):
        r"""
        Input sample accessor.

        Returns
        -------
        inputSample : :py:class:`openturns.Sample`
            Input sample.
        """
        return _otsubsetinverse.SubsetInverseSampling_getEventInputSample(self)

    def getEventOutputSample(self):
        r"""
        Output sample accessor.

        Returns
        -------
        outputSample : :py:class:`openturns.Sample`
            Ouput sample.
        """
        return _otsubsetinverse.SubsetInverseSampling_getEventOutputSample(self)

    def getOutputSample(self):
        r"""
        All output sample accessor.

        Returns
        -------
        outputSample : :py:class:`openturns.Sample`
            Output sample.
        """
        return _otsubsetinverse.SubsetInverseSampling_getOutputSample(self)

    def getInputSample(self):
        r"""
        All input sample accessor.

        Returns
        -------
        inputSample : :py:class:`openturns.Sample`
            Input sample.
        """
        return _otsubsetinverse.SubsetInverseSampling_getInputSample(self)

    def setISubset(self, iSubset):
        r"""
        Conditonal simulation activation accessor.

        Parameters
        ----------
        isubset : bool
            Activate or not the conditional simulation for the first step of the 
            simulation.
        """
        return _otsubsetinverse.SubsetInverseSampling_setISubset(self, iSubset)

    def setBetaMin(self, betaMin):
        r"""
        Radius of the hypershere accessor.

        Parameters
        ----------
        beta : float
            Radius value of the exclusion hypershere when the conditional simulation is activated.
        """
        return _otsubsetinverse.SubsetInverseSampling_setBetaMin(self, betaMin)

    def run(self):
        r"""
        Launch simulation.

        Notes
        -----
        It launches the simulation and creates a :class:`~openturns.SimulationResult`,
        structure containing all the results obtained after simulation.
        It computes the probability of occurence of the given event by computing the
        empirical mean of a sample of size at most *outerSampling * blockSize*,
        this sample being built by blocks of size *blockSize*. It allows to use
        efficiently the distribution of the computation as well as it allows to deal
        with a sample size :math:`> 2^{32}` by a combination of *blockSize* and
        *outerSampling*.

        see also
        --------
        setBlockSize, setMaximumOuterSampling, ResourceMap, SimulationResult
        """
        return _otsubsetinverse.SubsetInverseSampling_run(self)

    def __repr__(self):
        return _otsubsetinverse.SubsetInverseSampling___repr__(self)

    def __init__(self, *args):
        _otsubsetinverse.SubsetInverseSampling_swiginit(self, _otsubsetinverse.new_SubsetInverseSampling(*args))
    __swig_destroy__ = _otsubsetinverse.delete_SubsetInverseSampling

# Register SubsetInverseSampling in _otsubsetinverse:
_otsubsetinverse.SubsetInverseSampling_swigregister(SubsetInverseSampling)
cvar = _otsubsetinverse.cvar
SubsetInverseSampling.DefaultMaximumOuterSampling = _otsubsetinverse.cvar.SubsetInverseSampling_DefaultMaximumOuterSampling
SubsetInverseSampling.DefaultProposalRange = _otsubsetinverse.cvar.SubsetInverseSampling_DefaultProposalRange
SubsetInverseSampling.DefaultConditionalProbability = _otsubsetinverse.cvar.SubsetInverseSampling_DefaultConditionalProbability
SubsetInverseSampling.DefaultBetaMin = _otsubsetinverse.cvar.SubsetInverseSampling_DefaultBetaMin



