Python numpy.cbrt() Examples

The following are 30 code examples for showing how to use numpy.cbrt(). 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: estimagic   Author: OpenSourceEconomics   File: differentiation.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _no_extrapolation_hessian(internal_func, params_value, method):
    finite_diff = getattr(aux, method)
    hess = np.empty((len(params_value), len(params_value)))
    for i, val_1 in enumerate(params_value):
        h_1 = (1.0 + abs(val_1)) * np.cbrt(np.finfo(float).eps)
        for j, val_2 in enumerate(params_value):
            h_2 = (1.0 + abs(val_2)) * np.cbrt(np.finfo(float).eps)
            params_r = params_value.copy()
            params_r[j] += h_2
            # Calculate the first derivative w.r.t. var_1 at (params + h_2) with
            # the central method. This is not the right f_x0, but the real one
            # isn't needed for the central method.
            f_plus = finite_diff(internal_func, None, params_r, i, h_1)
            params_l = params_value.copy()
            params_l[j] -= h_2
            # Calculate the first derivative w.r.t. var_1 at (params - h_2) with
            # the central method. This is not the right f_x0, but the real one
            # isn't needed for the central method.
            f_minus = finite_diff(internal_func, None, params_l, i, h_1)
            f_diff = (f_plus - f_minus) / (2.0 * h_1 * h_2)
            hess[i, j] = f_diff
            hess[i, j] = f_diff
    return hess 
Example 2
Project: colorio   Author: nschloe   File: _cieluv.py    License: GNU General Public License v3.0 6 votes vote down vote up
def from_xyz100(self, xyz):
        def f(t):
            delta = 6.0 / 29.0
            out = numpy.array(t, dtype=float)
            is_greater = out > delta ** 3
            out[is_greater] = 116 * numpy.cbrt(out[is_greater]) - 16
            out[~is_greater] = out[~is_greater] / (delta / 2) ** 3
            return out

        L = f(xyz[1] / self.whitepoint[1])

        x, y, z = xyz
        p = x + 15 * y + 3 * z
        u = 4 * x / p
        v = 9 * y / p

        wx, wy, wz = self.whitepoint
        q = wx + 15 * wy + 3 * wz
        un = 4 * wx / q
        vn = 9 * wy / q
        return numpy.array([L, 13 * L * (u - un), 13 * L * (v - vn)]) 
Example 3
Project: PyXtal   Author: qzhu2017   File: structure.py    License: MIT License 6 votes vote down vote up
def symmetrized_stress(self, stress):
        #Make the matrix lower-diagonal
        for (i,j) in [(1,0),(2,1),(2,2)]:
            stress[i][j] = stress[i][j] + stress[j][i]
            stress[j][i] = 0
        #Normalize the matrix
        snm = self.struc.lattice.stress_normalization_matrix
        m2 = np.multiply(stress, snm)
        #Normalize the on-diagonal elements
        indices = self.struc.lattice.stress_indices
        if len(indices) == 2:
            total = 0
            for index in indices:
                total += stress[index]        
            value = total**0.5
            for index in inices:
                m2[index] = value
        elif len(indices) == 3:
            total = 0
            for index in indices:
                total += stress[index]        
            value = np.cbrt(total)
            for index in inices:
                m2[index] = value
        return m2 
Example 4
Project: PyXtal   Author: qzhu2017   File: LJ.py    License: MIT License 6 votes vote down vote up
def symmetrized_stress(self, stress):
        #Make the matrix lower-diagonal
        for (i,j) in [(1,0),(2,1),(2,2)]:
            stress[i][j] = stress[i][j] + stress[j][i]
            stress[j][i] = 0
        #Normalize the matrix
        snm = self.struc.lattice.stress_normalization_matrix
        m2 = np.multiply(stress, snm)
        #Normalize the on-diagonal elements
        indices = self.struc.lattice.stress_indices
        if len(indices) == 2:
            total = 0
            for index in indices:
                total += stress[index]        
            value = np.sqrt(total)
            for index in inices:
                m2[index] = value
        elif len(indices) == 3:
            total = 0
            for index in indices:
                total += stress[index]        
            value = np.cbrt(total)
            for index in inices:
                m2[index] = value
        return m2 
