pyuncertainnumber.pba ===================== .. py:module:: pyuncertainnumber.pba Submodules ---------- .. toctree:: :maxdepth: 1 /autoapi/pyuncertainnumber/pba/aggregation/index /autoapi/pyuncertainnumber/pba/cbox/index /autoapi/pyuncertainnumber/pba/cbox_constructor/index /autoapi/pyuncertainnumber/pba/constructors/index /autoapi/pyuncertainnumber/pba/context/index /autoapi/pyuncertainnumber/pba/core/index /autoapi/pyuncertainnumber/pba/dependency/index /autoapi/pyuncertainnumber/pba/distributions/index /autoapi/pyuncertainnumber/pba/dss/index /autoapi/pyuncertainnumber/pba/ecdf/index /autoapi/pyuncertainnumber/pba/imprecise/index /autoapi/pyuncertainnumber/pba/intervals/index /autoapi/pyuncertainnumber/pba/mixins/index /autoapi/pyuncertainnumber/pba/operation/index /autoapi/pyuncertainnumber/pba/params/index /autoapi/pyuncertainnumber/pba/pbox_abc/index /autoapi/pyuncertainnumber/pba/pbox_free/index /autoapi/pyuncertainnumber/pba/pbox_parametric/index /autoapi/pyuncertainnumber/pba/utils/index Attributes ---------- .. autoapisummary:: pyuncertainnumber.pba.normal pyuncertainnumber.pba.gaussian pyuncertainnumber.pba.named_pbox pyuncertainnumber.pba.known_constraints Classes ------- .. autoapisummary:: pyuncertainnumber.pba.I pyuncertainnumber.pba.Pbox pyuncertainnumber.pba.Leaf pyuncertainnumber.pba.Params pyuncertainnumber.pba.DempsterShafer pyuncertainnumber.pba.DSS pyuncertainnumber.pba.D pyuncertainnumber.pba.Distribution pyuncertainnumber.pba.JointDistribution pyuncertainnumber.pba.ECDF pyuncertainnumber.pba.Dependency pyuncertainnumber.pba.eCDF_bundle pyuncertainnumber.pba.Interval pyuncertainnumber.pba.Staircase pyuncertainnumber.pba.Params Functions --------- .. autoapisummary:: pyuncertainnumber.pba.intervalise pyuncertainnumber.pba.load_interval_from_json pyuncertainnumber.pba.wc_scalar_interval pyuncertainnumber.pba.makePbox pyuncertainnumber.pba._bound_pcdf pyuncertainnumber.pba._parametric_bounds_array pyuncertainnumber.pba.norm pyuncertainnumber.pba.lognormal pyuncertainnumber.pba.alpha pyuncertainnumber.pba.anglit pyuncertainnumber.pba.argus pyuncertainnumber.pba.arcsine pyuncertainnumber.pba.beta pyuncertainnumber.pba.betaprime pyuncertainnumber.pba.bradford pyuncertainnumber.pba.burr pyuncertainnumber.pba.burr12 pyuncertainnumber.pba.cauchy pyuncertainnumber.pba.chi pyuncertainnumber.pba.chi2 pyuncertainnumber.pba.cosine pyuncertainnumber.pba.crystalball pyuncertainnumber.pba.dgamma pyuncertainnumber.pba.dweibull pyuncertainnumber.pba.erlang pyuncertainnumber.pba.exponnorm pyuncertainnumber.pba.exponential pyuncertainnumber.pba.exponweib pyuncertainnumber.pba.exponpow pyuncertainnumber.pba.f pyuncertainnumber.pba.fatiguelife pyuncertainnumber.pba.fisk pyuncertainnumber.pba.foldcauchy pyuncertainnumber.pba.foldnorm pyuncertainnumber.pba.genlogistic pyuncertainnumber.pba.gennorm pyuncertainnumber.pba.genpareto pyuncertainnumber.pba.genexpon pyuncertainnumber.pba.genextreme pyuncertainnumber.pba.gausshyper pyuncertainnumber.pba.gamma pyuncertainnumber.pba.gengamma pyuncertainnumber.pba.genhalflogistic pyuncertainnumber.pba.geninvgauss pyuncertainnumber.pba.gompertz pyuncertainnumber.pba.gumbel_r pyuncertainnumber.pba.gumbel_l pyuncertainnumber.pba.halfcauchy pyuncertainnumber.pba.halflogistic pyuncertainnumber.pba.halfnorm pyuncertainnumber.pba.halfgennorm pyuncertainnumber.pba.hypsecant pyuncertainnumber.pba.invgamma pyuncertainnumber.pba.invgauss pyuncertainnumber.pba.invweibull pyuncertainnumber.pba.irwinhall pyuncertainnumber.pba.jf_skew_t pyuncertainnumber.pba.johnsonsb pyuncertainnumber.pba.johnsonsu pyuncertainnumber.pba.kappa4 pyuncertainnumber.pba.kappa3 pyuncertainnumber.pba.ksone pyuncertainnumber.pba.kstwo pyuncertainnumber.pba.kstwobign pyuncertainnumber.pba.laplace pyuncertainnumber.pba.laplace_asymmetric pyuncertainnumber.pba.levy pyuncertainnumber.pba.levy_l pyuncertainnumber.pba.levy_stable pyuncertainnumber.pba.logistic pyuncertainnumber.pba.loggamma pyuncertainnumber.pba.loglaplace pyuncertainnumber.pba.loguniform pyuncertainnumber.pba.lomax pyuncertainnumber.pba.maxwell pyuncertainnumber.pba.mielke pyuncertainnumber.pba.moyal pyuncertainnumber.pba.nakagami pyuncertainnumber.pba.ncx2 pyuncertainnumber.pba.ncf pyuncertainnumber.pba.nct pyuncertainnumber.pba.norminvgauss pyuncertainnumber.pba.pareto pyuncertainnumber.pba.pearson3 pyuncertainnumber.pba.powerlaw pyuncertainnumber.pba.powerlognorm pyuncertainnumber.pba.powernorm pyuncertainnumber.pba.rdist pyuncertainnumber.pba.rayleigh pyuncertainnumber.pba.rel_breitwigner pyuncertainnumber.pba.rice pyuncertainnumber.pba.recipinvgauss pyuncertainnumber.pba.semicircular pyuncertainnumber.pba.skewcauchy pyuncertainnumber.pba.skewnorm pyuncertainnumber.pba.studentized_range pyuncertainnumber.pba.t pyuncertainnumber.pba.trapezoid pyuncertainnumber.pba.triang pyuncertainnumber.pba.truncweibull_min pyuncertainnumber.pba.tukeylambda pyuncertainnumber.pba.uniform_sps pyuncertainnumber.pba.vonmises pyuncertainnumber.pba.vonmises_line pyuncertainnumber.pba.wald pyuncertainnumber.pba.weibull_min pyuncertainnumber.pba.weibull_max pyuncertainnumber.pba.wrapcauchy pyuncertainnumber.pba.lognormal_weird pyuncertainnumber.pba.uniform pyuncertainnumber.pba.exponential_by_lambda pyuncertainnumber.pba.trapz pyuncertainnumber.pba.weibull pyuncertainnumber.pba.KM pyuncertainnumber.pba.KN pyuncertainnumber.pba.bernoulli pyuncertainnumber.pba.betabinom pyuncertainnumber.pba.betanbinom pyuncertainnumber.pba.binom pyuncertainnumber.pba.boltzmann pyuncertainnumber.pba.dlaplace pyuncertainnumber.pba.geom pyuncertainnumber.pba.hypergeom pyuncertainnumber.pba.logser pyuncertainnumber.pba.nbinom pyuncertainnumber.pba.nchypergeom_fisher pyuncertainnumber.pba.nchypergeom_wallenius pyuncertainnumber.pba.nhypergeom pyuncertainnumber.pba.planck pyuncertainnumber.pba.poisson pyuncertainnumber.pba.randint pyuncertainnumber.pba.skellam pyuncertainnumber.pba.yulesimon pyuncertainnumber.pba.zipf pyuncertainnumber.pba.zipfian pyuncertainnumber.pba.known_properties pyuncertainnumber.pba.min_max pyuncertainnumber.pba.min_max_mean pyuncertainnumber.pba.min_mean pyuncertainnumber.pba.min_max_mean_std pyuncertainnumber.pba.min_max_mean_var pyuncertainnumber.pba.min_max_mode pyuncertainnumber.pba.min_max_median pyuncertainnumber.pba.mean_std pyuncertainnumber.pba.mean_var pyuncertainnumber.pba.pos_mean_std pyuncertainnumber.pba.from_percentiles pyuncertainnumber.pba.KS_bounds pyuncertainnumber.pba.dependency pyuncertainnumber.pba.inspect_pbox pyuncertainnumber.pba.pbox_from_ecdf_bundle pyuncertainnumber.pba.get_ecdf pyuncertainnumber.pba.convert pyuncertainnumber.pba.make_vec_interval pyuncertainnumber.pba.reweighting pyuncertainnumber.pba.get_ecdf pyuncertainnumber.pba.convert pyuncertainnumber.pba.envelope pyuncertainnumber.pba.imposition pyuncertainnumber.pba.stochastic_mixture pyuncertainnumber.pba.stacking pyuncertainnumber.pba.mixture_pbox pyuncertainnumber.pba.mixture_ds pyuncertainnumber.pba.env_samples pyuncertainnumber.pba.env_ecdf_sep pyuncertainnumber.pba.env_am pyuncertainnumber.pba.env_pbox_am pyuncertainnumber.pba.KS_bounds Package Contents ---------------- .. py:class:: I(lo: Union[float, numpy.ndarray], hi: Optional[Union[float, numpy.ndarray]] = None, do_heavy_checks: bool = True) Bases: :py:obj:`pyuncertainnumber.pba.mixins.NominalValueMixin` Interval is the main class .. py:attribute:: _lo .. py:attribute:: _hi :value: None .. py:method:: run_heavy_checks() Run heavy checks on the interval object .. py:method:: __repr__() .. py:method:: __str__() .. py:method:: __len__() .. py:method:: __iter__() .. py:method:: __contains__(item) Check if an item is enclosed within the interval. .. rubric:: Example >>> i = Interval(1,3) >>> 2 in i True >>> 4 in i False .. py:method:: __next__() .. py:method:: __getitem__(i: Union[int, slice]) .. py:method:: to_numpy() -> numpy.ndarray transform interval objects to numpy arrays .. py:method:: to_pbox() .. py:method:: lhs_sample(n) -> numpy.ndarray LHS sampling within the interval :param n: number of samples .. py:method:: endpoints_lhs_sample(n) -> numpy.ndarray LHS sampling within the interval plus the endpoints :param n: number of samples .. py:method:: plot(ax=None, **kwargs) .. py:method:: display() .. py:method:: is_degenerate() -> bool Check if the interval is degenerate (i.e., has zero width). .. py:method:: _compute_nominal_value() .. py:method:: ravel() Return a flattened (1D) interval object for multi-dimensional intervals .. rubric:: Example >>> A = np.random.rand(200, 200, 2) >>> i = pba.intervalise(A) >>> print(i.shape) >>> i2 = i.ravel() >>> print(i2.shape) .. py:property:: lo :type: Union[numpy.ndarray, float] .. py:property:: hi :type: Union[numpy.ndarray, float] .. py:property:: left .. py:property:: right .. py:property:: width .. py:property:: rad half width .. py:property:: mid .. py:property:: unsized .. py:property:: val seemingly equivalent to `self.to_numpy()` .. py:property:: scalar Check if the interval is wide sense scalar .. note:: wide sense: I(1,2) and I([1],[2]) are both scalars .. py:property:: is_scalar Check if the interval is a strict-sense scalar .. note:: strict sense: I(1,2) is a scalar, but I([1],[2]) is not .. py:property:: shape .. py:property:: ndim .. py:method:: __neg__() .. py:method:: __pos__() .. py:method:: __add__(other) .. py:method:: __radd__(left) .. py:method:: __sub__(other) .. py:method:: __rsub__(left) .. py:method:: __mul__(other) .. py:method:: __rmul__(left) .. py:method:: __truediv__(other) .. py:method:: __rtruediv__(left) .. py:method:: __pow__(other) .. py:method:: __lt__(other) .. py:method:: __rlt__(left) .. py:method:: __gt__(other) .. py:method:: __rgt__(left) .. py:method:: __le__(other) .. py:method:: __rle__(left) .. py:method:: __ge__(other) .. py:method:: __rge__(left) .. py:method:: __eq__(other) .. py:method:: __ne__(other) .. py:method:: __array_ufunc__(ufunc, method, *inputs, **kwargs) .. py:method:: abs() .. py:method:: sqrt() .. py:method:: exp() .. py:method:: log() .. py:method:: sin() .. py:method:: cos() .. py:method:: tan() .. py:method:: from_meanform(x, half_width) :classmethod: .. py:method:: save_json(filename: str, comment: str = None, save_dir: str | pathlib.Path = '.') -> None Save the interval object to a JSON5 file. :param filename: The name of the file (without extension) to save the interval object to. :type filename: str :param comment: A comment to include at the top of the file. :type comment: str, optional :param save_dir: Directory where the file should be saved. Defaults to current directory. :type save_dir: str | Path, optional .. note:: The file is saved with a `.json5` extension. .. rubric:: Example >>> a.save_json("interval_data", comment="This is interval data", save_dir="results/") .. py:function:: intervalise(x_: Any, interval_index=-1) -> Union[pyuncertainnumber.pba.intervals.number.Interval, Any] This function casts an array-like structure into an Interval structure. All array-like structures will be first coerced into an ndarray of floats. If the coercion is unsuccessful the following error is thrown: `ValueError: setting an array element with a sequence.` For example this is the expected behaviour: (*) an ndarray of shape (4,2) will be cast as an Interval of shape (4,). (*) an ndarray of shape (7,3,2) will be cast as an Interval of shape (7,3). (*) an ndarray of shape (3,2,7) will be cast as a degenerate Interval of shape (3,2,7). (*) an ndarray of shape (2,3,7) will be cast as an Interval of shape (3,7). (*) an ndarray of shape (2,3,7,2) will be cast as an Interval of shape (2,3,7) if interval_index is set to -1. If an ndarray has shape with multiple dimensions having size 2, then the last dimension is intervalised. So, an ndarray of shape (7,2,2) will be cast as an Interval of shape (7,2) with the last dimension intervalised. When the ndarray has shape (2,2) again is the last dimension that gets intervalised. In case of ambiguity, e.g. (2,5,2), now the first dimension can be forced to be intervalised, selecting index=0, default is -1. It returns an interval only if the input is an array-like structure, otherwise it returns the following numpy error: `ValueError: setting an array element with a sequence.` TODO: Parse a list of mixed numbers: interval and ndarrays. .. py:function:: load_interval_from_json(filename: str) -> pyuncertainnumber.pba.intervals.number.Interval Load a NumPy array from a JSON file saved by save_array_to_json(). .. note:: Both .json and .json5 files are supported. .. rubric:: Example >>> interval = load_interval_from_json("interval_data.json5") .. py:class:: Pbox(left: numpy.ndarray | list, right: numpy.ndarray | list, steps=Params.steps, mean=None, var=None, p_values=None) Bases: :py:obj:`pyuncertainnumber.pba.mixins.NominalValueMixin`, :py:obj:`abc.ABC` a base class for Pbox .. danger:: this is an abstract class and should not be instantiated directly. .. seealso:: :class:`pbox_abc.Staircase` and :class:`pbox_abc.Leaf` for concrete implementations. .. py:property:: left .. py:property:: right .. py:attribute:: steps :value: 200 .. py:attribute:: mean :value: None .. py:attribute:: var :value: None .. py:attribute:: _pvalues .. py:method:: _init_moments() :abstractmethod: .. py:method:: _init_range() .. py:method:: post_init_check() .. py:method:: steps_check() .. py:method:: _compute_nominal_value() .. py:method:: degenerate_flag() -> bool check if the pbox is degenerate (i.e. left == right everywhere) .. py:property:: degenerate :type: bool .. py:property:: p_values .. py:property:: range .. py:property:: lo Returns the left-most value in the interval .. py:property:: hi Returns the right-most value in the interval .. py:property:: support .. py:property:: median .. py:property:: enclosed_area the enclosed area between the two extreme cdfs .. py:method:: __iter__() .. py:method:: __eq__(other) Equality operator for Pbox objects .. note:: - two pboxes are equal if their left and right bounds are equal .. py:method:: __contains__(item) .. py:method:: to_interval() discretise pbox into a vec-interval of length of default steps .. note:: If desired a custom length of vec-interval as output, use `discretise()` method. .. py:method:: to_dss(discretisation=Params.steps) convert pbox to DempsterShafer object .. py:method:: to_numpy() convert pbox to a 2D numpy array (n, 2) of left and right .. py:class:: Leaf(left=None, right=None, steps=200, mean=None, var=None, dist_params=None, shape=None) Bases: :py:obj:`Staircase` parametric pbox .. py:attribute:: shape :value: None .. py:attribute:: dist_params :value: None .. py:method:: _init_moments_range() .. py:method:: __repr__() .. py:method:: sample(n_sam) sample from a parametric pbox or distribution .. py:class:: Params .. py:attribute:: steps :value: 200 .. py:attribute:: many :value: 2000 .. py:attribute:: p_lboundary :value: 0.001 .. py:attribute:: p_hboundary :value: 0.999 .. py:attribute:: p_values .. py:attribute:: scott_hedged_interpretation .. py:attribute:: user_hedged_interpretation .. py:function:: wc_scalar_interval(bound) wildcard scalar interval This function is used to parse a scalar bound into an Interval object. It can handle various input types such as lists, tuples, and strings. If the input is a string, it attempts to interpret it using the `hedge_interpret` function or parse it as an interval expression. If the input is a single number, it creates an Interval with that number as both bounds. .. py:function:: makePbox(func) -> pyuncertainnumber.pba.pbox_abc.Pbox .. py:function:: _bound_pcdf(dist_family, *args, **kwargs) bound the parametric CDF .. note:: - top-level implemenatation - only support fully bounded parameters .. py:function:: _parametric_bounds_array(dist_family, *args, **kwargs) from parametric distribution specification to define the lower and upper bound of the p-box :param dist_family: (str) the name of the distribution :param \*args: several parameter (interval or list) :param \*\*kwargs: scale parameters (interval or list) .. note:: - middle level implementation .. py:function:: norm(*args) .. py:function:: lognormal(*args) .. py:function:: alpha(*args) .. py:function:: anglit(*args) .. py:function:: argus(*args) .. py:function:: arcsine(*args) .. py:function:: beta(*args) .. py:function:: betaprime(*args) .. py:function:: bradford(*args) .. py:function:: burr(*args) .. py:function:: burr12(*args) .. py:function:: cauchy(*args) .. py:function:: chi(*args) .. py:function:: chi2(*args) .. py:function:: cosine(*args) .. py:function:: crystalball(*args) .. py:function:: dgamma(*args) .. py:function:: dweibull(*args) .. py:function:: erlang(*args) .. py:function:: exponnorm(*args) .. py:function:: exponential(*args, **kwargs) The default p-box constructor for the exponential distribution with scale parameterisation .. note:: scale parameterisation due to scipy.stats. Note that the "scale" argument is a must. There is an "exponential_by_lambda" constructor which uses the rate parameterisation. .. rubric:: Example >>> pba.pbox_parametric.exponential(scale=[1, 2]) .. py:function:: exponweib(*args) .. py:function:: exponpow(*args) .. py:function:: f(*args) .. py:function:: fatiguelife(*args) .. py:function:: fisk(*args) .. py:function:: foldcauchy(*args) .. py:function:: foldnorm(mu, s, steps=Params.steps) .. py:function:: genlogistic(*args) .. py:function:: gennorm(*args) .. py:function:: genpareto(*args) .. py:function:: genexpon(*args) .. py:function:: genextreme(*args) .. py:function:: gausshyper(*args) .. py:function:: gamma(*args) .. py:function:: gengamma(*args) .. py:function:: genhalflogistic(*args) .. py:function:: geninvgauss(*args) .. py:function:: gompertz(*args) .. py:function:: gumbel_r(*args) .. py:function:: gumbel_l(*args) .. py:function:: halfcauchy(*args) .. py:function:: halflogistic(*args) .. py:function:: halfnorm(*args) .. py:function:: halfgennorm(*args) .. py:function:: hypsecant(*args) .. py:function:: invgamma(*args) .. py:function:: invgauss(*args) .. py:function:: invweibull(*args) .. py:function:: irwinhall(*args) .. py:function:: jf_skew_t(*args) .. py:function:: johnsonsb(*args) .. py:function:: johnsonsu(*args) .. py:function:: kappa4(*args) .. py:function:: kappa3(*args) .. py:function:: ksone(*args) .. py:function:: kstwo(*args) .. py:function:: kstwobign(*args) .. py:function:: laplace(*args) .. py:function:: laplace_asymmetric(*args) .. py:function:: levy(*args) .. py:function:: levy_l(*args) .. py:function:: levy_stable(*args) .. py:function:: logistic(*args) .. py:function:: loggamma(*args) .. py:function:: loglaplace(*args) .. py:function:: loguniform(*args) .. py:function:: lomax(*args) .. py:function:: maxwell(*args) .. py:function:: mielke(*args) .. py:function:: moyal(*args) .. py:function:: nakagami(*args) .. py:function:: ncx2(*args) .. py:function:: ncf(*args) .. py:function:: nct(*args) .. py:function:: norminvgauss(*args) .. py:function:: pareto(*args) .. py:function:: pearson3(*args) .. py:function:: powerlaw(*args) .. py:function:: powerlognorm(*args) .. py:function:: powernorm(*args) .. py:function:: rdist(*args) .. py:function:: rayleigh(*args, **kwargs) .. py:function:: rel_breitwigner(*args) .. py:function:: rice(*args) .. py:function:: recipinvgauss(*args) .. py:function:: semicircular(*args) .. py:function:: skewcauchy(*args) .. py:function:: skewnorm(*args) .. py:function:: studentized_range(*args) .. py:function:: t(*args) .. py:function:: trapezoid(*args) .. py:function:: triang(*args) .. py:function:: truncweibull_min(*args) .. py:function:: tukeylambda(*args) .. py:function:: uniform_sps(*args) .. py:function:: vonmises(*args) .. py:function:: vonmises_line(*args) .. py:function:: wald(*args) .. py:function:: weibull_min(*args) .. py:function:: weibull_max(*args) .. py:function:: wrapcauchy(*args) .. py:function:: lognormal_weird(mean, var, steps=Params.steps) p-box for the lognormal distribution *Note: the parameters used are the mean and variance of the lognormal distribution not the mean and variance of the underlying normal* See: `[1]` `[2]` :param mean: mean of the lognormal distribution :param var: variance of the lognormal distribution :rtype: Pbox .. py:function:: uniform(a, b, steps=Params.steps) special case of Uniform distribution as Scipy has an unbelivably strange parameterisation than common sense :param - a: (float) lower endpoint :param - b: (float) upper endpoints .. py:function:: exponential_by_lambda(lamb: list | pyuncertainnumber.pba.intervals.number.Interval) -> pyuncertainnumber.pba.pbox_abc.Pbox Bespoke p-box constructor for the exponential distribution :param - lamb: (list or Interval) the rate parameter of the exponential distribution .. py:function:: trapz(a, b, c, d, steps=Params.steps) .. py:function:: weibull(*args, steps=Params.steps) .. py:function:: KM(k, m, steps=Params.steps) .. py:function:: KN(k, n, steps=Params.steps) .. py:function:: bernoulli(*args) .. py:function:: betabinom(*args) .. py:function:: betanbinom(*args) .. py:function:: binom(*args) .. py:function:: boltzmann(*args) .. py:function:: dlaplace(*args) .. py:function:: geom(*args) .. py:function:: hypergeom(*args) .. py:function:: logser(*args) .. py:function:: nbinom(*args) .. py:function:: nchypergeom_fisher(*args) .. py:function:: nchypergeom_wallenius(*args) .. py:function:: nhypergeom(*args) .. py:function:: planck(*args) .. py:function:: poisson(*args) .. py:function:: randint(*args) .. py:function:: skellam(*args) .. py:function:: yulesimon(*args) .. py:function:: zipf(*args) .. py:function:: zipfian(*args) .. py:data:: normal .. py:data:: gaussian .. py:data:: named_pbox .. py:function:: known_properties(maximum=None, mean=None, median=None, minimum=None, mode=None, percentiles=None, std=None, var=None, family=None, **kwargs) -> pyuncertainnumber.characterisation.uncertainNumber.UncertainNumber Construct a uncertain number given known statistical properties served as constraints. :param maximum: maximum value of the variable :type maximum: number :param mean: mean value of the variable :type mean: number :param median: median value of the variable :type median: number :param minimum: minimum value of the variable :type minimum: number :param mode: mode value of the variable :type mode: number :param percentiles: dictionary of percentiles and their values, e.g. {0: 0, 0.1: 1, 0.5: 2, 0.9: pun.I(3,4), 1:5} :type percentiles: dict :param std: standard deviation of the variable :type std: number :param var: variance of the variable :type var: number :param family: name of the distribution family, e.g. 'normal', 'lognormal', 'uniform', 'triangular', etc. :type family: str :returns: uncertain number .. note:: It's also possible to directly call a function given the known information, such as ``pun.mean_std(mean=1, std=0.5)``. .. rubric:: Example >>> from pyuncertainnumber.pba import known_properties >>> known_properties( ... maximum = 2, ... mean = 1, ... var = 0.25, ... minimum=0, ... ) .. py:data:: known_constraints .. py:function:: min_max(minimum: numbers.Number, maximum: numbers.Number) -> pyuncertainnumber.characterisation.uncertainNumber.UncertainNumber | pyuncertainnumber.pba.pbox_abc.Pbox Equivalent to an interval object constructed as a nonparametric Pbox. :param minimum: Left end of box :param maximum: Right end of box :returns: UncertainNumber or Pbox .. tip:: Two types of return values are possible: - by default, a `UncertainNumber` is returned; - For low-level controls, if `return_construct=True` is specified, a `Pbox` is returned. .. rubric:: Example >>> from pyuncertainnumber.pba import min_max >>> min_max(0, 2) # return a UncertainNumber >>> min_max(0, 2, return_construct=True) # return a Pbox .. py:function:: min_max_mean(minimum: numbers.Number, maximum: numbers.Number, mean: numbers.Number, steps: int = Params.steps) -> pyuncertainnumber.characterisation.uncertainNumber.UncertainNumber | pyuncertainnumber.pba.pbox_abc.Pbox Generates a distribution-free p-box based upon the minimum, maximum and mean of the variable :param minimum: minimum value of the variable :type minimum: float :param maximum: maximum value of the variable :type maximum: float :param mean: mean value of the variable :type mean: float :returns: UncertainNumber or Pbox .. tip:: Two types of return values are possible: - by default, a `UncertainNumber` is returned; - For low-level controls, if `return_construct=True` is specified, a `Pbox` is returned. .. rubric:: Example >>> min_max_mean(0, 2, 1) .. py:function:: min_mean(minimum, mean, steps=Params.steps) -> pyuncertainnumber.characterisation.uncertainNumber.UncertainNumber | pyuncertainnumber.pba.pbox_abc.Pbox Nonparametric pbox construction based on constraint of minimum and mean :param minimum: minimum value of the variable :type minimum: number :param mean: mean value of the variable :type mean: number :returns: UncertainNumber or Pbox .. tip:: Two types of return values are possible: - by default, a `UncertainNumber` is returned; - For low-level controls, if `return_construct=True` is specified, a `Pbox` is returned. .. rubric:: Example >>> from pyuncertainnumber.pba import min_mean >>> min_mean(0, 1) # return a UncertainNumber >>> min_mean(0, 1, return_construct=True) # return a Pbox .. py:function:: min_max_mean_std(minimum: numbers.Number, maximum: numbers.Number, mean: numbers.Number, std: numbers.Number, **kwargs) -> pyuncertainnumber.characterisation.uncertainNumber.UncertainNumber | pyuncertainnumber.pba.pbox_abc.Pbox Generates a distribution-free p-box based upon the minimum, maximum, mean and standard deviation of the variable :param maximum: maximum value of the variable :type maximum: number :param minimum: minimum value of the variable :type minimum: number :param std: standard deviation of the variable :type std: number :param var: variance of the variable :type var: number :returns: UncertainNumber or Pbox .. tip:: Two types of return values are possible: - by default, a `UncertainNumber` is returned; - For low-level controls, if `return_construct=True` is specified, a `Pbox` is returned. .. rubric:: Example >>> min_max_mean_std(0, 2, 1, 0.5) # return a UncertainNumber .. seealso:: :func:`min_max_mean_var` .. py:function:: min_max_mean_var(minimum: numbers.Number, maximum: numbers.Number, mean: numbers.Number, var: numbers.Number, **kwargs) -> pyuncertainnumber.characterisation.uncertainNumber.UncertainNumber | pyuncertainnumber.pba.pbox_abc.Pbox Generates a distribution-free p-box based upon the minimum, maximum, mean and standard deviation of the variable :param minimum: minimum value of the variable :type minimum: number :param maximum: maximum value of the variable :type maximum: number :param mean: mean value of the variable :type mean: number :param var: variance of the variable :type var: number .. tip:: Two types of return values are possible: - by default, a `UncertainNumber` is returned; - For low-level controls, if `return_construct=True` is specified, a `Pbox` is returned. .. rubric:: Example >>> min_max_mean_var(0, 2, 1, 0.25) # return a UncertainNumber .. admonition:: Implementation Equivalent to ``min_max_mean_std(minimum,maximum,mean,np.sqrt(var))`` .. seealso:: :func:`min_max_mean_std` .. py:function:: min_max_mode(minimum: numbers.Number, maximum: numbers.Number, mode: numbers.Number, steps: int = Params.steps) -> pyuncertainnumber.characterisation.uncertainNumber.UncertainNumber | pyuncertainnumber.pba.pbox_abc.Pbox Nonparametric pbox construction based on constraint of mean and var :param minimum: minimum value of the variable :param maximum: maximum value of the variable :param mode: mode value of the variable :type mode: number :returns: UncertainNumber or Pbox .. tip:: Two types of return values are possible: - by default, a `UncertainNumber` is returned; - For low-level controls, if `return_construct=True` is specified, a `Pbox` is returned. .. rubric:: Example >>> min_max_mode(0, 2, 1) # return a UncertainNumber .. py:function:: min_max_median(minimum: numbers.Number, maximum: numbers.Number, median: numbers.Number, steps: int = Params.steps) -> pyuncertainnumber.characterisation.uncertainNumber.UncertainNumber | pyuncertainnumber.pba.pbox_abc.Pbox Generates a distribution-free p-box based upon the minimum, maximum and median of the variable :param minimum: minimum value of the variable :param maximum: maximum value of the variable :param median: median value of the variable :returns: UncertainNumber or Pbox .. tip:: Two types of return values are possible: - by default, a `UncertainNumber` is returned; - For low-level controls, if `return_construct=True` is specified, a `Pbox` is returned. .. rubric:: Example >>> min_max_median(0, 2, 1) # return a UncertainNumber .. py:function:: mean_std(mean: numbers.Number, std: numbers.Number, steps=Params.steps) -> pyuncertainnumber.characterisation.uncertainNumber.UncertainNumber | pyuncertainnumber.pba.pbox_abc.Pbox Nonparametric pbox construction based on constraint of mean and std :param mean: mean value of the variable :type mean: number :param std: std value of the variable :type std: number :returns: UncertainNumber or Pbox .. tip:: Two types of return values are possible: - by default, a `UncertainNumber` is returned; - For low-level controls, if `return_construct=True` is specified, a `Pbox` is returned. .. rubric:: Example >>> mean_std(1, 0.5) .. py:function:: mean_var(mean: numbers.Number, var: numbers.Number) -> pyuncertainnumber.characterisation.uncertainNumber.UncertainNumber | pyuncertainnumber.pba.pbox_abc.Pbox Nonparametric pbox construction based on constraint of mean and var :param mean: mean value of the variable :type mean: number :param vasr: var value of the variable :type vasr: number :returns: UncertainNumber or Pbox .. tip:: Two types of return values are possible: - by default, a `UncertainNumber` is returned; - For low-level controls, if `return_construct=True` is specified, a `Pbox` is returned. .. rubric:: Example >>> mean_var(1, 0.25) # return a UncertainNumber .. py:function:: pos_mean_std(mean: numbers.Number, std: numbers.Number, steps=Params.steps) -> pyuncertainnumber.pba.pbox_abc.Pbox Generates a positive distribution-free p-box based upon the mean and standard deviation of the variable :param mean: mean of the variable :param std: standard deviation of the variable :returns: UncertainNumber or Pbox .. tip:: Two types of return values are possible: - by default, a `UncertainNumber` is returned; - For low-level controls, if `return_construct=True` is specified, a `Pbox` is returned. .. py:function:: from_percentiles(percentiles: dict, steps: int = Params.steps) -> pyuncertainnumber.characterisation.uncertainNumber.UncertainNumber | pyuncertainnumber.pba.pbox_abc.Pbox yields a distribution-free p-box based on specified percentiles of the variable :param percentiles: dictionary of percentiles and their values (e.g. {0: 0, 0.1: 1, 0.5: 2, 0.9: I(3,4), 1:5}) :param steps: number of steps to use in the p-box .. note:: The percentiles dictionary is of the form {percentile: value}. Where value can either be a number or an I. If value is a number, the percentile is assumed to be a point percentile. If value is an I, the percentile is assumed to be an interval percentile. If no keys for 0 and 1 are given, ``-np.inf`` and ``np.inf`` are used respectively. This will result in a p-box that is not bounded and raise a warning. If the percentiles are not increasing, the percentiles will be intersected. This may not be desired behaviour. ValueError: If any of the percentiles are not between 0 and 1. :returns: UncertainNumber or Pbox .. tip:: Two types of return values are possible: - by default, a `UncertainNumber` is returned; - For low-level controls, if `return_construct=True` is specified, a `Pbox` is returned. .. rubric:: Example >>> pba.from_percentiles( >>> {0: 0, >>> 0.25: 0.5, >>> 0.5: pba.I(1,2), >>> 0.75: pba.I(1.5,2.5), >>> 1: 3}) >>> .display() .. py:function:: KS_bounds(s: numpy.typing.ArrayLike, alpha: float, display=True, output_type='bounds') -> Union[tuple[pyuncertainnumber.pba.ecdf.eCDF_bundle], pyuncertainnumber.pba.pbox_abc.Pbox, pyuncertainnumber.UncertainNumber] construct free pbox from sample data by Kolmogorov-Smirnoff confidence bounds :param s: sample data, precise and imprecise :type s: ArrayLike :param dn: KS critical value at a significance level and sample size N; :type dn: float :param output_type: A choice between {'bounds', 'pbox', 'un'}, default='bounds' which returns two eCDF bundles as bounds; 'pbox' to return a pbox object; 'un' to return an uncertain number object. :type output_type: str :returns: a tuple of two CDF bounds, i.e. upper and lower (eCDF_bundle objects), or a Pbox object, or an UncertainNumber object the return type is controlled by the `output_type` argument. .. note:: By default the function returns two eCDF bundles as the extreme bounds. With the upper and lower bounds, a free pbox can be constructed. .. rubric:: Example >>> # both precise data (e.g. numpy array) and imprecise data (e.g. a vector of interval) are supported >>> precise_data = np.random.normal(0, 1, 100) # precise data case >>> ub, lb = pba.KS_bounds(precise_data, alpha=0.025, display=True) >>> # alternatively, an uncertain number or a p-box can be returned >>> pba.KS_bounds(precise_data, alpha=0.025, display=False, output_type='pbox') # return a pbox object >>> pba.KS_bounds(precise_data, alpha=0.025, display=False, output_type='un') # return an uncertain number object >>> # imprecise data case >>> impre_data = pba.I(lo = precise_data -0.5, hi = precise_data + 0.5) >>> ub, lb = pba.KS_bounds(impre_data, alpha=0.025, display=True) .. figure:: /_static/ks_bounds_demo.png :alt: ks_bounds :align: center :width: 50% Kolmogorov-Smirnoff confidence bounds illustration with precise and imprecise data. .. py:class:: DempsterShafer(intervals: pyuncertainnumber.pba.intervals.Interval | list[list] | list[pyuncertainnumber.pba.intervals.Interval] | numpy.ndarray, masses: numpy.typing.ArrayLike) Bases: :py:obj:`pyuncertainnumber.pba.mixins.NominalValueMixin`, :py:obj:`pyuncertainnumber.pba.mixins._PboxOpsMixin` Class for Dempester-Shafer structures. :param intervals: expect wildcard vector intervals, vec-Interval; list of scalar intervals; list of list pairs; or 2D array; :param masses: probability masses :type masses: ArrayLike .. rubric:: Example >>> from pyuncertainnumber import pba >>> dss = pba.DempsterShafer(intervals=[[1,5], [3,6]], masses=[0.5, 0.5]) >>> dss.structures [dempstershafer_element(interval=[1.0,5.0], mass=0.5), dempstershafer_element(interval=[3.0,6.0], mass=0.5)] .. note:: Dempster-Shafer structures are also called belief structures or evidence structures, and it can be converted to p-boxes. .. figure:: /_static/dss_pbox_illustration.png :alt: p-box and DSS illustration :align: center :width: 80% P-box and Dempster Shafer structure illustration. .. py:attribute:: _intervals .. py:attribute:: _masses .. py:method:: _create_DSstructure() .. py:method:: __repr__() .. py:method:: _compute_nominal_value() .. py:property:: structures .. py:property:: intervals Returns the Interval-typed focal elements of the Dempster-Shafer structure. .. py:property:: focal_elements Returns the focal elements of the Dempster-Shafer structure. .. py:property:: masses .. py:method:: plot(style='raw', ax=None, zorder=None, **kwargs) for box type transform dss into a pbox and plot :param style: "raw" (default), "box", "pbox", "interval" :type style: str :param edge_color: edge color for raw style. If None, use default red color. :type edge_color: str .. py:method:: display(style='box', ax=None, **kwargs) .. py:method:: to_pbox() .. py:method:: _to_pbox() for mixin use only .. py:method:: from_dsElements(*ds_elements: dempstershafer_element) :classmethod: Create a Dempster-Shafer structure from a list of Dempster-Shafer elements. .. py:class:: DSS(intervals: pyuncertainnumber.pba.intervals.Interval | list[list] | list[pyuncertainnumber.pba.intervals.Interval] | numpy.ndarray, masses: numpy.typing.ArrayLike) Bases: :py:obj:`pyuncertainnumber.pba.mixins.NominalValueMixin`, :py:obj:`pyuncertainnumber.pba.mixins._PboxOpsMixin` Class for Dempester-Shafer structures. :param intervals: expect wildcard vector intervals, vec-Interval; list of scalar intervals; list of list pairs; or 2D array; :param masses: probability masses :type masses: ArrayLike .. rubric:: Example >>> from pyuncertainnumber import pba >>> dss = pba.DempsterShafer(intervals=[[1,5], [3,6]], masses=[0.5, 0.5]) >>> dss.structures [dempstershafer_element(interval=[1.0,5.0], mass=0.5), dempstershafer_element(interval=[3.0,6.0], mass=0.5)] .. note:: Dempster-Shafer structures are also called belief structures or evidence structures, and it can be converted to p-boxes. .. figure:: /_static/dss_pbox_illustration.png :alt: p-box and DSS illustration :align: center :width: 80% P-box and Dempster Shafer structure illustration. .. py:attribute:: _intervals .. py:attribute:: _masses .. py:method:: _create_DSstructure() .. py:method:: __repr__() .. py:method:: _compute_nominal_value() .. py:property:: structures .. py:property:: intervals Returns the Interval-typed focal elements of the Dempster-Shafer structure. .. py:property:: focal_elements Returns the focal elements of the Dempster-Shafer structure. .. py:property:: masses .. py:method:: plot(style='raw', ax=None, zorder=None, **kwargs) for box type transform dss into a pbox and plot :param style: "raw" (default), "box", "pbox", "interval" :type style: str :param edge_color: edge color for raw style. If None, use default red color. :type edge_color: str .. py:method:: display(style='box', ax=None, **kwargs) .. py:method:: to_pbox() .. py:method:: _to_pbox() for mixin use only .. py:method:: from_dsElements(*ds_elements: dempstershafer_element) :classmethod: Create a Dempster-Shafer structure from a list of Dempster-Shafer elements. .. py:class:: D Bases: :py:obj:`pyuncertainnumber.pba.mixins.NominalValueMixin` Two signatures are currentlly supported, either a parametric specification or from a nonparametric empirical data set. .. note:: the nonparametric instasntiation via arrtribute `empirical_data` will be deprecated soon. We have introduced a :class:`distributions.ECDF` class instead. .. rubric:: Example >>> d = Distribution('gaussian', (0,1)) .. py:attribute:: dist_family :type: str :value: None .. py:attribute:: dist_params :type: list[float] | tuple[float, Ellipsis] :value: None .. py:attribute:: empirical_data :type: list[float] | numpy.ndarray :value: None .. py:attribute:: skip_post :type: bool :value: False .. py:method:: __post_init__() .. py:method:: __repr__() .. py:method:: rep() Create the underling dist object either sps dist or sample approximated or pbox dist .. note:: underlying constructor to create the scipy.stats distribution object .. py:method:: _match_distribution() match the distribution object based on the family and parameters .. py:method:: parse_params_from_dist() .. py:method:: flag() boolean flag for if the distribution is a parameterised distribution or not .. note:: - only parameterised dist can do sampling - for non-parameterised sample-data based dist, next steps could be fitting .. py:method:: sample(size) generate deviates from the distribution .. py:method:: generate_rns(N) generate 'N' random numbers from the distribution .. py:method:: alpha_cut(alpha) alpha cut interface .. py:method:: make_nominal_value() one value representation of the distribution .. note:: - use mean for now; .. py:method:: plot(**kwargs) display the distribution .. py:method:: display(**kwargs) .. py:method:: _get_hint() .. py:method:: fit(data) fit the distribution to the data .. py:method:: get_PI(alpha: numbers.Number = 0.95) -> pyuncertainnumber.Interval Compute the predictive interval at the coverage level of `alpha` :param - alpha: coverage level, default is 0.95 :type - alpha: float .. rubric:: Example >>> from pyuncertainnumber import pba >>> d = pba.Distribution('gaussian', (0, 1)) >>> pi = d.get_PI(alpha=0.95) >>> print(pi) # prints the interval at the 95% coverage level .. py:method:: pdf(x: numpy.typing.ArrayLike) compute the probability density function (pdf) at x .. py:method:: log_pdf_eval(x: numpy.typing.ArrayLike) compute the log of probability density function (pdf) at x .. py:method:: cdf(x: numpy.typing.ArrayLike) compute the cumulative distribution function (cdf) at x .. py:method:: get_whole_cdf() return the cumulative distribution function (cdf) .. py:method:: _compute_nominal_value() .. py:property:: dist the underlying sps.dist object .. py:property:: lo .. py:property:: hi .. py:property:: range .. py:property:: hint .. py:method:: dist_from_sps(dist: scipy.stats.rv_continuous | scipy.stats.rv_discrete, shape: str = None) :classmethod: .. py:method:: to_pbox() convert the distribution to a pbox .. note:: - this only works for parameteried distributions for now - later on work with sample-approximated dist until `fit()`is implemented .. py:method:: __neg__() .. py:method:: __add__(other) .. py:method:: __radd__(other) .. py:method:: __sub__(other) .. py:method:: __rsub__(other) .. py:method:: __mul__(other) .. py:method:: __rmul__(other) .. py:method:: __truediv__(other) .. py:method:: __rtruediv__(other) .. py:method:: __pow__(other) .. py:method:: __rpow__(other) .. py:class:: Distribution Bases: :py:obj:`pyuncertainnumber.pba.mixins.NominalValueMixin` Two signatures are currentlly supported, either a parametric specification or from a nonparametric empirical data set. .. note:: the nonparametric instasntiation via arrtribute `empirical_data` will be deprecated soon. We have introduced a :class:`distributions.ECDF` class instead. .. rubric:: Example >>> d = Distribution('gaussian', (0,1)) .. py:attribute:: dist_family :type: str :value: None .. py:attribute:: dist_params :type: list[float] | tuple[float, Ellipsis] :value: None .. py:attribute:: empirical_data :type: list[float] | numpy.ndarray :value: None .. py:attribute:: skip_post :type: bool :value: False .. py:method:: __post_init__() .. py:method:: __repr__() .. py:method:: rep() Create the underling dist object either sps dist or sample approximated or pbox dist .. note:: underlying constructor to create the scipy.stats distribution object .. py:method:: _match_distribution() match the distribution object based on the family and parameters .. py:method:: parse_params_from_dist() .. py:method:: flag() boolean flag for if the distribution is a parameterised distribution or not .. note:: - only parameterised dist can do sampling - for non-parameterised sample-data based dist, next steps could be fitting .. py:method:: sample(size) generate deviates from the distribution .. py:method:: generate_rns(N) generate 'N' random numbers from the distribution .. py:method:: alpha_cut(alpha) alpha cut interface .. py:method:: make_nominal_value() one value representation of the distribution .. note:: - use mean for now; .. py:method:: plot(**kwargs) display the distribution .. py:method:: display(**kwargs) .. py:method:: _get_hint() .. py:method:: fit(data) fit the distribution to the data .. py:method:: get_PI(alpha: numbers.Number = 0.95) -> pyuncertainnumber.Interval Compute the predictive interval at the coverage level of `alpha` :param - alpha: coverage level, default is 0.95 :type - alpha: float .. rubric:: Example >>> from pyuncertainnumber import pba >>> d = pba.Distribution('gaussian', (0, 1)) >>> pi = d.get_PI(alpha=0.95) >>> print(pi) # prints the interval at the 95% coverage level .. py:method:: pdf(x: numpy.typing.ArrayLike) compute the probability density function (pdf) at x .. py:method:: log_pdf_eval(x: numpy.typing.ArrayLike) compute the log of probability density function (pdf) at x .. py:method:: cdf(x: numpy.typing.ArrayLike) compute the cumulative distribution function (cdf) at x .. py:method:: get_whole_cdf() return the cumulative distribution function (cdf) .. py:method:: _compute_nominal_value() .. py:property:: dist the underlying sps.dist object .. py:property:: lo .. py:property:: hi .. py:property:: range .. py:property:: hint .. py:method:: dist_from_sps(dist: scipy.stats.rv_continuous | scipy.stats.rv_discrete, shape: str = None) :classmethod: .. py:method:: to_pbox() convert the distribution to a pbox .. note:: - this only works for parameteried distributions for now - later on work with sample-approximated dist until `fit()`is implemented .. py:method:: __neg__() .. py:method:: __add__(other) .. py:method:: __radd__(other) .. py:method:: __sub__(other) .. py:method:: __rsub__(other) .. py:method:: __mul__(other) .. py:method:: __rmul__(other) .. py:method:: __truediv__(other) .. py:method:: __rtruediv__(other) .. py:method:: __pow__(other) .. py:method:: __rpow__(other) .. py:class:: JointDistribution(copula: pyuncertainnumber.pba.dependency.Dependency, marginals: list[Distribution]) Joint distribution class .. rubric:: Example >>> from pyuncertainnumber import pba >>> dist_a, dist_b = pba.Distribution('gaussian', (5,1)), pba.Distribution('uniform', (2, 3)) >>> c = pba.Dependency('gaussian', params=0.8) >>> joint_dist = pba.JointDistribution(copula=c, marginals=[dist_a, dist_b]) >>> samples = joint_dist.sample(size=1000) .. py:attribute:: marginals .. py:attribute:: copula .. py:attribute:: _joint_dist .. py:attribute:: ndim .. py:method:: __repr__() .. py:method:: from_sps(copula: statsmodels.distributions.copula, marginals: list[scipy.stats.rv_continuous]) :staticmethod: .. py:method:: sample(size, random_state=42) generate orginal-space samples from the joint distribution .. py:method:: u_sample(size, random_state=42) generate copula-space samples from the joint distribution .. py:method:: joint_density_of_bi_grid(x: numpy.typing.ArrayLike, y: numpy.typing.ArrayLike) compute the joint density on a grid given x and y arrays Used for bivariate arithmetic calculations of X and Y with designated (known) dependency and marginals. .. note:: discretisation step sizes dx and dy are set up by the input x and y arrays .. rubric:: Example >>> x = np.linspace(0, 1, 50) >>> y = np.linspace(0, 1, 50) >>> dep = Dependency("gaussian", params=0.7) >>> joint_density = dep.joint_density_of_grid(x, y) .. py:method:: cdf_of_g(XX, YY, fXY, dx, dy, g_func, z_vals) -> numpy.typing.ArrayLike :staticmethod: Numerically approximate F_Z(z) = P(g(X,Y) <= z) via discretisation on a grid :param z_vals: discretisation of z values (array) at which to compute F_Z :type z_vals: ArrayLike :param XX: the grid arrays from meshgrid :param YY: the grid arrays from meshgrid :param fXY: joint density on the grid :param dx: spacings in x and y directions :param dy: spacings in x and y directions :param g_func: a general callable applied elementwise to (XX, YY) :type g_func: callable :returns: cumulative distribution function values at z_vals :rtype: FZ (ArrayLike) .. note:: given precomputed grid (XX,YY), joint density fXY, and spacings. .. py:class:: ECDF(empirical_data: numpy.ndarray) Bases: :py:obj:`pyuncertainnumber.pba.pbox_abc.Staircase` Empirical cumulative distribution function (ecdf) class .. admonition:: Implementation supported by `Pbox` API hence samples will be degenerate intervals .. rubric:: Example >>> import numpy as np >>> s = np.random.normal(size=1000) >>> ecdf = ECDF(s) >>> ecdf.plot() .. py:class:: Dependency(family: str, params: numbers.Number | None = None, **kwargs) Dependency class to specify copula models. :param family: Name of the copula family, one of "gaussian", "t", "frank", "gumbel", "clayton", "independence". :type family: str :param params: Backward-compatible single-parameter shortcut: - gaussian/t: interpreted as corr - frank/gumbel/clayton: interpreted as theta - independence: ignored :type params: Number | None :param \*\*kwargs: Any keyword parameters supported by the selected copula, e.g. corr=..., df=..., theta=..., k_dim=..., allow_singular=... .. rubric:: Examples >>> Dependency("gaussian", params=0.8, k_dim=3) # legacy style >>> Dependency("gaussian", corr=0.8, k_dim=3) # explicit >>> Dependency("t", corr=0.6, df=5, k_dim=4) >>> Dependency("frank", theta=2.5, k_dim=2) >>> Dependency("independence", k_dim=5) .. py:attribute:: copulas_dict .. py:attribute:: _single_param_alias .. py:attribute:: family :value: '' .. py:attribute:: params :value: None .. py:attribute:: _copula .. py:property:: copula Access the underlying statsmodels copula instance. .. py:method:: _post_init_check() .. py:method:: __repr__() .. py:method:: pdf(u) .. py:method:: cdf(u) .. py:method:: u_sample(n: int, random_state=None) draws n samples in the U space (unit hypercube) .. py:method:: display(style='3d_cdf', ax=None) show the PDF or CDF in the u space .. py:method:: fit(data) .. py:function:: dependency(dep_type: str) Context manager to temporarily change arithmetic dependency ('f', 'p', 'o', or 'i') .. py:function:: inspect_pbox(pbox) quickly inspect a pbox object .. py:function:: pbox_from_ecdf_bundle(lower_bound: pyuncertainnumber.pba.ecdf.eCDF_bundle, upper_bound: pyuncertainnumber.pba.ecdf.eCDF_bundle) -> Pbox Construct a p-box from two empirical CDF bundles as the extreme bounds .. py:function:: get_ecdf(s, w=None, display=False) -> tuple compute the weighted ecdf from (precise) sample data :param s: 1 dimensional precise sample data :type s: array-like :param w: weights :type w: array-like .. note:: - Sudret eq.1 :returns: ecdf in the form of a tuple of q and p .. py:function:: convert(un) Convert any input un into a Pbox object .. note:: - theorically 'un' can be {Interval, DempsterShafer, Distribution, float, int} .. py:function:: make_vec_interval(vec) parse an array-like structure into a vector interval For most part, it works same to `intervalise`, except that this function can also handle a list of UN objects. .. rubric:: Example >>> a, b = pba.I(1, 2), pba.I(3, 4) >>> make_vec_interval([a, b]) Interval([1, 3], [2, 4]) .. py:function:: reweighting(*masses) reweight the masses to sum to 1 .. py:class:: eCDF_bundle a handy tuple of eCDF function q and p .. py:attribute:: quantiles :type: numpy.ndarray .. py:attribute:: probabilities :type: numpy.ndarray .. py:method:: __repr__() .. py:method:: from_sps_ecdf(e) :classmethod: utility to tranform sps.ecdf to eCDF_bundle .. py:method:: plot_bounds(other) plot the lower and upper bounds .. py:function:: get_ecdf(s, w=None, display=False) -> tuple compute the weighted ecdf from (precise) sample data :param s: 1 dimensional precise sample data :type s: array-like :param w: weights :type w: array-like .. note:: - Sudret eq.1 :returns: ecdf in the form of a tuple of q and p .. py:class:: Interval(lo: Union[float, numpy.ndarray], hi: Optional[Union[float, numpy.ndarray]] = None, do_heavy_checks: bool = True) Bases: :py:obj:`pyuncertainnumber.pba.mixins.NominalValueMixin` Interval is the main class .. py:attribute:: _lo .. py:attribute:: _hi :value: None .. py:method:: run_heavy_checks() Run heavy checks on the interval object .. py:method:: __repr__() .. py:method:: __str__() .. py:method:: __len__() .. py:method:: __iter__() .. py:method:: __contains__(item) Check if an item is enclosed within the interval. .. rubric:: Example >>> i = Interval(1,3) >>> 2 in i True >>> 4 in i False .. py:method:: __next__() .. py:method:: __getitem__(i: Union[int, slice]) .. py:method:: to_numpy() -> numpy.ndarray transform interval objects to numpy arrays .. py:method:: to_pbox() .. py:method:: lhs_sample(n) -> numpy.ndarray LHS sampling within the interval :param n: number of samples .. py:method:: endpoints_lhs_sample(n) -> numpy.ndarray LHS sampling within the interval plus the endpoints :param n: number of samples .. py:method:: plot(ax=None, **kwargs) .. py:method:: display() .. py:method:: is_degenerate() -> bool Check if the interval is degenerate (i.e., has zero width). .. py:method:: _compute_nominal_value() .. py:method:: ravel() Return a flattened (1D) interval object for multi-dimensional intervals .. rubric:: Example >>> A = np.random.rand(200, 200, 2) >>> i = pba.intervalise(A) >>> print(i.shape) >>> i2 = i.ravel() >>> print(i2.shape) .. py:property:: lo :type: Union[numpy.ndarray, float] .. py:property:: hi :type: Union[numpy.ndarray, float] .. py:property:: left .. py:property:: right .. py:property:: width .. py:property:: rad half width .. py:property:: mid .. py:property:: unsized .. py:property:: val seemingly equivalent to `self.to_numpy()` .. py:property:: scalar Check if the interval is wide sense scalar .. note:: wide sense: I(1,2) and I([1],[2]) are both scalars .. py:property:: is_scalar Check if the interval is a strict-sense scalar .. note:: strict sense: I(1,2) is a scalar, but I([1],[2]) is not .. py:property:: shape .. py:property:: ndim .. py:method:: __neg__() .. py:method:: __pos__() .. py:method:: __add__(other) .. py:method:: __radd__(left) .. py:method:: __sub__(other) .. py:method:: __rsub__(left) .. py:method:: __mul__(other) .. py:method:: __rmul__(left) .. py:method:: __truediv__(other) .. py:method:: __rtruediv__(left) .. py:method:: __pow__(other) .. py:method:: __lt__(other) .. py:method:: __rlt__(left) .. py:method:: __gt__(other) .. py:method:: __rgt__(left) .. py:method:: __le__(other) .. py:method:: __rle__(left) .. py:method:: __ge__(other) .. py:method:: __rge__(left) .. py:method:: __eq__(other) .. py:method:: __ne__(other) .. py:method:: __array_ufunc__(ufunc, method, *inputs, **kwargs) .. py:method:: abs() .. py:method:: sqrt() .. py:method:: exp() .. py:method:: log() .. py:method:: sin() .. py:method:: cos() .. py:method:: tan() .. py:method:: from_meanform(x, half_width) :classmethod: .. py:method:: save_json(filename: str, comment: str = None, save_dir: str | pathlib.Path = '.') -> None Save the interval object to a JSON5 file. :param filename: The name of the file (without extension) to save the interval object to. :type filename: str :param comment: A comment to include at the top of the file. :type comment: str, optional :param save_dir: Directory where the file should be saved. Defaults to current directory. :type save_dir: str | Path, optional .. note:: The file is saved with a `.json5` extension. .. rubric:: Example >>> a.save_json("interval_data", comment="This is interval data", save_dir="results/") .. py:class:: Staircase(left, right, steps=200, mean=None, var=None, p_values=None) Bases: :py:obj:`Pbox` distribution free p-box .. py:method:: _init_moments() Initialize mean/var interval estimates. strategy: 1) Try LP-based bounds. 2) If that fails, try ECDF-based bounds. 3) If that also fails, set to NaN intervals so the program continues. This function NEVER raises. .. py:method:: __repr__() .. py:method:: plot(title=None, ax=None, style='box', fill_color='lightgray', bound_colors=None, bound_styles=None, left_line_kwargs=None, right_line_kwargs=None, nuance='step', alpha=0.3, **kwargs) default plotting function :param style: 'box' or 'simple' :type style: str :param fill_color: color to fill the box (only for 'box' style) :type fill_color: str :param bound_colors: list of two colors for left and right bound lines :type bound_colors: list :param bound_styles: list of two linestyles for left and right bound lines :type bound_styles: list :param left_line_kwargs: additional kwargs for left bound line :type left_line_kwargs: dict :param right_line_kwargs: additional kwargs for right bound line :type right_line_kwargs: dict :param nuance: 'step' or 'curve' for bound line styles :type nuance: str :param alpha: transparency level for the box fill (only for 'box' style) :type alpha: float :param \*\*kwargs: additional keyword arguments for the plot .. note:: Two styles are supported: a 'box' with fill-in color and a 'simple' one without fill-in color. Color and linestyle of the bound lines can be customized via the `bound_styles`, `left_line_kwargs`, and `right_line_kwargs` parameters. The argument `nuance` controls whether the bound lines are plotted as step functions ('step') or smooth curves ('curve'). .. rubric:: Example >>> a = pba.normal([2, 6], [0.5, 1]) >>> fig, ax = plt.subplots() >>> a.plot(ax=ax, style='simple') # simple style without fill-in color >>> # box style with fill-in color and also customized bound colors >>> a.plot(ax=ax, style='box', ... fill_color='lightblue', ... bound_colors = ['lightblue', 'lightblue'], ... bound_styles=("--", ":"), ... alpha=0.5 ... ) >>> # customized left and right bound line styles >>> ax = pbox.plot( ... left_line_kwargs={"linestyle": "--", "linewidth": 2}, ... right_line_kwargs={"linestyle": ":", "linewidth": 2, "alpha": 0.8}, ) .. py:method:: plot_reverse_axis(title=None, ax=None, style='box', fill_color='lightgray', bound_colors=None, nuance='step', alpha=0.3, orientation='xy', invert_xaxis=True, **kwargs) A testing plotting function that can swap quantile and probability axes. :param style: 'box' or 'simple' :type style: str :param orientation: 'xy' keeps x on horizontal and Pr(X<=x) on vertical; 'yx' swaps them. :type orientation: str .. py:method:: plot_outside_legend(title=None, ax=None, style='box', fill_color='lightgray', bound_colors=None, nuance='step', alpha=0.3, **kwargs) a specific variant of `plot()` which is used for scipy proceeding only. :param style: 'box' or 'simple' :type style: str .. py:method:: display(*args, **kwargs) .. py:method:: plot_probability_bound(x: float, ax=None, linecolor='r', markercolor='r', **kwargs) plot the probability bound at a certain quantile x .. note:: - a vertical line .. py:method:: plot_quantile_bound(p: float, ax=None, **kwargs) plot the quantile bound at a certain probability level p .. note:: - a horizontal line .. py:method:: from_CDFbundle(a, b) :classmethod: pbox from two emipirical CDF bundle :param - a: CDF bundle of lower extreme F; :param - b: CDF bundle of upper extreme F; .. py:method:: __neg__() .. py:method:: __add__(other) .. py:method:: __radd__(other) .. py:method:: __sub__(other) .. py:method:: __rsub__(other) .. py:method:: __mul__(other) .. py:method:: __rmul__(other) .. py:method:: __truediv__(other) .. py:method:: __rtruediv__(other) .. py:method:: __pow__(other) .. py:method:: __rpow__(other: numbers.Number) Power operation with the base as `other` and self as the exponent .. py:method:: __array_ufunc__(ufunc, method, *inputs, **kwargs) .. py:method:: cdf(x: numpy.ndarray) get the bounds on the cdf w.r.t x value :param x: x values :type x: array-like .. py:method:: alpha_cut(alpha=0.5) test the lightweight `alpha_cut` method :param alpha: probability levels :type alpha: array-like .. py:method:: sample(n_sam) LHS sampling by default .. py:method:: precise_sample(n_a: int, theta: float = None, n_e: int = None) Generate precise samples from a p-box .. py:method:: discretise(n=None) -> pyuncertainnumber.Interval alpha-cut discretisation of the p-box without outward rounding :param n: number of steps to be used in the discretisation. :type n: int :returns: vector Interval .. py:method:: outer_discretisation(n=None) discretisation of a p-box to get intervals based on the scheme of outer approximation :param n: number of steps to be used in the discretisation :type n: int .. note:: `the_interval_list` will have length one less than that of default `p_values` (i.e. 100 and 99) :returns: the outer intervals in vec-Interval form .. py:method:: condensation(n) -> Self ourter condensation of the pbox to reduce the number of steps and get a sparser staircase pbox :param n: number of steps to be used in the discretisation :type n: int .. note:: Have not thought about a better name so we call it `condensation` for now. Candidate names include 'approximation'. It will ouput a p-box and keep steps as 200 for computational consistency. .. rubric:: Example >>> p.condensation(n=5) :returns: a staircase p-box that looks sparser but has the same number of steps .. py:method:: condense(n) -> pyuncertainnumber.pba.dss.DempsterShafer Another condensation function which has steps of n Compared to the above `condensation` method that ouputs a p-box and keeps steps as 200 for computational consistency. This one condenses in a more literal manner, as in having n steps in the resulting Dempster-Shafer structure. .. py:method:: truncate(a, b) Truncate the Pbox to the range [a, b]. example: >>> from pyuncertainnumber import pba >>> p = pba.normal([4, 9], 1) >>> tr = p.truncate(3, 8) >>> fig, ax = plt.subplots() >>> p.plot(ax=ax) >>> tr.plot(ax=ax, fill_color='r') >>> plt.show() .. py:method:: min(other, method='f') Returns a new Pbox object that represents the element-wise minimum of two Pboxes. :param - other: Another Pbox object or a numeric value. :param - method: Calculation method to determine the minimum. Can be one of 'f', 'p', 'o', 'i'. :returns: Pbox .. py:method:: max(other, method='f') .. py:method:: get_PI(alpha: numbers.Number = 0.95, style='narrowest') -> pyuncertainnumber.Interval Compute the predictive interval at the coverage level of `alpha` :param alpha: coverage level for the predictive interval, default is 0.95 :type alpha: Number :param style: 'narrowest' or 'widest', default is 'narrowest' :type style: str .. note:: by default, narrowest predictive interval is returned; when the narrowest does not exist, a warning will the generated and then the widest is returned instead. .. rubric:: Example >>> from pyuncertainnumber import pba >>> p = pba.normal([10, 15, 1]) >>> p.get_PI(alpha=0.95, style='narrowest') .. py:method:: straddles(N, endpoints=True) -> bool Check whether the p-box straddles a number N :param N: the Number to check :type N: float :param endpoints: Whether to include the endpoints within the check :type endpoints: Boolean :returns: True If :math:`\mathrm{left} \leq N \leq \mathrm{right}` (Assuming `endpoints=True`) False Otherwise .. note:: This could affect the results of Frechet bounds .. py:method:: straddles_zero() -> bool Checks specifically whether :math:`0` is within the p-box .. py:method:: is_zero() .. py:method:: is_nagative() .. py:method:: env(other) computes the envelope of two Pboxes. :param other: :type other: Pbox :returns: - Pbox .. py:method:: imp(other) Returns the imposition of self with other pbox .. note:: - binary imposition between two pboxes only .. py:method:: _unary_template(f) .. py:method:: exp() exponential function: e^x .. py:method:: sqrt() square root function: √x .. py:method:: reciprocal() Calculate the reciprocal of the pbox .. note:: the pbox should not straddle zero, otherwise a warning is raised .. py:method:: log() natural logarithm of the pbox .. note:: - the pbox must be positive .. py:method:: sin() .. py:method:: cos() .. py:method:: tanh() .. py:method:: add(other, dependency='f') .. py:method:: sub(other, dependency='f') .. py:method:: mul(other, dependency='f') Multiplication of uncertain numbers with the defined dependency dependency .. py:method:: div(other, dependency='f') .. py:method:: pow(other, dependency='f') Exponentiation of uncertain numbers with the defined dependency dependency This suggests that the exponent (i.e. `other`) can also be an uncertain number. .. py:method:: balchprod(other) Frechet convolution of two pboxes when any of them straddles zero .. py:function:: convert(un) Convert any input un into a Pbox object .. note:: - theorically 'un' can be {Interval, DempsterShafer, Distribution, float, int} .. py:class:: Params .. py:attribute:: steps :value: 200 .. py:attribute:: many :value: 2000 .. py:attribute:: p_lboundary :value: 0.001 .. py:attribute:: p_hboundary :value: 0.999 .. py:attribute:: p_values .. py:attribute:: scott_hedged_interpretation .. py:attribute:: user_hedged_interpretation .. py:function:: envelope(*l_uns: pyuncertainnumber.pba.pbox_abc.Pbox | pyuncertainnumber.pba.dss.DempsterShafer | numbers.Number | pyuncertainnumber.pba.intervals.Interval | pyuncertainnumber.pba.distributions.Distribution | pyuncertainnumber.characterisation.uncertainNumber.UncertainNumber, output_type='pbox') -> pyuncertainnumber.pba.pbox_abc.Staircase | pyuncertainnumber.characterisation.uncertainNumber.UncertainNumber calculates the envelope of constructs only :param l_uns: the components, constructs and uncertain numbers, on which the envelope operation applied on. :type l_uns: list :param output_type: {'pbox' or 'uncertain_number' or 'un'} - default is pbox :type output_type: str :returns: the envelope of the given arguments, either a p-box or an interval. .. rubric:: Example >>> from pyuncertainnumber import envelope >>> a = pba.normal(3, 1) >>> b = pba.uniform(5, 8) >>> c = pba.normal(13, 2) >>> t = envelope(a, b, c, output_type='pbox') # or output_type='uncertain_number' .. py:function:: imposition(*l_uns: pyuncertainnumber.pba.pbox_abc.Pbox | pyuncertainnumber.pba.dss.DempsterShafer | numbers.Number | pyuncertainnumber.pba.intervals.Interval | pyuncertainnumber.pba.distributions.Distribution | pyuncertainnumber.characterisation.uncertainNumber.UncertainNumber, output_type='pbox') -> pyuncertainnumber.pba.pbox_abc.Staircase | pyuncertainnumber.characterisation.uncertainNumber.UncertainNumber Returns the imposition/intersection of the list of p-boxes :param l_uns: a list of constructs or UN objects to be mixed :type l_uns: list :param output_type: {'pbox' or 'uncertain_number' or 'un'} - default is pbox :type output_type: str :returns: - Pbox or UncertainNumber .. rubric:: Example >>> import pyuncertainnumber as pun >>> from pyuncertainnumber import pba >>> a = pba.normal([3, 7], 1) >>> b = pba.uniform([3,5], [6,9]) >>> i = pun.imposition(a, b) .. py:function:: stochastic_mixture(*l_uns: pyuncertainnumber.pba.pbox_abc.Pbox | pyuncertainnumber.pba.dss.DempsterShafer | numbers.Number | pyuncertainnumber.pba.intervals.Interval | pyuncertainnumber.pba.distributions.Distribution | pyuncertainnumber.characterisation.uncertainNumber.UncertainNumber, weights=None) it could work for either Pbox, distribution, DS structure or Intervals :param - l_uns: list of constructs or uncertain numbers :type - l_uns: list :param - weights: list of weights :type - weights: list .. rubric:: Example >>> import pyuncertainnumber as pun >>> p = pun.stochastic_mixture([[1,3], [2,4]]) .. py:function:: stacking(vec_interval: pyuncertainnumber.pba.intervals.Interval | list[pyuncertainnumber.pba.intervals.Interval], *, weights=None, display=False, ax=None, return_type='pbox', **kwargs) -> pyuncertainnumber.pba.pbox_abc.Pbox stochastic mixture operation of Intervals with probability masses :param - vec_interval: list of Intervals or a vectorised Interval :type - vec_interval: list :param - weights: list of weights :type - weights: list :param - display: boolean for plotting :type - display: Boolean :param - return_type: {'pbox' or 'ds' or 'bounds'} :type - return_type: str :returns: by default a p-box but can return the left and right bound F in `eCDF_bundlebounds`. .. note:: - For intervals specifically. - it takes a list of intervals or a single vectorised interval, which is a different signature compared to the other aggregation functions. - together the interval and masses, it can be deemed that all the inputs required is jointly a DS structure .. rubric:: Example >>> stacking([[1,3], [2,4]], weights=[0.5, 0.5], display=True) .. py:function:: mixture_pbox(*l_pboxes, weights=None, display=False) -> pyuncertainnumber.pba.pbox_abc.Pbox .. py:function:: mixture_ds(*l_ds, display=False) -> pyuncertainnumber.pba.dss.DempsterShafer mixture operation for DS structure .. py:function:: env_samples(data: numpy.typing.ArrayLike, output_type='pbox', ecdf_choice='canonical') nonparametric envelope function directly from data samples :param data: Each row represents a distribution, on which the envelope operation applied. :type data: ArrayLike :param output_type: {'pbox' or 'cdf'} default is pbox cdf is the CDF bundle :type output_type: str :param ecdf_choice: {'canonical' or 'staircase'} :type ecdf_choice: str .. note:: envelope on a set of empirical CDFs .. py:function:: env_ecdf_sep(*ecdfs, output_type='pbox', ecdf_choice='canonical') nonparametric envelope function for separate empirical CDFs .. py:function:: env_am(n_pars: numpy.typing.ArrayLike) -> numpy.ndarray bespoke function used for am metric case :param n_pars: (n_sam, 2) of tuple (mu, sigma) which may be a tensor :type n_pars: ArrayLike .. py:function:: env_pbox_am(n_mean: numpy.typing.ArrayLike, n_std: numpy.typing.ArrayLike) -> numpy.ndarray bespoke function used for am metric case :param n_mean: (n_sam,) of mean values which may be a tensor :type n_mean: ArrayLike :param n_std: (n_sam,) of standard deviation values which may be a tensor :type n_std: ArrayLike .. py:function:: KS_bounds(s: numpy.typing.ArrayLike, alpha: float, display=True, output_type='bounds') -> Union[tuple[pyuncertainnumber.pba.ecdf.eCDF_bundle], pyuncertainnumber.pba.pbox_abc.Pbox, pyuncertainnumber.UncertainNumber] construct free pbox from sample data by Kolmogorov-Smirnoff confidence bounds :param s: sample data, precise and imprecise :type s: ArrayLike :param dn: KS critical value at a significance level and sample size N; :type dn: float :param output_type: A choice between {'bounds', 'pbox', 'un'}, default='bounds' which returns two eCDF bundles as bounds; 'pbox' to return a pbox object; 'un' to return an uncertain number object. :type output_type: str :returns: a tuple of two CDF bounds, i.e. upper and lower (eCDF_bundle objects), or a Pbox object, or an UncertainNumber object the return type is controlled by the `output_type` argument. .. note:: By default the function returns two eCDF bundles as the extreme bounds. With the upper and lower bounds, a free pbox can be constructed. .. rubric:: Example >>> # both precise data (e.g. numpy array) and imprecise data (e.g. a vector of interval) are supported >>> precise_data = np.random.normal(0, 1, 100) # precise data case >>> ub, lb = pba.KS_bounds(precise_data, alpha=0.025, display=True) >>> # alternatively, an uncertain number or a p-box can be returned >>> pba.KS_bounds(precise_data, alpha=0.025, display=False, output_type='pbox') # return a pbox object >>> pba.KS_bounds(precise_data, alpha=0.025, display=False, output_type='un') # return an uncertain number object >>> # imprecise data case >>> impre_data = pba.I(lo = precise_data -0.5, hi = precise_data + 0.5) >>> ub, lb = pba.KS_bounds(impre_data, alpha=0.025, display=True) .. figure:: /_static/ks_bounds_demo.png :alt: ks_bounds :align: center :width: 50% Kolmogorov-Smirnoff confidence bounds illustration with precise and imprecise data.