Python numpy.errstate() Examples

The following are 30 code examples for showing how to use numpy.errstate(). 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: pyscf   Author: pyscf   File: thermo.py    License: Apache License 2.0 6 votes vote down vote up
def rotation_const(mass, atom_coords, unit='GHz'):
    '''Rotational constants to characterize rotational spectra

    Kwargs:
        unit (string) : One of GHz, wavenumber
    '''
    mass_center = numpy.einsum('z,zr->r', mass, atom_coords) / mass.sum()
    r = atom_coords - mass_center
    im = numpy.einsum('z,zr,zs->rs', mass, r, r)
    im = numpy.eye(3) * im.trace() - im
    e = numpy.sort(numpy.linalg.eigvalsh(im))

    unit_im = nist.ATOMIC_MASS * (nist.BOHR_SI)**2
    unit_hz = nist.HBAR / (4 * numpy.pi * unit_im)
    with numpy.errstate(divide='ignore'):
        if unit.lower() == 'ghz':
            e = unit_hz / e * 1e-9
        elif unit.lower() == 'wavenumber':
            e = unit_hz / e / nist.LIGHT_SPEED_SI * 1e-2
        else:
            raise RuntimeError('Unsupported unit ' + unit)
    return e 
Example 2
Project: python-control   Author: python-control   File: grid.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __call__(self, transform_xy, x1, y1, x2, y2):
        x_, y_ = np.linspace(x1, x2, self.nx), np.linspace(y1, y2, self.ny)
        x, y = np.meshgrid(x_, y_)
        lon, lat = transform_xy(np.ravel(x), np.ravel(y))

        with np.errstate(invalid='ignore'):
            if self.lon_cycle is not None:
                lon0 = np.nanmin(lon)
                # Changed from 180 to 360 to be able to span only
                # 90-270 (left hand side)
                lon -= 360. * ((lon - lon0) > 360.)
            if self.lat_cycle is not None:
                lat0 = np.nanmin(lat)
                # Changed from 180 to 360 to be able to span only
                # 90-270 (left hand side)
                lat -= 360. * ((lat - lat0) > 360.)

        lon_min, lon_max = np.nanmin(lon), np.nanmax(lon)
        lat_min, lat_max = np.nanmin(lat), np.nanmax(lat)

        lon_min, lon_max, lat_min, lat_max = \
            self._adjust_extremes(lon_min, lon_max, lat_min, lat_max)

        return lon_min, lon_max, lat_min, lat_max 
Example 3
Project: quail   Author: ContextLab   File: helpers.py    License: MIT License 6 votes vote down vote up
def r2z(r):
    """
    Function that calculates the Fisher z-transformation

    Parameters
    ----------
    r : int or ndarray
        Correlation value

    Returns
    ----------
    result : int or ndarray
        Fishers z transformed correlation value


    """
    with np.errstate(invalid='ignore', divide='ignore'):
        return 0.5 * (np.log(1 + r) - np.log(1 - r)) 
Example 4
Project: quail   Author: ContextLab   File: helpers.py    License: MIT License 6 votes vote down vote up
def z2r(z):
    """
    Function that calculates the inverse Fisher z-transformation

    Parameters
    ----------
    z : int or ndarray
        Fishers z transformed correlation value

    Returns
    ----------
    result : int or ndarray
        Correlation value


    """
    with np.errstate(invalid='ignore', divide='ignore'):
        return (np.exp(2 * z) - 1) / (np.exp(2 * z) + 1) 
Example 5
Project: recruit   Author: Frank-qlu   File: test_type_check.py    License: Apache License 2.0 6 votes vote down vote up
def test_generic(self):
        with np.errstate(divide='ignore', invalid='ignore'):
            vals = nan_to_num(np.array((-1., 0, 1))/0.)
        assert_all(vals[0] < -1e10) and assert_all(np.isfinite(vals[0]))
        assert_(vals[1] == 0)
        assert_all(vals[2] > 1e10) and assert_all(np.isfinite(vals[2]))
        assert_equal(type(vals), np.ndarray)

        # perform the same test but in-place
        with np.errstate(divide='ignore', invalid='ignore'):
            vals = np.array((-1., 0, 1))/0.
        result = nan_to_num(vals, copy=False)

        assert_(result is vals)
        assert_all(vals[0] < -1e10) and assert_all(np.isfinite(vals[0]))
        assert_(vals[1] == 0)
        assert_all(vals[2] > 1e10) and assert_all(np.isfinite(vals[2]))
        assert_equal(type(vals), np.ndarray) 