Example 5
Project: PyXtal   Author: qzhu2017   File: operations.py    License: MIT License 6 votes vote down vote up
def random_shear_matrix(width=1.0, unitary=False):
    """
    Generate a random symmetric shear matrix with Gaussian elements. If unitary
    is True, normalize to determinant 1

    Args:
        width: the width of the normal distribution to use when choosing values.
            Passed to np.random.normal
        unitary: whether or not to normalize the matrix to determinant 1
    
    Returns:
        a 3x3 numpy array of floats
    """
    mat = np.zeros([3,3])
    determinant = 0
    while determinant == 0:
        a, b, c = np.random.normal(scale=width), np.random.normal(scale=width), np.random.normal(scale=width)
        mat = np.array([[1,a,b],[a,1,c],[b,c,1]])
        determinant = np.linalg.det(mat)
    if unitary:
        new = mat / np.cbrt(np.linalg.det(mat))
        return new
    else: return mat 
Example 6
Project: panel   Author: holoviz   File: vtk.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _subsample_array(self, array):
        original_shape = array.shape
        spacing = self.spacing
        extent = tuple((o_s - 1) * s for o_s, s in zip(original_shape, spacing))
        dim_ratio = np.cbrt((array.nbytes / 1e6) / self.max_data_size)
        max_shape = tuple(int(o_s / dim_ratio) for o_s in original_shape)
        dowsnscale_factor = [max(o_s, m_s) / m_s for m_s, o_s in zip(max_shape, original_shape)]

        if any([d_f > 1 for d_f in dowsnscale_factor]):
            try:
                import scipy.ndimage as nd
                sub_array = nd.interpolation.zoom(array, zoom=[1 / d_f for d_f in dowsnscale_factor], order=0)
            except ImportError:
                sub_array = array[::int(np.ceil(dowsnscale_factor[0])),
                                  ::int(np.ceil(dowsnscale_factor[1])),
                                  ::int(np.ceil(dowsnscale_factor[2]))]
            self._sub_spacing = tuple(e / (s - 1) for e, s in zip(extent, sub_array.shape))
        else:
            sub_array = array
            self._sub_spacing = self.spacing
        return sub_array 
Example 7
Project: floris   Author: NREL   File: turbine.py    License: Apache License 2.0 6 votes vote down vote up
def average_velocity(self):
        """
        This property calculates and returns the cube root of the
        mean cubed velocity in the turbine's rotor swept area (m/s).

        Returns:
            float: The average velocity across a rotor.

        Examples:
            To get the average velocity for a turbine:

            >>> avg_vel = floris.farm.turbines[0].average_velocity()
        """
        # remove all invalid numbers from interpolation
        data = self.velocities[np.where(~np.isnan(self.velocities))]
        avg_vel = np.cbrt(np.mean(data ** 3))
        if np.isnan(avg_vel):
            avg_vel = 0
        elif np.isinf(avg_vel):
            avg_vel = 0

        return avg_vel 
Example 8
Project: differential-privacy-library   Author: IBM   File: k_means.py    License: MIT License 5 votes vote down vote up
def _split_epsilon(self, dims, total_iters, rho=0.225):
        """Split epsilon between sum perturbation and count perturbation, as proposed by Su et al.

        Parameters
        ----------
        dims : int
            Number of dimensions to split `epsilon` across.

        total_iters : int
            Total number of iterations to split `epsilon` across.

        rho : float, default: 0.225
            Coordinate normalisation factor.

        Returns
        -------
        epsilon_0 : float
            The epsilon value for satisfying differential privacy on the count of a cluster.

        epsilon_i : float
            The epsilon value for satisfying differential privacy on each dimension of the center of a cluster.

        """
        epsilon_i = 1
        epsilon_0 = np.cbrt(4 * dims * rho ** 2)

        normaliser = self.epsilon / total_iters / (epsilon_i * dims + epsilon_0)

        return epsilon_i * normaliser, epsilon_0 * normaliser 
