Python numpy.geomspace() Examples

The following are 26 code examples for showing how to use numpy.geomspace(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: celer   Author: mathurinm   File: test_lasso.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_celer_path_logreg():
    X, y = build_dataset(
        n_samples=50, n_features=100, sparse_X=True)
    y = np.sign(y)
    alpha_max = norm(X.T.dot(y), ord=np.inf) / 2
    alphas = alpha_max * np.geomspace(1, 1e-2, 10)

    tol = 1e-8
    coefs, Cs, n_iters = _logistic_regression_path(
        X, y, Cs=1. / alphas, fit_intercept=False, penalty='l1',
        solver='liblinear', tol=tol)

    _, coefs_c, gaps = celer_path(
        X, y, "logreg", alphas=alphas, tol=tol, verbose=2)

    np.testing.assert_array_less(gaps, tol)
    np.testing.assert_allclose(coefs != 0, coefs_c.T != 0)
    np.testing.assert_allclose(coefs, coefs_c.T, atol=1e-5, rtol=1e-3) 
Example 2
Project: recruit   Author: Frank-qlu   File: test_histograms.py    License: Apache License 2.0 6 votes vote down vote up
def test_scott_vs_stone(self):
        """Verify that Scott's rule and Stone's rule converges for normally distributed data"""

        def nbins_ratio(seed, size):
            rng = np.random.RandomState(seed)
            x = rng.normal(loc=0, scale=2, size=size)
            a, b = len(np.histogram(x, 'stone')[0]), len(np.histogram(x, 'scott')[0])
            return a / (a + b)

        ll = [[nbins_ratio(seed, size) for size in np.geomspace(start=10, stop=100, num=4).round().astype(int)]
              for seed in range(256)]

        # the average difference between the two methods decreases as the dataset size increases.
        assert_almost_equal(abs(np.mean(ll, axis=0) - 0.5),
                            [0.1065248,
                             0.0968844,
                             0.0331818,
                             0.0178057],
                            decimal=3) 
Example 3
Project: dwave-hybrid   Author: dwavesystems   File: pt.py    License: Apache License 2.0 6 votes vote down vote up
def next(self, state, **runopts):
        bqm = state.problem

        # get a reasonable beta range
        beta_hot, beta_cold = neal.default_beta_range(bqm)

        # generate betas for all branches/replicas
        betas = np.geomspace(beta_hot, beta_cold, self.num_replicas)

        # create num_replicas with betas spaced with geometric progression
        states = hybrid.States(*[state.updated(beta=b) for b in betas])

        return states


#
# A few PT workflow generators. Should be treated as Runnable classes
# 
Example 4
Project: dwave-hybrid   Author: dwavesystems   File: pa.py    License: Apache License 2.0 6 votes vote down vote up
def next(self, state, **runopts):
        bqm = state.problem

        # get a reasonable beta range
        beta_hot, beta_cold = neal.default_beta_range(bqm)

        # generate betas
        if self.interpolation == 'linear':
            beta_schedule = np.linspace(beta_hot, beta_cold, self.length)
        elif self.interpolation == 'geometric':
            beta_schedule = np.geomspace(beta_hot, beta_cold, self.length)
        else:
            raise ValueError("Beta schedule type {} not implemented".format(self.interpolation))

        # store the schedule in output state
        return state.updated(beta_schedule=beta_schedule) 
Example 5
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_histograms.py    License: MIT License 6 votes vote down vote up
def test_scott_vs_stone(self):
        """Verify that Scott's rule and Stone's rule converges for normally distributed data"""

        def nbins_ratio(seed, size):
            rng = np.random.RandomState(seed)
            x = rng.normal(loc=0, scale=2, size=size)
            a, b = len(np.histogram(x, 'stone')[0]), len(np.histogram(x, 'scott')[0])
            return a / (a + b)

        ll = [[nbins_ratio(seed, size) for size in np.geomspace(start=10, stop=100, num=4).round().astype(int)]
              for seed in range(256)]

        # the average difference between the two methods decreases as the dataset size increases.
        assert_almost_equal(abs(np.mean(ll, axis=0) - 0.5),
                            [0.1065248,
                             0.0968844,
                             0.0331818,
                             0.0178057],
                            decimal=3) 
Example 6
Project: trax   Author: google   File: array_ops.py    License: Apache License 2.0 6 votes vote down vote up
def geomspace(start, stop, num=50, endpoint=True, dtype=float):  # pylint: disable=missing-docstring
  if dtype:
    dtype = utils.result_type(dtype)
  if num < 0:
    raise ValueError('Number of samples {} must be non-negative.'.format(num))
  if not num:
    return empty([0])
  step = 1.
  if endpoint:
    if num > 1:
      step = tf.pow((stop / start), 1 / (num - 1))
  else:
    step = tf.pow((stop / start), 1 / num)
  result = tf.cast(tf.range(num), step.dtype)
  result = tf.pow(step, result)
  result = tf.multiply(result, start)
  if dtype:
    result = tf.cast(result, dtype=dtype)
  return arrays_lib.tensor_to_ndarray(result)


# Building matrices. 
Example 7
Project: trax   Author: google   File: array_ops_test.py    License: Apache License 2.0 6 votes vote down vote up
def testGeomSpace(self):

    def run_test(start, stop, **kwargs):
      arg1 = start
      arg2 = stop
      self.match(
          array_ops.geomspace(arg1, arg2, **kwargs),
          np.geomspace(arg1, arg2, **kwargs),
          msg='geomspace({}, {})'.format(arg1, arg2),
          almost=True,
          decimal=4)

    run_test(1, 1000, num=5)
    run_test(1, 1000, num=5, endpoint=False)
    run_test(-1, -1000, num=5)
    run_test(-1, -1000, num=5, endpoint=False) 
Example 8
def test_scott_vs_stone(self):
        """Verify that Scott's rule and Stone's rule converges for normally distributed data"""

        def nbins_ratio(seed, size):
            rng = np.random.RandomState(seed)
            x = rng.normal(loc=0, scale=2, size=size)
            a, b = len(np.histogram(x, 'stone')[0]), len(np.histogram(x, 'scott')[0])
            return a / (a + b)

        ll = [[nbins_ratio(seed, size) for size in np.geomspace(start=10, stop=100, num=4).round().astype(int)]
              for seed in range(256)]

        # the average difference between the two methods decreases as the dataset size increases.
        assert_almost_equal(abs(np.mean(ll, axis=0) - 0.5),
                            [0.1065248,
                             0.0968844,
                             0.0331818,
                             0.0178057],
                            decimal=3) 
Example 9
Project: phoebe2   Author: phoebe-project   File: __init__.py    License: GNU General Public License v3.0 6 votes vote down vote up
def monkeypatch():
    """
    monkeypatch built-in numpy functions to call those provided by nparray instead.

    ```py
    import nparray
    import numpy as np

    nparray.monkeypatch()
    print(np.linspace(0,1,11))
    ```

    """
    np.array = array
    np.arange = arange
    np.linspace = linspace
    np.logspace = logspace
    np.geomspace = geomspace
    np.full = full
    np.full_like = full_like
    np.zeros = zeros
    np.zeros_like = zeros_like
    np.ones = ones
    np.ones_like = ones_like
    np.eye = eye 
Example 10
Project: coffeegrindsize   Author: jgagneastro   File: test_histograms.py    License: MIT License 6 votes vote down vote up
def test_scott_vs_stone(self):
        """Verify that Scott's rule and Stone's rule converges for normally distributed data"""

        def nbins_ratio(seed, size):
            rng = np.random.RandomState(seed)
            x = rng.normal(loc=0, scale=2, size=size)
            a, b = len(np.histogram(x, 'stone')[0]), len(np.histogram(x, 'scott')[0])
            return a / (a + b)

        ll = [[nbins_ratio(seed, size) for size in np.geomspace(start=10, stop=100, num=4).round().astype(int)]
              for seed in range(256)]

        # the average difference between the two methods decreases as the dataset size increases.
        assert_almost_equal(abs(np.mean(ll, axis=0) - 0.5),
                            [0.1065248,
                             0.0968844,
                             0.0331818,
                             0.0178057],
                            decimal=3) 
Example 11
Project: AMPL   Author: ATOMconsortium   File: hyperparam_search_wrapper.py    License: MIT License 5 votes vote down vote up
def generate_combo(self, params_dict):
        """
        Method to generate all combinations from a given set of key-value pairs
        
        Args:
            params_dict: Set of key-value pairs with the key being the param name and the value being the list of values
            you want to try for that param
        
        Returns:
            new_dict: The list of all combinations of parameters
        """
        if not params_dict:
            return None

        new_dict = {}
        for key, value in params_dict.items():
            assert isinstance(value, collections.Iterable)
            if key == 'layers':
                new_dict[key] = value
            elif type(value[0]) != str:
                tmp_list = list(np.geomspace(value[0], value[1], value[2]))
                if key in self.convert_to_int:
                    new_dict[key] = [int(x) for x in tmp_list]
                else:
                    new_dict[key] = tmp_list
            else:
                new_dict[key] = value
        return new_dict 
Example 12
Project: trax   Author: google   File: lax_numpy_test.py    License: Apache License 2.0 5 votes vote down vote up
def testGeomspace(self, start_shape, stop_shape, num,
                    endpoint, dtype, rng_factory):
    rng = rng_factory()
    # relax default tolerances slightly
    tol = {onp.float16: 4e-3, onp.float32: 2e-3, onp.complex128: 1e-14}
    def args_maker():
      """Test the set of inputs onp.geomspace is well-defined on."""
      start, stop = self._GetArgsMaker(rng,
                                [start_shape, stop_shape],
                                [dtype, dtype])()
      # onp.geomspace can't handle differently ranked tensors
      # w. negative numbers!
      start, stop = lnp.broadcast_arrays(start, stop)
      if dtype in complex_dtypes:
        return start, stop
      # to avoid NaNs, non-complex start and stop cannot
      # differ in sign, elementwise
      start = start * lnp.sign(start) * lnp.sign(stop)
      return start, stop
    start, stop = args_maker()
    ndim = len(onp.shape(start + stop))
    for axis in range(-ndim, ndim):
      def lnp_op(start, stop):
        return lnp.geomspace(start, stop, num, endpoint=endpoint, dtype=dtype,
                             axis=axis)
      def onp_op(start, stop):
        start = start.astype(onp.float32) if dtype == lnp.bfloat16 else start
        stop = stop.astype(onp.float32) if dtype == lnp.bfloat16 else stop
        return onp.geomspace(
          start, stop, num, endpoint=endpoint,
          dtype=dtype if dtype != lnp.bfloat16 else onp.float32,
          axis=axis).astype(dtype)
      self._CheckAgainstNumpy(onp_op, lnp_op, args_maker,
                              check_dtypes=False, tol=tol)
      if dtype in (inexact_dtypes + [None,]):
        self._CompileAndCheck(lnp_op, args_maker,
                              check_dtypes=False, atol=tol, rtol=tol,
                              check_incomplete_shape=True) 
Example 13
Project: CatLearn   Author: SUNCAT-Center   File: scikit_wrapper.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _lasso(self):
        """Order features according to their corresponding coefficients."""
        if self.line_search:
            pred = None
            try:
                alpha_list = np.geomspace(self.max_alpha, self.min_alpha,
                                          self.steps)
            except AttributeError:
                alpha_list = np.exp(np.linspace(np.log(self.max_alpha),
                                                np.log(self.min_alpha),
                                                self.steps))
            for alpha in alpha_list:
                regr = Lasso(alpha=alpha, max_iter=self.iter,
                             fit_intercept=True, normalize=True,
                             selection='random')
                model = regr.fit(self.train_matrix, self.train_target)
                nz = len(model.coef_) - (model.coef_ == 0.).sum()
                if nz >= self.size:
                    coeff = model.coef_
                    break
        else:
            regr = LassoCV(fit_intercept=True, normalize=True,
                           n_alphas=self.steps, max_iter=self.iter,
                           eps=self.eps, cv=None)
            model = regr.fit(X=self.train_matrix, y=self.train_target)
            coeff = model.coef_

            # Make the linear prediction.
            pred = None
            if self.predict:
                data = model.predict(self.test_matrix)
                pred = get_error(prediction=data,
                                 target=self.test_target)['average']

        return coeff, pred 
Example 14
Project: combine-FEVER-NSMN   Author: easonnie   File: item_rules.py    License: MIT License 5 votes vote down vote up
def preceding_sent_weighed_similarity(self, sent_list,
                                                item,
                                                k=5,
                                                start=1.1,
                                                end=0.8,
                                                *args):
        k = min(len(sent_list), k)
        return np.arange(k), np.geomspace(start, end, k) 
Example 15
Project: ctapipe   Author: cta-observatory   File: charge_resolution.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def bin_dataframe(df, n_bins):
    """
    Assign a "bin" column to the dataframe to indicate which bin the true
    charges belong to.

    Bins are assigned in log space.

    Parameters
    ----------
    df : pd.DataFrame
    n_bins : int
        Number of bins to allow in range

    Returns
    -------
    pd.DataFrame
    """
    true = df["true"].values
    min_ = true.min()
    max_ = true.max()
    bins = np.geomspace(min_, max_, n_bins)
    log_bin_width = np.diff(np.log10(bins))[0]
    bins = np.append(bins, 10 ** (np.log10(bins[-1]) + log_bin_width))
    df["bin"] = np.digitize(true, bins, right=True) - 1

    return df 
Example 16
Project: polyaxon   Author: polyaxon   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def get_length(matrix):
    if matrix.IDENTIFIER == V1HpChoice.IDENTIFIER:
        return len(matrix.value)
    if matrix.IDENTIFIER == V1HpPChoice.IDENTIFIER:
        return len(matrix.value)

    if matrix.IDENTIFIER == V1HpRange.IDENTIFIER:
        return len(np.arange(**matrix.value))

    if matrix.IDENTIFIER == V1HpLinSpace.IDENTIFIER:
        return len(np.linspace(**matrix.value))

    if matrix.IDENTIFIER == V1HpLogSpace.IDENTIFIER:
        return len(np.logspace(**matrix.value))

    if matrix.IDENTIFIER == V1HpGeomSpace.IDENTIFIER:
        return len(np.geomspace(**matrix.value))

    if matrix.IDENTIFIER in {
        V1HpUniform.IDENTIFIER,
        V1HpQUniform.IDENTIFIER,
        V1HpLogUniform.IDENTIFIER,
        V1HpQLogUniform.IDENTIFIER,
        V1HpNormal.IDENTIFIER,
        V1HpQNormal.IDENTIFIER,
        V1HpLogNormal.IDENTIFIER,
        V1HpQLogNormal.IDENTIFIER,
    }:
        raise ValidationError("Distribution should not call `length`") 
Example 17
Project: polyaxon   Author: polyaxon   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def to_numpy(matrix):
    if matrix.IDENTIFIER == V1HpChoice.IDENTIFIER:
        return matrix.value
    if matrix.IDENTIFIER == V1HpPChoice.IDENTIFIER:
        raise ValidationError(
            "Distribution should not call `to_numpy`, "
            "instead it should call `sample`."
        )

    if matrix.IDENTIFIER == V1HpRange.IDENTIFIER:
        return np.arange(**matrix.value)

    if matrix.IDENTIFIER == V1HpLinSpace.IDENTIFIER:
        return np.linspace(**matrix.value)

    if matrix.IDENTIFIER == V1HpLogSpace.IDENTIFIER:
        return np.logspace(**matrix.value)

    if matrix.IDENTIFIER == V1HpGeomSpace.IDENTIFIER:
        return np.geomspace(**matrix.value)

    if matrix.IDENTIFIER in {
        V1HpUniform.IDENTIFIER,
        V1HpQUniform.IDENTIFIER,
        V1HpLogUniform.IDENTIFIER,
        V1HpQLogUniform.IDENTIFIER,
        V1HpNormal.IDENTIFIER,
        V1HpQNormal.IDENTIFIER,
        V1HpLogNormal.IDENTIFIER,
        V1HpQLogNormal.IDENTIFIER,
    }:
        raise ValidationError(
            "Distribution should not call `to_numpy`, "
            "instead it should call `sample`."
        ) 
Example 18
Project: phoebe2   Author: phoebe-project   File: __init__.py    License: GNU General Public License v3.0 5 votes vote down vote up
def logspace(start, stop, num, endpoint=True, base=10.0, unit=None):
    """
    See also:

    * <nparray.geomspace>

    Arguments
    ------------
    * `start` (int or float): ``base ** start`` is the starting value of the sequence.
    * `stop` (int or float): ``base ** stop`` is the final value of the sequence,
        unless `endpoint` is False.  In that case, ``num + 1`` values are spaced
        over the interval in log-space, of which all but the last (a sequence of
        length `num`) are returned.
    * `num` (int): number of samples to generate.
    * `endpoint` (bool, optional, default=True): If True, `stop` is the last
        sample. Otherwise, it is not included.
    * `base` (float, optional, default=10.0): The base of the log space. The
        step size between the elements in ``ln(samples) / ln(base)``
        (or ``log_base(samples)``) is uniform.
    * `unit` (astropy unit or string, optional, default=None): unit
      corresponding to the passed values.

    Returns
    -----------
    * <Logspace>
    """
    return _wrappers.Logspace(start, stop, num, endpoint, base, unit) 
Example 19
Project: phoebe2   Author: phoebe-project   File: __init__.py    License: GNU General Public License v3.0 5 votes vote down vote up
def geomspace(start, stop, num, endpoint=True, unit=None):
    """
    See also:

    * <nparray.logspace>

    Arguments
    ------------
    * `start` (int or float): the starting point of the sequence.
    * `stop` (int or float): the final value of the sequence, unless `endpoint`
        is False.  In that case, ``num + 1`` values are spaced over the
        interval in log-space, of which all but the last (a sequence of
        length `num`) are returned.
    * `num` (int): number of samples to generate.
    * `endpoint` (bool, optional, default=True): If True, `stop` is the last
        sample. Otherwise, it is not included.
    * `unit` (astropy unit or string, optional, default=None): unit
      corresponding to the passed values.

    Returns
    -----------
    * <Geomspace>
    """
    if LooseVersion(np.__version__) >= LooseVersion("1.13"):
        return _wrappers.Geomspace(start, stop, num, endpoint, unit)
    else:
        raise NotImplementedError("geomspace requires numpy version >= 1.13") 
Example 20
Project: phoebe2   Author: phoebe-project   File: nparray.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, start, stop, num, endpoint=True, unit=None):
        """
        This is available as a top-level convenience function as <nparray.geomspace>.

        Arguments
        ------------
        * `start` (int or float): the starting point of the sequence.
        * `stop` (int or float): the final value of the sequence, unless `endpoint`
            is False.  In that case, ``num + 1`` values are spaced over the
            interval in log-space, of which all but the last (a sequence of
            length `num`) are returned.
        * `num` (int): number of samples to generate.
        * `endpoint` (bool, optional, default=True): If True, `stop` is the last
            sample. Otherwise, it is not included.
        * `unit` (astropy unit or string, optional, default=None): unit
          corresponding to the passed values.

        Returns
        -----------
        * <Geomspace>
        """
        super(Geomspace, self).__init__(('start', start, is_float),
                                       ('stop', stop, is_float),
                                       ('num', num, is_int_positive),
                                       ('endpoint', endpoint, is_bool),
                                       ('unit', unit, is_unit_or_unitstring_or_none)) 