Example 6
Project: recruit   Author: Frank-qlu   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def gisinf(x):
    """like isinf, but always raise an error if type not supported instead of
    returning a TypeError object.

    Notes
    -----
    isinf and other ufunc sometimes return a NotImplementedType object instead
    of raising any exception. This function is a wrapper to make sure an
    exception is always raised.

    This should be removed once this problem is solved at the Ufunc level."""
    from numpy.core import isinf, errstate
    with errstate(invalid='ignore'):
        st = isinf(x)
        if isinstance(st, type(NotImplemented)):
            raise TypeError("isinf not supported for this type")
    return st 
Example 7
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 6 votes vote down vote up
def test_warnings(self):
        # test warning code path
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            with np.errstate(all="warn"):
                np.divide(1, 0.)
                assert_equal(len(w), 1)
                assert_("divide by zero" in str(w[0].message))
                np.array(1e300) * np.array(1e300)
                assert_equal(len(w), 2)
                assert_("overflow" in str(w[-1].message))
                np.array(np.inf) - np.array(np.inf)
                assert_equal(len(w), 3)
                assert_("invalid value" in str(w[-1].message))
                np.array(1e-300) * np.array(1e-300)
                assert_equal(len(w), 4)
                assert_("underflow" in str(w[-1].message)) 
Example 8
Project: recruit   Author: Frank-qlu   File: test_getlimits.py    License: Apache License 2.0 6 votes vote down vote up
def test_known_types():
    # Test we are correctly compiling parameters for known types
    for ftype, ma_like in ((np.float16, _float_ma[16]),
                           (np.float32, _float_ma[32]),
                           (np.float64, _float_ma[64])):
        assert_ma_equal(_discovered_machar(ftype), ma_like)
    # Suppress warning for broken discovery of double double on PPC
    with np.errstate(all='ignore'):
        ld_ma = _discovered_machar(np.longdouble)
    bytes = np.dtype(np.longdouble).itemsize
    if (ld_ma.it, ld_ma.maxexp) == (63, 16384) and bytes in (12, 16):
        # 80-bit extended precision
        assert_ma_equal(ld_ma, _float_ma[80])
    elif (ld_ma.it, ld_ma.maxexp) == (112, 16384) and bytes == 16:
        # IEE 754 128-bit
        assert_ma_equal(ld_ma, _float_ma[128]) 
Example 9
Project: recruit   Author: Frank-qlu   File: test_umath.py    License: Apache License 2.0 6 votes vote down vote up
def test_complex_nan_comparisons():
    nans = [complex(np.nan, 0), complex(0, np.nan), complex(np.nan, np.nan)]
    fins = [complex(1, 0), complex(-1, 0), complex(0, 1), complex(0, -1),
            complex(1, 1), complex(-1, -1), complex(0, 0)]

    with np.errstate(invalid='ignore'):
        for x in nans + fins:
            x = np.array([x])
            for y in nans + fins:
                y = np.array([y])

                if np.isfinite(x) and np.isfinite(y):
                    continue

                assert_equal(x < y, False, err_msg="%r < %r" % (x, y))
                assert_equal(x > y, False, err_msg="%r > %r" % (x, y))
                assert_equal(x <= y, False, err_msg="%r <= %r" % (x, y))
                assert_equal(x >= y, False, err_msg="%r >= %r" % (x, y))
                assert_equal(x == y, False, err_msg="%r == %r" % (x, y)) 