Example 9
Project: differential-privacy-library   Author: IBM   File: k_means.py    License: MIT License 5 votes vote down vote up
def _calc_iters(self, n_dims, n_samples, rho=0.225):
        """Calculate the number of iterations to allow for the KMeans algorithm."""

        epsilon_m = np.sqrt(500 * (self.n_clusters ** 3) / (n_samples ** 2) *
                            (n_dims + np.cbrt(4 * n_dims * (rho ** 2))) ** 3)

        iters = max(min(self.epsilon / epsilon_m, 7), 2)

        return int(iters) 
Example 10
Project: recruit   Author: Frank-qlu   File: test_umath.py    License: Apache License 2.0 5 votes vote down vote up
def test_cbrt_scalar(self):
        assert_almost_equal((np.cbrt(np.float32(-2.5)**3)), -2.5) 
Example 11
Project: recruit   Author: Frank-qlu   File: test_umath.py    License: Apache License 2.0 5 votes vote down vote up
def test_cbrt(self):
        x = np.array([1., 2., -3., np.inf, -np.inf])
        assert_almost_equal(np.cbrt(x**3), x)

        assert_(np.isnan(np.cbrt(np.nan)))
        assert_equal(np.cbrt(np.inf), np.inf)
        assert_equal(np.cbrt(-np.inf), -np.inf) 
Example 12
Project: PySpice   Author: FabriceSalvaire   File: Unit.py    License: GNU General Public License v3.0 5 votes vote down vote up
def cbrt(self):
        return self.power(1/3)

#################################################################################################### 
Example 13
Project: PySpice   Author: FabriceSalvaire   File: Unit.py    License: GNU General Public License v3.0 5 votes vote down vote up
def cbrt(self, prefixed_unit=False):
        si_unit = self._si_unit.cbrt()
        return self._equivalent_unit_or_power(si_unit, prefixed_unit)

    ############################################## 
Example 14
Project: mars   Author: mars-project   File: cbrt.py    License: Apache License 2.0 5 votes vote down vote up
def cbrt(x, out=None, where=None, **kwargs):
    """
    Return the cube-root of an tensor, element-wise.

    Parameters
    ----------
    x : array_like
        The values whose cube-roots are required.
    out : Tensor, None, or tuple of Tensor and None, optional
        A location into which the result is stored. If provided, it must have
        a shape that the inputs broadcast to. If not provided or `None`,
        a freshly-allocated tensor is returned. A tuple (possible only as a
        keyword argument) must have length equal to the number of outputs.
    where : array_like, optional
        Values of True indicate to calculate the ufunc at that position, values
        of False indicate to leave the value in the output alone.
    **kwargs

    Returns
    -------
    y : Tensor
        An tensor of the same shape as `x`, containing the cube
        cube-root of each element in `x`.
        If `out` was provided, `y` is a reference to it.


    Examples
    --------
    >>> import mars.tensor as mt

    >>> mt.cbrt([1,8,27]).execute()
    array([ 1.,  2.,  3.])
    """
    op = TensorCbrt(**kwargs)
    return op(x, out=out, where=where) 
Example 15
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_cbrt_scalar(self):
        assert_almost_equal((np.cbrt(np.float32(-2.5)**3)), -2.5) 
Example 16
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_cbrt(self):
        x = np.array([1., 2., -3., np.inf, -np.inf])
        assert_almost_equal(np.cbrt(x**3), x)

        assert_(np.isnan(np.cbrt(np.nan)))
        assert_equal(np.cbrt(np.inf), np.inf)
        assert_equal(np.cbrt(-np.inf), -np.inf) 
