python类errstate()的实例源码

test_numeric.py 文件源码 项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda 作者: SignalMedia 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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.)
                self.assertEqual(len(w), 1)
                self.assertTrue("divide by zero" in str(w[0].message))
                np.array(1e300) * np.array(1e300)
                self.assertEqual(len(w), 2)
                self.assertTrue("overflow" in str(w[-1].message))
                np.array(np.inf) - np.array(np.inf)
                self.assertEqual(len(w), 3)
                self.assertTrue("invalid value" in str(w[-1].message))
                np.array(1e-300) * np.array(1e-300)
                self.assertEqual(len(w), 4)
                self.assertTrue("underflow" in str(w[-1].message))
domain.py 文件源码 项目:pyballd 作者: Yurlungur 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def get_drdX(self,X):
        "Derivative of radial coordinate with respect to compactified"
        dXdr = self.get_dXdr(X)
        with np.errstate(invalid='ignore'):
            drdX = 1./dXdr
        return drdX
domain.py 文件源码 项目:pyballd 作者: Yurlungur 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get_d2rdX2(self,X):
        "Second derivative of radial coordinate with respect to compactified"
        d2Xdr2 = self.get_d2Xdr2(X)
        with np.errstate(invalid='ignore'):
            d2rdX2 = 1./d2Xdr2
        return d2rdX2
domain.py 文件源码 项目:pyballd 作者: Yurlungur 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get_X_from_x(self,x):
        "X is x compactified"
        L = self.L
        with np.errstate(invalid='ignore'):
            X = (x-L)/(x+L)
        return X
domain.py 文件源码 项目:pyballd 作者: Yurlungur 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def get_x_from_X(self,X):
        "X is x compactified"
        L = self.L
        with np.errstate(invalid='ignore'):
            x = L*(1+X)/(1-X)
        return x
test_array_utils.py 文件源码 项目:npstreams 作者: LaurentRDC 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_generic(self):
        """ Test that NaNs are replaced with a fill value """
        with np.errstate(divide='ignore', invalid='ignore'):
            vals = nan_to_num(np.array([0])/0., fill_value = 14)
        self.assertEqual(vals[0], 14)
metrics.py 文件源码 项目:GraphTime 作者: GlooperLabs 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def f_score(Theta_true, Theta_est, beta=1, eps=1e-6, per_ts=False):
    """Compute f1 score in the same manner as `precision` and `recall`.
    Therefore see those two functions for the respective waiting and per_ts
    explanation.

    Parameters
    ----------
    Theta_true : 3D ndarray, shape (timesteps, n_vertices, n_vertices)
    Theta_est : 3D ndarray, shape (timesteps, n_vertices, n_vertices)
    beta : float (default 1)
        beta value of the F score to be computed
    eps : float
    per_ts : bool
        whether to compute average or per timestep recall

    Returns
    -------
    ndarray or float
        recall list or single precision value
    """
    prec = precision(Theta_true, Theta_est, eps, per_ts=True)
    rec = recall(Theta_true, Theta_est, eps, per_ts=True)
    with np.errstate(divide='ignore', invalid='ignore'):
        nom = (1 + beta**2) * prec * rec
        print(beta**2 * prec)
        den = beta**2 * prec + rec
        f = np.nan_to_num(np.true_divide(nom, den))
    return f if per_ts else np.sum(f) / len(Theta_true)