Example 10
Project: recruit   Author: Frank-qlu   File: test_scalarmath.py    License: Apache License 2.0 6 votes vote down vote up
def test_zero_division(self):
        with np.errstate(all="ignore"):
            for t in [np.complex64, np.complex128]:
                a = t(0.0)
                b = t(1.0)
                assert_(np.isinf(b/a))
                b = t(complex(np.inf, np.inf))
                assert_(np.isinf(b/a))
                b = t(complex(np.inf, np.nan))
                assert_(np.isinf(b/a))
                b = t(complex(np.nan, np.inf))
                assert_(np.isinf(b/a))
                b = t(complex(np.nan, np.nan))
                assert_(np.isnan(b/a))
                b = t(0.)
                assert_(np.isnan(b/a)) 
Example 11
Project: recruit   Author: Frank-qlu   File: test_scalarmath.py    License: Apache License 2.0 6 votes vote down vote up
def test_signed_zeros(self):
        with np.errstate(all="ignore"):
            for t in [np.complex64, np.complex128]:
                # tupled (numerator, denominator, expected)
                # for testing as expected == numerator/denominator
                data = (
                    (( 0.0,-1.0), ( 0.0, 1.0), (-1.0,-0.0)),
                    (( 0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)),
                    (( 0.0,-1.0), (-0.0,-1.0), ( 1.0, 0.0)),
                    (( 0.0,-1.0), (-0.0, 1.0), (-1.0, 0.0)),
                    (( 0.0, 1.0), ( 0.0,-1.0), (-1.0, 0.0)),
                    (( 0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)),
                    ((-0.0,-1.0), ( 0.0,-1.0), ( 1.0,-0.0)),
                    ((-0.0, 1.0), ( 0.0,-1.0), (-1.0,-0.0))
                )
                for cases in data:
                    n = cases[0]
                    d = cases[1]
                    ex = cases[2]
                    result = t(complex(n[0], n[1])) / t(complex(d[0], d[1]))
                    # check real and imag parts separately to avoid comparison
                    # in array context, which does not account for signed zeros
                    assert_equal(result.real, ex[0])
                    assert_equal(result.imag, ex[1]) 
Example 12
Project: recruit   Author: Frank-qlu   File: methods.py    License: Apache License 2.0 6 votes vote down vote up
def test_combine_add(self, data_repeated):
        # GH 20825
        orig_data1, orig_data2 = data_repeated(2)
        s1 = pd.Series(orig_data1)
        s2 = pd.Series(orig_data2)
        result = s1.combine(s2, lambda x1, x2: x1 + x2)
        with np.errstate(over='ignore'):
            expected = pd.Series(
                orig_data1._from_sequence([a + b for (a, b) in
                                           zip(list(orig_data1),
                                               list(orig_data2))]))
        self.assert_series_equal(result, expected)

        val = s1.iloc[0]
        result = s1.combine(val, lambda x1, x2: x1 + x2)
        expected = pd.Series(
            orig_data1._from_sequence([a + val for a in list(orig_data1)]))
        self.assert_series_equal(result, expected) 
Example 13
Project: EXOSIMS   Author: dsavransky   File: test_deltaMag.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test1(self):
        r"""Testing some limiting cases."""
        p   = np.array([0.0,1.0,1.0,1.0,1.0]) 
        Rp  = np.array([1.0,0.0,1.0,1.0,1.0]) * u.kilometer
        d   = np.array([1.0,1.0,0.0,1.0,np.inf]) * u.kilometer
        Phi = np.array([1.0,1.0,1.0,0.0,1.0])
        # suppress division-by-zero warnings
        with np.errstate(divide='ignore'):
            result = deltaMag(p, Rp, d, Phi)
        expected = np.array([np.inf, np.inf, -np.inf, np.inf, np.inf])
        np.testing.assert_allclose(expected, result, rtol=1e-1, atol=0) 