Example 17
Project: orbit-predictor   Author: satellogic   File: utils.py    License: MIT License 5 votes vote down vote up
def eclipse_duration(beta, period, r_p=R_E_MEAN_KM):
    """Eclipse duration, in minutes"""
    # Based on Vallado 4th ed., pp. 305
    # Circular orbital radius corresponding to given period
    r = np.cbrt(MU_E / (4 * pi ** 2) * (period * 60) ** 2)

    # We clip the argument of acos between -1 and 1
    # to return a eclipse duration of 0 when it is out of range
    return acos(
        np.clip(sqrt(1 - (r_p / r) ** 2) / cos(radians(beta)), -1, 1)
    ) * period / pi 
Example 18
Project: vnpy_crypto   Author: birforce   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_cbrt_scalar(self):
        assert_almost_equal((np.cbrt(np.float32(-2.5)**3)), -2.5) 
Example 19
Project: vnpy_crypto   Author: birforce   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_cbrt(self):
        x = np.array([1., 2., -3., np.inf, -np.inf])
        assert_almost_equal(np.cbrt(x**3), x)

        assert_(np.isnan(np.cbrt(np.nan)))
        assert_equal(np.cbrt(np.inf), np.inf)
        assert_equal(np.cbrt(-np.inf), -np.inf) 
Example 20
Project: RaptorX-Contact   Author: j3xugit   File: DataProcessor.py    License: GNU General Public License v3.0 5 votes vote down vote up
def CubeRootFeature(d):
	##the cube root of the difference between the two positions, the radius of protein is related to this feature
    	seqLen = len(d['sequence'])
	feature = []
	for i in range(seqLen):
		dVector = [ abs(j-i) for j in range(seqLen) ]
		feature.append(dVector)
	posFeature = np.cbrt( np.array( feature ).astype(theano.config.floatX) )
	return posFeature
	
## load native distance matrix from a file 
Example 21
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_cbrt_scalar(self):
        assert_almost_equal((np.cbrt(np.float32(-2.5)**3)), -2.5) 
Example 22
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_cbrt(self):
        x = np.array([1., 2., -3., np.inf, -np.inf])
        assert_almost_equal(np.cbrt(x**3), x)

        assert_(np.isnan(np.cbrt(np.nan)))
        assert_equal(np.cbrt(np.inf), np.inf)
        assert_equal(np.cbrt(-np.inf), -np.inf) 
Example 23
Project: trax   Author: google   File: math_ops.py    License: Apache License 2.0 5 votes vote down vote up
def cbrt(x):
  def f(x):
    # __pow__ can't handle negative base, so we use `abs` here.
    rt = tf.math.abs(x) ** (1.0 / 3)
    return tf.where(x < 0, -rt, rt)
  return _scalar(f, x, True) 
Example 24
Project: deep_pipe   Author: neuro-ml   File: itertools.py    License: MIT License 5 votes vote down vote up
def pam(functions: Iterable[Callable], *args, **kwargs):
    """
    Inverse of `map`. Apply a sequence of callables to fixed arguments.

    Examples
    --------
    >>> list(pam([np.sqrt, np.square, np.cbrt], 64))
    [8, 4096, 4]
    """
    for f in functions:
        yield f(*args, **kwargs) 
