pyuncertainnumber.pba.pbox_abc ============================== .. py:module:: pyuncertainnumber.pba.pbox_abc Classes ------- .. autoapisummary:: pyuncertainnumber.pba.pbox_abc.Pbox pyuncertainnumber.pba.pbox_abc.Staircase pyuncertainnumber.pba.pbox_abc.Leaf pyuncertainnumber.pba.pbox_abc.Cbox Functions --------- .. autoapisummary:: pyuncertainnumber.pba.pbox_abc.bound_steps_check pyuncertainnumber.pba.pbox_abc.pbox_from_extredists pyuncertainnumber.pba.pbox_abc.pbox_from_ecdf_bundle pyuncertainnumber.pba.pbox_abc.naive_frechet_pbox pyuncertainnumber.pba.pbox_abc.vectorised_naive_frechet_pbox pyuncertainnumber.pba.pbox_abc.classic_frechet_pbox pyuncertainnumber.pba.pbox_abc.straddle_frechet_pbox pyuncertainnumber.pba.pbox_abc.nagative_frechet_pbox pyuncertainnumber.pba.pbox_abc.frechet_pbox_mul pyuncertainnumber.pba.pbox_abc.is_un pyuncertainnumber.pba.pbox_abc.convert_pbox pyuncertainnumber.pba.pbox_abc.pbox_number_ops pyuncertainnumber.pba.pbox_abc.truncate pyuncertainnumber.pba.pbox_abc.sin pyuncertainnumber.pba.pbox_abc.cos pyuncertainnumber.pba.pbox_abc.tanh pyuncertainnumber.pba.pbox_abc.exp pyuncertainnumber.pba.pbox_abc.log pyuncertainnumber.pba.pbox_abc.sqrt pyuncertainnumber.pba.pbox_abc.simple_stacking pyuncertainnumber.pba.pbox_abc.inspect_pbox Module Contents --------------- .. py:function:: bound_steps_check(bound) .. py:function:: pbox_from_extredists(rvs, shape='beta', extre_bound_params=None) transform into pbox object from extreme bounds parameterised by `sps.dist` :param rvs: list of scipy.stats.rv_continuous objects :type rvs: list .. 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:: naive_frechet_pbox(x, y, op) -> Staircase A wrapper that returns a Pbox from the naive Frechet operation .. note:: old implementation from pba.r .. py:function:: vectorised_naive_frechet_pbox(x, y, op) -> Staircase A wrapper that returns a Pbox from the naive Frechet operation .. py:function:: classic_frechet_pbox(x, y, op) -> Staircase this corresponds to the Frank, Nelson and Sklar Frechet bounds implementation .. py:function:: straddle_frechet_pbox(x, y) bespoke Frechet for multiplcation when anyone straddles 0 .. py:function:: nagative_frechet_pbox(x, y) .. py:function:: frechet_pbox_mul(x, y) the overall pbox .. 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:: 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: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:: Cbox(left, right, steps=200) Bases: :py:obj:`Pbox` 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:function:: is_un(un) if the `un` is modelled by accepted constructs .. py:function:: convert_pbox(un) transform the input un into a Pbox object .. note:: - theorically 'un' can be {Interval, DempsterShafer, Distribution, float, int} .. py:function:: pbox_number_ops(pbox: Pbox, n: numbers.Number, f: callable) blueprint for arithmetic between pbox and real numbers .. py:function:: truncate(pbox, min, max) .. py:function:: sin() .. py:function:: cos() .. py:function:: tanh() .. py:function:: exp() .. py:function:: log() .. py:function:: sqrt() .. py:function:: simple_stacking(itvls) simple version of stacking vector Interval objects into pbox :param itvls: a vector Interval object to be stacked :type itvls: Interval .. note:: - only meant for quick use during development - see `stacking` function for production use .. py:function:: inspect_pbox(pbox) quickly inspect a pbox object