Example 14
Project: differential-privacy-library   Author: IBM   File: standard_scaler.py    License: MIT License 5 votes vote down vote up
def _incremental_mean_and_var(X, epsilon, bounds, last_mean, last_variance, last_sample_count):
    # Initialising new accountant, as budget is tracked in main class. Subject to review in line with GH issue #21
    temp_acc = BudgetAccountant()

    # old = stats until now
    # new = the current increment
    # updated = the aggregated stats
    last_sum = last_mean * last_sample_count

    new_mean = nanmean(X, epsilon=epsilon, axis=0, bounds=bounds, accountant=temp_acc)
    new_sample_count = np.sum(~np.isnan(X), axis=0)
    new_sum = new_mean * new_sample_count
    updated_sample_count = last_sample_count + new_sample_count

    updated_mean = (last_sum + new_sum) / updated_sample_count

    if last_variance is None:
        updated_variance = None
    else:
        new_unnormalized_variance = nanvar(X, epsilon=epsilon, axis=0, bounds=bounds,
                                           accountant=temp_acc) * new_sample_count
        last_unnormalized_variance = last_variance * last_sample_count

        with np.errstate(divide='ignore', invalid='ignore'):
            last_over_new_count = last_sample_count / new_sample_count
            updated_unnormalized_variance = (
                last_unnormalized_variance + new_unnormalized_variance +
                last_over_new_count / updated_sample_count *
                (last_sum / last_over_new_count - new_sum) ** 2)

        zeros = last_sample_count == 0
        updated_unnormalized_variance[zeros] = new_unnormalized_variance[zeros]
        updated_variance = updated_unnormalized_variance / updated_sample_count

    return updated_mean, updated_variance, updated_sample_count


# noinspection PyPep8Naming,PyAttributeOutsideInit 
Example 15
Project: pymoo   Author: msu-coinlab   File: mw.py    License: Apache License 2.0 5 votes vote down vote up
def _evaluate(self, X, out, *args, **kwargs):
        g = self.g1(X)
        f0 = g * X[:, 0]
        f1 = g * np.sqrt(1.0 - np.power(f0 / g, 2.0))

        with np.errstate(divide='ignore'):
            atan = np.arctan(f1 / f0)

        g0 = f0 ** 2 + f1 ** 2 - np.power(1.7 - self.LA2(0.2, 2.0, 1.0, 1.0, atan), 2.0)
        t = 0.5 * np.pi - 2 * np.abs(atan - 0.25 * np.pi)
        g1 = np.power(1 + self.LA2(0.5, 6.0, 3.0, 1.0, t), 2.0) - f0 ** 2 - f1 ** 2
        g2 = np.power(1 - self.LA2(0.45, 6.0, 3.0, 1.0, t), 2.0) - f0 ** 2 - f1 ** 2
        out["F"] = np.column_stack([f0, f1])
        out["G"] = np.column_stack([g0, g1, g2]) 
Example 16
Project: pymoo   Author: msu-coinlab   File: mw.py    License: Apache License 2.0 5 votes vote down vote up
def _evaluate(self, X, out, *args, **kwargs):
        g = self.g2(X)
        f0 = g * X[:, 0]
        f1 = g * np.sqrt(1.1 * 1.1 - np.power(f0 / g, 2.0))

        with np.errstate(divide='ignore'):
            atan = np.arctan(f1 / f0)

        g0 = f0 ** 2 / np.power(1.0 + self.LA3(0.15, 6.0, 4.0, 10.0, atan), 2.0) + f1 ** 2 / np.power(
            1.0 + self.LA3(0.75, 6.0, 4.0, 10.0, atan), 2.0) - 1
        out["F"] = np.column_stack([f0, f1])
        out["G"] = g0.reshape((-1, 1)) 
Example 17
Project: pymoo   Author: msu-coinlab   File: mw.py    License: Apache License 2.0 5 votes vote down vote up
def _evaluate(self, X, out, *args, **kwargs):
        g = self.g3(X)
        f0 = g * X[:, 0]
        f1 = g * np.sqrt(1 - np.power(f0 / g, 2))

        with np.errstate(divide='ignore'):
            atan = np.arctan(f1 / f0)

        g0 = f0 ** 2 + f1 ** 2 - np.power(1.2 + np.abs(self.LA2(0.4, 4.0, 1.0, 16.0, atan)), 2.0)
        g1 = np.power(1.15 - self.LA2(0.2, 4.0, 1.0, 8.0, atan), 2.0) - f0 ** 2 - f1 ** 2
        out["F"] = np.column_stack([f0, f1])
        out["G"] = np.column_stack([g0, g1]) 