metrics.py 文件源码 项目:GraphTime 作者: GlooperLabs 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def global_f_score(Theta_true, Theta_est, beta=1, eps=1e-6):
    """In line with `global_precision` and `global_recall`, compute the
    global f score given true and estimated graphical structures. The
    f score has the only parameter beta.

    Parameters
    ----------
    Theta_true : 3D ndarray, shape (timesteps, n_vertices, n_vertices)
    Theta_est : 3D ndarray, shape (timesteps, n_vertices, n_vertices)
    beta : float (default 1)
        beta value of the F score to be computed
    eps : float
    per_ts : bool
        whether to compute average or per timestep recall

    Returns
    -------
    float f-beta score
    """
    assert Theta_est.shape == Theta_true.shape
    d = Theta_true.shape[1]
    n = len(Theta_est)
    tps = fps = fns = tns = 0
    for i in range(n):
        est_edges = set(get_edges(Theta_est[i], eps))
        gt_edges = set(get_edges(Theta_true[i], eps))
        n_joint = len(est_edges.intersection(gt_edges))
        tps += n_joint
        fps += len(est_edges) - n_joint
        fns += len(gt_edges) - n_joint
        tns += d**2 - d - tps - fps - fns
    nom = (1 + beta**2) * tps
    denom = nom + beta**2 * fns + fps
    with np.errstate(divide='ignore', invalid='ignore'):
        f = np.nan_to_num(np.true_divide(nom, denom))
        return f
PsiMarginal.py 文件源码 项目:Psi-staircase 作者: NNiehof 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def __entropy(self, pdf):
        """Calculate shannon entropy of posterior distribution.
        Arguments
        ---------
            pdf :   ndarray (float64)
                    posterior distribution of psychometric curve parameters for each stimuli


        Returns
        -------
        1D numpy array (float64) : Shannon entropy of posterior for each stimuli
        """
        # Marginalize out all nuisance parameters, i.e. all except alpha and sigma
        postDims = np.ndim(pdf)
        if self.marginalize == True:
            while postDims > 3:  # marginalize out second-to-last dimension, last dim is x
                pdf = np.sum(pdf, axis=-2)
                postDims -= 1
        # find expected entropy, suppress divide-by-zero and invalid value warnings
        # as this is handled by the NaN redefinition to 0
        with np.errstate(divide='ignore', invalid='ignore'):
            entropy = np.multiply(pdf, np.log(pdf))
        entropy[np.isnan(entropy)] = 0  # define 0*log(0) to equal 0
        dimSum = tuple(range(postDims - 1))  # dimensions to sum over. also a Chinese dish
        entropy = -(np.sum(entropy, axis=dimSum))
        return entropy
crosstalk_deprojection.py 文件源码 项目:atoolbox 作者: liweitianux 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def estimate_errors(self, gehrels=True):
        """
        Estimate the statistical errors of each spectral group (after
        applying grouping) for the source spectrum (and background spectrum).

        If `gehrels=True', the statistical error for a spectral group with
        N photons is given by `1 + sqrt(N + 0.75)'; otherwise, the error
        is given by `sqrt(N)'.

        Attributes
        ----------
        spec_err : `~numpy.ndarray`
            Estimated errors for the spectral data.
            NOTE: If the spectral data (in counts) have negative groups, the
                  errors of those groups are set to 0.0!
        """
        with np.errstate(invalid="ignore"):
            if gehrels:
                self.spec_err = 1.0 + np.sqrt(self.spec_data + 0.75)
            else:
                self.spec_err = np.sqrt(self.spec_data)
        # Warn about and fix the invalid error values
        invalid = ~np.isfinite(self.spec_err)
        if np.sum(invalid) > 0:
            print("WARNING: invalid spectral errors are set to 0.0! " +
                  "(due to negative spectral group counts)")
            self.spec_err[invalid] = 0.0
plot.py 文件源码 项目:circletracking 作者: caspervdw 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def norm_axesimage(ax, vmin, vmax):
    try:
        axim = ax.get_images()[0]
    except IndexError:
        return
    im = axim.get_array()
    if im.ndim == 3:  # RGB, custom norm
        if vmax - vmin > 0:
            # the masked array may give underflowerror here
            with np.errstate(under='ignore'):
                axim.set_array((im - vmin) / (vmax - vmin))
        axim.set_clim(0, 1)  # this is actually ignored for RGB by mpl
    else:  # use built-in
        axim.set_clim(vmin, vmax)
    return axim