Example 25
Project: 6-PACK   Author: j96w   File: eval_dataset_nocs.py    License: MIT License 5 votes vote down vote up
def get_pose(self, choose_frame, choose_obj):
        has_pose = []
        pose = {}
        with open('{0}/data/gts/real_test/results_real_test_{1}_{2}.pkl'.format(self.root, choose_frame.split("/")[-2], choose_frame.split("/")[-1]), 'rb') as f:
            nocs_data = cPickle.load(f)
        for idx in range(nocs_data['gt_RTs'].shape[0]):
            idx = idx + 1
            pose[idx] = nocs_data['gt_RTs'][idx-1]
            pose[idx][:3, :3] = pose[idx][:3, :3] / np.cbrt(np.linalg.det(pose[idx][:3, :3]))
            z_180_RT = np.zeros((4, 4), dtype=np.float32)
            z_180_RT[:3, :3] = np.diag([-1, -1, 1])
            z_180_RT[3, 3] = 1
            pose[idx] = z_180_RT @ pose[idx]
            pose[idx][:3,3] = pose[idx][:3,3] * 1000

        input_file = open('{0}_meta.txt'.format(choose_frame), 'r')
        while 1:
            input_line = input_file.readline()
            if not input_line:
                break
            if input_line[-1:] == '\n':
                input_line = input_line[:-1]
            input_line = input_line.split(' ')
            if input_line[-1] == choose_obj:
                ans = pose[int(input_line[0])]
                ans_idx = int(input_line[0])
                break
        input_file.close()

        ans = np.array(ans)
        ans_r = ans[:3, :3]
        ans_t = ans[:3, 3].flatten()

        return ans_r, ans_t, ans_idx 
Example 26
Project: 6-PACK   Author: j96w   File: benchmark.py    License: MIT License 5 votes vote down vote up
def compute_RT_degree_cm_symmetry(RT_1, RT_2, class_id, handle_visibility, synset_names):
    if RT_1 is None or RT_2 is None:
        return 10000,10000
    try:
        assert np.array_equal(RT_1[3, :], RT_2[3, :])
        assert np.array_equal(RT_1[3, :], np.array([0, 0, 0, 1]))
    except AssertionError:
        return 10000,10000

    R1 = RT_1[:3, :3] / np.cbrt(np.linalg.det(RT_1[:3, :3]))
    T1 = RT_1[:3, 3]

    R2 = RT_2[:3, :3] / np.cbrt(np.linalg.det(RT_2[:3, :3]))
    T2 = RT_2[:3, 3]

    if synset_names[class_id] in ['bottle', 'can', 'bowl']:
        y = np.array([0, 1, 0])
        y1 = R1 @ y
        y2 = R2 @ y
        theta = np.arccos(y1.dot(y2) / (np.linalg.norm(y1) * np.linalg.norm(y2)))
    elif synset_names[class_id] == 'mug' and handle_visibility==0:
        y = np.array([0, 1, 0])
        y1 = R1 @ y
        y2 = R2 @ y
        theta = np.arccos(y1.dot(y2) / (np.linalg.norm(y1) * np.linalg.norm(y2)))
    elif synset_names[class_id] in ['phone', 'eggbox', 'glue']:
        y_180_RT = np.diag([-1.0, 1.0, -1.0])
        R = R1 @ R2.transpose()
        R_rot = R1 @ y_180_RT @ R2.transpose()
        theta = min(np.arccos((np.trace(R) - 1) / 2),
                    np.arccos((np.trace(R_rot) - 1) / 2))
    else:
        R = R1 @ R2.transpose()
        theta = np.arccos((np.trace(R) - 1) / 2)

    theta *= 180 / np.pi
    shift = np.linalg.norm(T1 - T2)
    result = np.array([theta, shift])

    return result 
Example 27
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_cbrt_scalar(self):
        assert_almost_equal((np.cbrt(np.float32(-2.5)**3)), -2.5) 
Example 28
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_cbrt(self):
        x = np.array([1., 2., -3., np.inf, -np.inf])
        assert_almost_equal(np.cbrt(x**3), x)

        assert_(np.isnan(np.cbrt(np.nan)))
        assert_equal(np.cbrt(np.inf), np.inf)
        assert_equal(np.cbrt(-np.inf), -np.inf) 
Example 29
def test_cbrt_scalar(self):
        assert_almost_equal((np.cbrt(np.float32(-2.5)**3)), -2.5) 
Example 30
def test_cbrt(self):
        x = np.array([1., 2., -3., np.inf, -np.inf])
        assert_almost_equal(np.cbrt(x**3), x)

        assert_(np.isnan(np.cbrt(np.nan)))
        assert_equal(np.cbrt(np.inf), np.inf)
        assert_equal(np.cbrt(-np.inf), -np.inf)