Example 21
Project: phoebe2   Author: phoebe-project   File: nparray.py    License: GNU General Public License v3.0 5 votes vote down vote up
def array(self):
        """
        Compute the underyling numpy array by calling:

        ```py
        np.geomspace(start, stop, num, endpoint)
        ```

        Returns
        ---------
        * (numpy array): the underlying (computed) numpy array
        """
        return np.geomspace(self.start, self.stop, self.num, self.endpoint) 
Example 22
Project: corrscope   Author: corrscope   File: spectrum.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, scfg: SpectrumConfig, subsmp_s: float, dummy_data: np.ndarray):
        self.scfg = scfg

        n_fftindex: FFTIndex = signal.next_fast_len(len(dummy_data))

        # Increase n_fftindex until every note has nonzero width.
        while True:
            # Compute parameters
            self.min_hz = scfg.min_hz
            self.max_hz = self.min_hz * 2 ** scfg.octaves
            n_fencepost = scfg.notes_per_octave * scfg.octaves + 1

            note_fenceposts_hz = np.geomspace(
                self.min_hz, self.max_hz, n_fencepost, dtype=FLOAT
            )

            # Convert fenceposts to FFTIndex
            fft_from_hertz = n_fftindex / subsmp_s
            note_fenceposts: FFTIndexArray = (
                fft_from_hertz * note_fenceposts_hz
            ).astype(np.int32)
            note_widths = np.diff(note_fenceposts)

            if np.any(note_widths == 0):
                n_fftindex = signal.next_fast_len(n_fftindex + n_fftindex // 5 + 1)
                continue
            else:
                break

        self.n_fftindex = n_fftindex  # Passed to rfft() to automatically zero-pad data.
        self.note_fenceposts = note_fenceposts
        self.n_fencepost = len(note_fenceposts) 
Example 23
Project: gempy   Author: cgre-aachen   File: grid_types.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def create_irregular_grid_kernel(resolution, radius):
        """
        Create an isometric grid kernel (centered at 0)

        Args:
            resolution: [s0]
            radius (float): Maximum distance of the kernel

        Returns:
            tuple: center of the voxel, left edge of each voxel (for xyz), right edge of each voxel (for xyz).
        """

        if radius is not list or radius is not np.ndarray:
            radius = np.repeat(radius, 3)

        g_ = []
        g_2 = []
        d_ = []
        for xyz in [0, 1, 2]:

            if xyz == 2:
                # Make the grid only negative for the z axis

                g_.append(np.geomspace(0.01, 1, int(resolution[xyz])))
                g_2.append((np.concatenate(([0], g_[xyz])) + 0.05) * - radius[xyz] * 1.2)
            else:
                g_.append(np.geomspace(0.01, 1, int(resolution[xyz] / 2)))
                g_2.append(np.concatenate((-g_[xyz][::-1], [0], g_[xyz])) * radius[xyz])
            d_.append(np.diff(np.pad(g_2[xyz], 1, 'reflect', reflect_type='odd')))

        g = np.meshgrid(*g_2)
        d_left = np.meshgrid(d_[0][:-1]/2, d_[1][:-1]/2, d_[2][:-1]/2)
        d_right = np.meshgrid(d_[0][1:]/2, d_[1][1:]/2, d_[2][1:]/2)
        kernel_g = np.vstack(tuple(map(np.ravel, g))).T.astype("float64")
        kernel_d_left = np.vstack(tuple(map(np.ravel, d_left))).T.astype("float64")
        kernel_d_right = np.vstack(tuple(map(np.ravel, d_right))).T.astype("float64")

        return kernel_g, kernel_d_left, kernel_d_right 
Example 24
Project: Carnets   Author: holzschu   File: test_quantity_non_ufuncs.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_geomspace(self):
        out = np.geomspace(1000.*u.m, 10.*u.km, 5)
        expected = np.geomspace(1, 10, 5) * u.km
        assert np.all(out == expected)

        q1 = np.arange(1., 7.).reshape(2, 3) * u.m
        q2 = 10000. * u.cm
        out = np.geomspace(q1, q2, 5)
        expected = np.geomspace(q1.to_value(q2.unit), q2.value, 5) * q2.unit
        assert np.all(out == expected) 
Example 25
Project: MyGrad   Author: rsokl   File: funcs.py    License: MIT License 4 votes vote down vote up
def logspace(
    start, stop, num=50, include_endpoint=True, base=10, dtype=None, constant=False
):
    """ Return a Tensor with evenly-spaced numbers over a specified interval on a log scale.

        In linear space, values are generated within [base**start, base**stop], with the endpoint
        optionally excluded.

        Parameters
        ----------
        start : Real
            The starting value of the sequence, inclusive; start at `base ** start`.

        stop : Real
            The ending value of the sequence, inclusive unless `include_endpoint` is False; end at
            `base ** stop`.

        num : int, optional (default=50)
            The number of values to generate. Must be non-negative.

        include_endpoint : bool, optional (default=True)
            Whether to include the endpoint in the Tensor. Note that if False, the step size changes
            to accommodate the sequence excluding the endpoint.

        base : Real, optional (default=10)
            The base of the log space.

        dtype : data-type, optional (default=None)
            The data type of the output Tensor, or None to infer from the inputs.

        constant : bool, optional (default=False)
            If ``True``, the returned tensor is a constant (it
            does not back-propagate a gradient)

        See Also
        --------
        arange : Similar to linspace, with the step size specified instead of the
                 number of samples. Note that, when used with a float endpoint, the
                 endpoint may or may not be included.
        linspace : Similar to logspace, but with the samples uniformly distributed
                   in linear space, instead of log space.
        geomspace : Similar to logspace, but with endpoints specified directly.

        Examples
        --------
        >>> import mygrad as mg
        >>> mg.logspace(2.0, 3.0, num=4)
        Tensor([  100.        ,   215.443469  ,   464.15888336,  1000.        ])
        >>> mg.logspace(2.0, 3.0, num=4, endpoint=False)
        Tensor([ 100.        ,  177.827941  ,  316.22776602,  562.34132519])
        >>> mg.logspace(2.0, 3.0, num=4, base=2.0)
        Tensor([ 4.        ,  5.0396842 ,  6.34960421,  8.        ])

        Returns
        -------
        Tensor
            A Tensor of `num` evenly-spaced values in the log interval [base**start, base**stop].
    """
    return Tensor(
        np.logspace(start, stop, num, include_endpoint, base, dtype), constant=constant
    ) 
Example 26
Project: reliability   Author: MatthewReid854   File: Distributions.py    License: GNU Lesser General Public License v3.0 4 votes vote down vote up
def __expon_CI(self, func, plot_CI, text_title, color):
        '''
        Generates the confidence intervals for CDF, SF, HF, CHF
        This is a hidden function intended only for use by other functions.
        '''
        if func not in ['CDF', 'SF', 'HF', 'CHF']:
            raise ValueError('func must be either CDF, SF, HF, or CHF')

        # determine the xrange so it can be reimposed after plotting the CI. Without this the xrange gets too large as some CI can extend a long way.
        x_lims = plt.xlim()
        y_lims = plt.ylim()

        # this section plots the confidence interval
        if self.Lambda_SE is not None and self.Z is not None and plot_CI is True:

            # add a line to the plot title to include the confidence bounds information
            CI_100 = round((1 - ss.norm.cdf(-self.Z) * 2) * 100, 4)  # Converts Z to CI and formats the confidence interval value ==> 0.95 becomes 95
            if CI_100 % 1 == 0:
                CI_100 = int(CI_100)  # removes decimals if the only decimal is 0
            text_title = str(text_title + '\n' + str(CI_100) + '% confidence bounds')  # Adds the CI and CI_type to the title
            plt.title(text_title)
            plt.subplots_adjust(top=0.83)

            Lambda_upper = self.Lambda * (np.exp(self.Z * (self.Lambda_SE / self.Lambda)))
            Lambda_lower = self.Lambda * (np.exp(-self.Z * (self.Lambda_SE / self.Lambda)))
            t_max = self.b95 * 5
            t = np.geomspace(1e-5, t_max, 1000)

            if func == 'CDF':
                yy_upper0 = 1 - np.exp(-Lambda_upper * t)
                yy_lower0 = 1 - np.exp(-Lambda_lower * t)
                y_max = 1 - 1e-8
                y_min = 1e-8
            if func == 'SF':
                yy_upper0 = np.exp(-Lambda_upper * t)
                yy_lower0 = np.exp(-Lambda_lower * t)
                y_max = 1 - 1e-8
                y_min = 1e-8
            if func == 'HF':
                yy_upper0 = Lambda_upper * np.ones_like(t)
                yy_lower0 = Lambda_lower * np.ones_like(t)
                y_min = 0
                y_max = Lambda_upper * 2
                y_lims = (0, Lambda_upper * 1.2)  # this changes the ylims to ensure the CI will be included as it is a constant
            if func == 'CHF':
                yy_upper0 = -np.log(np.exp(-Lambda_upper * t))  # same as -np.log(SF)
                yy_lower0 = -np.log(np.exp(-Lambda_lower * t))
                y_min = 0
                y_max = 1e10
            # impose plotting limits so not plotting to infinity
            yy_lower = np.where(yy_lower0 < y_min, y_min, np.where(yy_lower0 > y_max, y_max, yy_lower0))
            yy_upper = np.where(yy_upper0 < y_min, y_min, np.where(yy_upper0 > y_max, y_max, yy_upper0))
            plt.fill_between(t + self.gamma, yy_lower, yy_upper, color=color, alpha=0.3, linewidth=0)  # the linewidth and linestyle hides the boundary between the two parts
            plt.plot(t + self.gamma, yy_lower, color=color, linewidth=0)
            plt.plot(t + self.gamma, yy_upper, color=color, linewidth=0)
            # reimpose the xlim and ylim to be what it was before the CI was plotted
            plt.xlim(x_lims)
            plt.ylim(y_lims)