do_adjust.py 文件源码 项目:Large-scale-bundle-adjustment-in-scipy 作者: bachmmmar 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def rotate(points, rot_vecs):
    """Rotate points by given rotation vectors.

    Rodrigues' rotation formula is used.
    """
    theta = np.linalg.norm(rot_vecs, axis=1)[:, np.newaxis]
    with np.errstate(invalid='ignore'):
        v = rot_vecs / theta
        v = np.nan_to_num(v)
    dot = np.sum(points * v, axis=1)[:, np.newaxis]
    cos_theta = np.cos(theta)
    sin_theta = np.sin(theta)

    return cos_theta * points + sin_theta * np.cross(v, points) + dot * (1 - cos_theta) * v
structure.py 文件源码 项目:atomorder 作者: larsbratholm 项目源码 文件源码 阅读 48 收藏 0 点赞 0 评论 0
def get_relative_normed_coordinates(self, molecule):
        # ignore divide by zero warning
        #with warnings.catch_warnings():
        #    warnings.filterwarnings("ignore", r'invalid value encountered in divide')
        with np.errstate(divide="ignore", invalid="ignore"):
            return (molecule.coordinates - self.coordinates[None,:]) / self.distances[:,None]
test_regression.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def test_array_str_64bit(self, level=rlevel):
        # Ticket #501
        s = np.array([1, np.nan], dtype=np.float64)
        with np.errstate(all='raise'):
            np.array_str(s)  # Should succeed
test_regression.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_sign_for_complex_nan(self, level=rlevel):
        # Ticket 794.
        with np.errstate(invalid='ignore'):
            C = np.array([-np.inf, -2+1j, 0, 2-1j, np.inf, np.nan])
            have = np.sign(C)
            want = np.array([-1+0j, -1+0j, 0+0j, 1+0j, 1+0j, np.nan])
            assert_equal(have, want)
test_regression.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_errobj_reference_leak(self, level=rlevel):
        # Ticket #955
        with np.errstate(all="ignore"):
            z = int(0)
            p = np.int32(-1)

            gc.collect()
            n_before = len(gc.get_objects())
            z**p  # this shouldn't leak a reference to errobj
            gc.collect()
            n_after = len(gc.get_objects())
            assert_(n_before >= n_after, (n_before, n_after))
test_regression.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def test_signed_integer_division_overflow(self):
        # Ticket #1317.
        def test_type(t):
            min = np.array([np.iinfo(t).min])
            min //= -1

        with np.errstate(divide="ignore"):
            for t in (np.int8, np.int16, np.int32, np.int64, np.int, np.long):
                test_type(t)
test_machar.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_underlow(self):
        # Regression test for #759:
        # instanciating MachAr for dtype = np.float96 raises spurious warning.
        with errstate(all='raise'):
            try:
                self._run_machar_highprec()
            except FloatingPointError as e:
                self.fail("Caught %s exception, should not have been raised." % e)
test_numeric.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_divide_err(self):
        with np.errstate(divide='raise'):
            try:
                np.array([1.]) / np.array([0.])
            except FloatingPointError:
                pass
            else:
                self.fail()
            np.seterr(divide='ignore')
            np.array([1.]) / np.array([0.])
test_numeric.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def test_errobj(self):
        olderrobj = np.geterrobj()
        self.called = 0
        try:
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter("always")
                with np.errstate(divide='warn'):
                    np.seterrobj([20000, 1, None])
                    np.array([1.]) / np.array([0.])
                    self.assertEqual(len(w), 1)

            def log_err(*args):
                self.called += 1
                extobj_err = args
                assert_(len(extobj_err) == 2)
                assert_("divide" in extobj_err[0])

            with np.errstate(divide='ignore'):
                np.seterrobj([20000, 3, log_err])
                np.array([1.]) / np.array([0.])
            self.assertEqual(self.called, 1)

            np.seterrobj(olderrobj)
            with np.errstate(divide='ignore'):
                np.divide(1., 0., extobj=[20000, 3, log_err])
            self.assertEqual(self.called, 2)
        finally:
            np.seterrobj(olderrobj)
            del self.called


问题


面经


文章

微信
公众号

扫码关注公众号