Example 18
Project: pyscf   Author: pyscf   File: test_pp.py    License: Apache License 2.0 5 votes vote down vote up
def get_pp_loc_part2(cell, kpt=np.zeros(3)):
    coords = gen_grid.gen_uniform_grids(cell)
    aoR = numint.eval_ao(cell, coords, kpt)
    nao = cell.nao_nr()

    SI = cell.get_SI()
    G = lib.norm(cell.Gv, axis=1)
    vlocG = np.zeros((cell.natm,len(G)))
    for ia in range(cell.natm):
        Zia = cell.atom_charge(ia)
        symb = cell.atom_symbol(ia)
        if symb not in cell._pseudo:
            vlocG[ia] = 0
            continue
        pp = cell._pseudo[symb]
        rloc, nexp, cexp = pp[1:3+1]

        G_red = G*rloc
        cfacs = np.array(
                [1*G_red**0,
                 3 - G_red**2,
                 15 - 10*G_red**2 + G_red**4,
                 105 - 105*G_red**2 + 21*G_red**4 - G_red**6])

        with np.errstate(divide='ignore'):
            # Note the signs -- potential here is positive
            vlocG[ia,:] = (# 4*np.pi * Zia * np.exp(-0.5*G_red**2)/G**2
                           - (2*np.pi)**(3/2.)*rloc**3*np.exp(-0.5*G_red**2)*(
                                np.dot(cexp, cfacs[:nexp])) )

    vpplocG = -np.sum(SI * vlocG, axis=0)
    vpplocR = tools.ifft(vpplocG, cell.mesh).real
    vpploc = np.dot(aoR.T.conj(), vpplocR.reshape(-1,1)*aoR)
    if aoR.dtype == np.double:
        return vpploc.real
    else:
        return vpploc 
Example 19
Project: pyGSTi   Author: pyGSTio   File: scoring.py    License: Apache License 2.0 5 votes vote down vote up
def list_score(input_array, scoreFunc='all'):
    """Score an array of eigenvalues. Smaller scores are better.

    Parameters
    ----------
    input_array : numpy array
        The eigenvalues to be scored.

    scoreFunc : {'all', 'worst'}, optional
        Sets the objective function for scoring the eigenvalues. If 'all',
        score is ``sum(1/input_array)``. If 'worst', score is
        ``1/min(input_array)``.

        Note: we use this function in various optimization routines, and
        sometimes choosing one or the other objective function can help avoid
        suboptimal local minima.

    Returns
    -------
    float
        Score for the eigenvalues.

    """
    # We're expecting division by zero in many instances when we call this
    # function, and the inf can be handled appropriately, so we suppress
    # division warnings printed to stderr.
    with _np.errstate(divide='ignore'):
        if scoreFunc == 'all':
            score = sum(1. / _np.abs(input_array))
        elif scoreFunc == 'worst':
            score = 1. / min(_np.abs(input_array))
        else:
            raise ValueError("'%s' is not a valid value for scoreFunc.  "
                             "Either 'all' or 'worst' must be specified!"
                             % scoreFunc)

    return score 
Example 20
Project: recruit   Author: Frank-qlu   File: test_masked_matrix.py    License: Apache License 2.0 5 votes vote down vote up
def test_masked_unary_operations(self):
        # Tests masked_unary_operation
        (x, mx) = self.data
        with np.errstate(divide='ignore'):
            assert_(isinstance(log(mx), MMatrix))
            assert_equal(log(x), np.log(x)) 
Example 21
Project: recruit   Author: Frank-qlu   File: nanfunctions.py    License: Apache License 2.0 5 votes vote down vote up
def _divide_by_count(a, b, out=None):
    """
    Compute a/b ignoring invalid results. If `a` is an array the division
    is done in place. If `a` is a scalar, then its type is preserved in the
    output. If out is None, then then a is used instead so that the
    division is in place. Note that this is only called with `a` an inexact
    type.

    Parameters
    ----------
    a : {ndarray, numpy scalar}
        Numerator. Expected to be of inexact type but not checked.
    b : {ndarray, numpy scalar}
        Denominator.
    out : ndarray, optional
        Alternate output array in which to place the result.  The default
        is ``None``; if provided, it must have the same shape as the
        expected output, but the type will be cast if necessary.

    Returns
    -------
    ret : {ndarray, numpy scalar}
        The return value is a/b. If `a` was an ndarray the division is done
        in place. If `a` is a numpy scalar, the division preserves its type.

    """
    with np.errstate(invalid='ignore', divide='ignore'):
        if isinstance(a, np.ndarray):
            if out is None:
                return np.divide(a, b, out=a, casting='unsafe')
            else:
                return np.divide(a, b, out=out, casting='unsafe')
        else:
            if out is None:
                return a.dtype.type(a / b)
            else:
                # This is questionable, but currently a numpy scalar can
                # be output to a zero dimensional array.
                return np.divide(a, b, out=out, casting='unsafe') 
Example 22
Project: recruit   Author: Frank-qlu   File: test_function_base.py    License: Apache License 2.0 5 votes vote down vote up
def test_extreme(self):
        x = [[1e-100, 1e100], [1e100, 1e-100]]
        with np.errstate(all='raise'):
            c = corrcoef(x)
        assert_array_almost_equal(c, np.array([[1., -1.], [-1., 1.]]))
        assert_(np.all(np.abs(c) <= 1.0)) 
Example 23
Project: recruit   Author: Frank-qlu   File: test_type_check.py    License: Apache License 2.0 5 votes vote down vote up
def test_posinf(self):
        with np.errstate(divide='ignore'):
            assert_all(np.isnan(np.array((1.,))/0.) == 0) 
Example 24
Project: recruit   Author: Frank-qlu   File: test_type_check.py    License: Apache License 2.0 5 votes vote down vote up
def test_neginf(self):
        with np.errstate(divide='ignore'):
            assert_all(np.isnan(np.array((-1.,))/0.) == 0) 
Example 25
Project: recruit   Author: Frank-qlu   File: test_type_check.py    License: Apache License 2.0 5 votes vote down vote up
def test_complex1(self):
        with np.errstate(divide='ignore', invalid='ignore'):
            assert_all(np.isnan(np.array(0+0j)/0.) == 1) 
Example 26
Project: recruit   Author: Frank-qlu   File: test_type_check.py    License: Apache License 2.0 5 votes vote down vote up
def test_posinf(self):
        with np.errstate(divide='ignore', invalid='ignore'):
            assert_all(np.isfinite(np.array((1.,))/0.) == 0) 
Example 27
Project: recruit   Author: Frank-qlu   File: test_type_check.py    License: Apache License 2.0 5 votes vote down vote up
def test_neginf(self):
        with np.errstate(divide='ignore', invalid='ignore'):
            assert_all(np.isfinite(np.array((-1.,))/0.) == 0) 
Example 28
Project: recruit   Author: Frank-qlu   File: test_type_check.py    License: Apache License 2.0 5 votes vote down vote up
def test_ind(self):
        with np.errstate(divide='ignore', invalid='ignore'):
            assert_all(np.isfinite(np.array((0.,))/0.) == 0) 
Example 29
Project: recruit   Author: Frank-qlu   File: test_type_check.py    License: Apache License 2.0 5 votes vote down vote up
def test_complex1(self):
        with np.errstate(divide='ignore', invalid='ignore'):
            assert_all(np.isfinite(np.array(1+1j)/0.) == 0) 
Example 30
Project: recruit   Author: Frank-qlu   File: test_type_check.py    License: Apache License 2.0 5 votes vote down vote up
def test_posinf_scalar(self):
        with np.errstate(divide='ignore', invalid='ignore'):
            assert_all(np.isinf(np.array(1.,)/0.) == 1)