numpy.seterr

Here are the examples of the python api numpy.seterr taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

82 Examples 7

Page 1 Selected Page 2

Example 1

Project: python-qinfer Source File: perf_testing.py
@contextmanager
def numpy_err_policy(**kwargs):
    """
    Uses :ref:`np.seterr` to set an error policy for NumPy functions
    called during the context manager block. For example::

    >>> with numpy_err_policy(divide='raise'):
    ...     # NumPy divsion errors here are exceptions.
    >>> # NumPy division errors here follow the previous policy.
    """

    old_errs = np.seterr(**kwargs)
    yield
    np.seterr(**old_errs)

Example 2

Project: GPy Source File: decorators.py
def silence_errors(f):
    """
    This wraps a function and it silences numpy errors that
    happen during the execution. After the function has exited, it restores
    the previous state of the warnings.
    """
    @wraps(f)
    def wrapper(*args, **kwds):
        status = np.seterr(all='ignore')
        result = f(*args, **kwds)
        np.seterr(**status)
        return result
    return wrapper

Example 3

Project: scipy Source File: test_orthogonal_eval.py
Function: test_warnings
def test_warnings():
    # ticket 1334
    olderr = np.seterr(all='raise')
    try:
        # these should raise no fp warnings
        orth.eval_legendre(1, 0)
        orth.eval_laguerre(1, 1)
        orth.eval_gegenbauer(1, 1, 0)
    finally:
        np.seterr(**olderr)

Example 4

Project: pyhsmm Source File: transitions.py
Function: max_likelihood
    def max_likelihood(self,stateseqs=None,expected_transcounts=None):
        trans_counts = sum(expected_transcounts) if stateseqs is None \
                else self._count_transitions(stateseqs)
        # NOTE: we could just call max_likelihood on each trans row, but this
        # way it's a bit nicer
        errs = np.seterr(invalid='ignore',divide='ignore')
        trans_matrix = np.nan_to_num(trans_counts / trans_counts.sum(1)[:,na])
        np.seterr(**errs)

        # all-zero rows get set to uniform
        trans_matrix[trans_matrix.sum(1) == 0] = 1./(trans_matrix.shape[0]-1)
        trans_matrix.flat[::trans_matrix.shape[0]+1] = 0.

        self.trans_matrix = trans_matrix
        assert np.allclose(0.,np.diag(self.trans_matrix))
        assert np.allclose(1.,self.trans_matrix.sum(1))

        return self

Example 5

Project: roboto Source File: convertCurves.py
def calcIntersect(a,b,c,d):
    numpy.seterr(all='raise')
    e = b-a
    f = d-c
    p = array([-e[1], e[0]])
    try:
        h = dot((a-c),p) / dot(f,p)
    except:
        print a,b,c,d
        raise
    return c + dot(f,h)

Example 6

Project: numexpr Source File: test_numexpr.py
def test():
    """
    Run all the tests in the test suite.
    """

    print_versions()
    # For some reason, NumPy issues all kinds of warnings when using Python3.
    # Ignoring them in tests should be ok, as all results are checked out.
    # See https://github.com/pydata/numexpr/issues/183 for details.
    np.seterr(divide='ignore', invalid='ignore', over='ignore', under='ignore')
    return unittest.TextTestRunner().run(suite())

Example 7

Project: pyhsmm Source File: hmm_states.py
Function: messages_forwards_log
    @staticmethod
    def _messages_forwards_log(trans_matrix,init_state_distn,log_likelihoods):
        errs = np.seterr(over='ignore')
        Al = np.log(trans_matrix)
        aBl = log_likelihoods

        alphal = np.zeros_like(aBl)

        alphal[0] = np.log(init_state_distn) + aBl[0]
        for t in range(alphal.shape[0]-1):
            alphal[t+1] = logsumexp(alphal[t] + Al.T,axis=1) + aBl[t+1]

        np.seterr(**errs)
        return alphal

Example 8

Project: scipy Source File: test_minpack.py
    def test_array_basic1(self):
        # f(x) = c * x**2; fixed point should be x=1/c
        def func(x, c):
            return c * x**2
        c = array([0.75, 1.0, 1.25])
        x0 = [1.1, 1.15, 0.9]
        olderr = np.seterr(all='ignore')
        try:
            x = fixed_point(func, x0, args=(c,))
        finally:
            np.seterr(**olderr)
        assert_almost_equal(x, 1.0/c)

Example 9

Project: scipy Source File: test_measurements.py
def test_variance06():
    labels = [2, 2, 3, 3, 4]
    olderr = np.seterr(all='ignore')
    try:
        for type in types:
            input = np.array([1, 3, 8, 10, 8], type)
            output = ndimage.variance(input, labels, [2, 3, 4])
            assert_array_almost_equal(output, [1.0, 1.0, 0.0])
    finally:
        np.seterr(**olderr)

Example 10

Project: AWS-Lambda-ML-Microservice-Skeleton Source File: test_classification.py
def test_zero_precision_recall():
    # Check that pathological cases do not bring NaNs

    old_error_settings = np.seterr(all='raise')

    try:
        y_true = np.array([0, 1, 2, 0, 1, 2])
        y_pred = np.array([2, 0, 1, 1, 2, 0])

        assert_almost_equal(precision_score(y_true, y_pred,
                                            average='weighted'), 0.0, 2)
        assert_almost_equal(recall_score(y_true, y_pred, average='weighted'),
                            0.0, 2)
        assert_almost_equal(f1_score(y_true, y_pred, average='weighted'),
                            0.0, 2)

    finally:
        np.seterr(**old_error_settings)

Example 11

Project: tvb-framework Source File: abcadapter.py
def nan_allowed():
    """
    Annotation that configures NumPy not to throw an exception in case of floating points errors are computed.
    It should be used on Adapter methods where computation of NaN/ Inf/etc. is allowed.
    """

    def wrap(func):

        @wraps(func)
        def new_function(*args, **kw):
            old_fp_error_handling = numpy.seterr(all='ignore')
            try:
                return func(*args, **kw)
            finally:
                numpy.seterr(**old_fp_error_handling)

        return new_function
    return wrap

Example 12

Project: borg Source File: util.py
@contextlib.contextmanager
def numpy_errors(**kwargs):
    """Temporarily modify numpy error options."""

    old = numpy.seterr(**kwargs)

    try:
        yield
    except:
        raise
    finally:
        numpy.seterr(**old)

Example 13

Project: scipy Source File: test_orthogonal.py
Function: test_chebyc
    def test_chebyc(self):
        C0 = orth.chebyc(0)
        C1 = orth.chebyc(1)
        olderr = np.seterr(all='ignore')
        try:
            C2 = orth.chebyc(2)
            C3 = orth.chebyc(3)
            C4 = orth.chebyc(4)
            C5 = orth.chebyc(5)
        finally:
            np.seterr(**olderr)

        assert_array_almost_equal(C0.c,[2],13)
        assert_array_almost_equal(C1.c,[1,0],13)
        assert_array_almost_equal(C2.c,[1,0,-2],13)
        assert_array_almost_equal(C3.c,[1,0,-3,0],13)
        assert_array_almost_equal(C4.c,[1,0,-4,0,2],13)
        assert_array_almost_equal(C5.c,[1,0,-5,0,5,0],13)

Example 14

Project: Kayak Source File: nonlinearities.py
Function: compute_value
    def _compute_value(self):
        # Somewhat complicated to handle overflow.
        X            = self.X.value
        se           = np.seterr(over='ignore')
        exp_X        = np.exp(X / self.scale)
        result       = np.log(1.0 + np.exp( X/self.scale ))*self.scale
        over         = np.isinf(exp_X)
        result[over] = X[over]/self.scale
        return result

Example 15

Project: scipy Source File: test_minpack.py
    def test_array_trivial(self):
        def func(x):
            return 2.0*x
        x0 = [0.3, 0.15]
        olderr = np.seterr(all='ignore')
        try:
            x = fixed_point(func, x0)
        finally:
            np.seterr(**olderr)
        assert_almost_equal(x, [0.0, 0.0])

Example 16

Project: pybasicbayes Source File: mixture.py
Function: get_vlb
    def get_vlb(self):
        # return avg energy plus entropy, our contribution to the mean field
        # variational lower bound
        errs = np.seterr(invalid='ignore',divide='ignore')
        prod = self.r*np.log(self.r)
        prod[np.isnan(prod)] = 0. # 0 * -inf = 0.
        np.seterr(**errs)

        logpitilde = self.weights.expected_log_likelihood(np.arange(len(self.components)))

        q_entropy = -prod.sum()
        p_avgengy = (self.r*logpitilde).sum()

        return p_avgengy + q_entropy

Example 17

Project: scipy Source File: test_orthogonal_eval.py
Function: test_sh_legendre
    def test_sh_legendre(self):
        olderr = np.seterr(all='ignore')
        try:
            self.check_poly(orth.eval_sh_legendre, orth.sh_legendre,
                            param_ranges=[], x_range=[0, 1])
        finally:
            np.seterr(**olderr)

Example 18

Project: pyhsmm Source File: transitions.py
Function: max_likelihood
    def max_likelihood(self,stateseqs=None,expected_transcounts=None):
        trans_counts = sum(expected_transcounts) if stateseqs is None \
                else self._count_transitions(stateseqs)

        # NOTE: could just call max_likelihood on each trans row, but this way
        # it handles a few lazy-initialization cases (e.g. if _row_distns aren't
        # initialized)
        errs = np.seterr(invalid='ignore',divide='ignore')
        trans_matrix = np.nan_to_num(trans_counts / trans_counts.sum(1)[:,na])
        np.seterr(**errs)

        # all-zero rows get set to uniform
        trans_matrix[trans_matrix.sum(1) == 0] = 1./trans_matrix.shape[0]
        assert np.allclose(trans_matrix.sum(1),1.)

        self.trans_matrix = trans_matrix

        return self

Example 19

Project: scipy Source File: test_orthogonal_eval.py
Function: test_sh_chebyt
    def test_sh_chebyt(self):
        olderr = np.seterr(all='ignore')
        try:
            self.check_poly(orth.eval_sh_chebyt, orth.sh_chebyt,
                            param_ranges=[], x_range=[0, 1])
        finally:
            np.seterr(**olderr)

Example 20

Project: AWS-Lambda-ML-Microservice-Skeleton Source File: test__differential_evolution.py
Function: set_up
    def setUp(self):
        self.old_seterr = np.seterr(invalid='raise')
        self.limits = np.array([[0., 0.],
                                [2., 2.]])
        self.bounds = [(0., 2.), (0., 2.)]

        self.dummy_solver = DifferentialEvolutionSolver(self.quadratic,
                                                        [(0, 100)])

        #dummy_solver2 will be used to test mutation strategies
        self.dummy_solver2 = DifferentialEvolutionSolver(self.quadratic,
                                                         [(0, 1)],
                                                         popsize=7,
                                                         mutation=0.5)
        #create a population that's only 7 members long
        #[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
        population = np.atleast_2d(np.arange(0.1, 0.8, 0.1)).T
        self.dummy_solver2.population = population

Example 21

Project: scipy Source File: test_measurements.py
def test_variance01():
    olderr = np.seterr(all='ignore')
    try:
        with warnings.catch_warnings():
            # Numpy 1.9 gives warnings for mean([])
            warnings.filterwarnings('ignore', message="Mean of empty slice.")
            for type in types:
                input = np.array([], type)
                output = ndimage.variance(input)
                assert_(np.isnan(output))
    finally:
        np.seterr(**olderr)

Example 22

Project: scipy Source File: test__differential_evolution.py
Function: set_up
    def setUp(self):
        self.old_seterr = np.seterr(invalid='raise')
        self.limits = np.array([[0., 0.],
                                [2., 2.]])
        self.bounds = [(0., 2.), (0., 2.)]

        self.dummy_solver = DifferentialEvolutionSolver(self.quadratic,
                                                        [(0, 100)])

        # dummy_solver2 will be used to test mutation strategies
        self.dummy_solver2 = DifferentialEvolutionSolver(self.quadratic,
                                                         [(0, 1)],
                                                         popsize=7,
                                                         mutation=0.5)
        # create a population that's only 7 members long
        # [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
        population = np.atleast_2d(np.arange(0.1, 0.8, 0.1)).T
        self.dummy_solver2.population = population

Example 23

Project: pyhsmm Source File: transitions.py
    def _get_trans_matrix(self):
        out = self.full_trans_matrix
        out.flat[::out.shape[0]+1] = 0
        errs = np.seterr(invalid='ignore')
        out /= out.sum(1)[:,na]
        out = np.nan_to_num(out)
        np.seterr(**errs)
        return out

Example 24

Project: scipy Source File: test_optimize.py
    @suppressed_stdout
    def test_bfgs_infinite(self):
        # Test corner case where -Inf is the minimum.  See gh-2019.
        func = lambda x: -np.e**-x
        fprime = lambda x: -func(x)
        x0 = [0]
        olderr = np.seterr(over='ignore')
        try:
            if self.use_wrapper:
                opts = {'disp': self.disp}
                x = optimize.minimize(func, x0, jac=fprime, method='BFGS',
                                      args=(), options=opts)['x']
            else:
                x = optimize.fmin_bfgs(func, x0, fprime, disp=self.disp)
            assert_(not np.isfinite(func(x)))
        finally:
            np.seterr(**olderr)

Example 25

Project: mystic Source File: abstract_solver.py
    def _clipGuessWithinRangeBoundary(self, x0, at=True):
        """ensure that initial guess is set within bounds

input::
    - x0: must be a sequence of length self.nDim"""
       #if len(x0) != self.nDim: #XXX: unnecessary w/ self.trialSolution
       #    raise ValueError, "initial guess must be length %s" % self.nDim
        x0 = asarray(x0)
        bounds = (self._strictMin,self._strictMax)
        if not len(self._strictMin): return x0
        # clip x0 at bounds
        settings = numpy.seterr(all='ignore')
        x_ = x0.clip(*bounds)
        numpy.seterr(**settings)
        if at: return x_
        # clip x0 within bounds
        x_ = x_ != x0
        x0[x_] = random.uniform(self._strictMin,self._strictMax)[x_]
        return x0

Example 26

Project: mystic Source File: distance.py
def Lnorm(weights, p=1):
  "calculate L-p norm of weights"
  # weights is a numpy array
  # p is an int
  from numpy import asarray, seterr, inf
  weights = asarray(weights).flatten()
  if not p:
    w = float(len(weights[weights != 0.0])) # total number of nonzero elements
  elif p == inf:
    w = float(max(abs(weights)))
  else:
    orig = seterr(over='raise', invalid='raise')
    try:
      w = float(sum(abs(weights**p)))**(1./p)
    except FloatingPointError: # use the infinity norm
      w = float(max(abs(weights)))
    seterr(**orig)
  return w

Example 27

Project: mystic Source File: scipy_optimize.py
def _linesearch_powell(func, p, xi, tol=1e-3):
    # line-search algorithm using fminbound
    #  find the minimium of the function
    #  func(x0+ alpha*direc)
    def myfunc(alpha):
        return func(p + alpha * xi)
    settings = numpy.seterr(all='ignore')
    alpha_min, fret, iter, num = brent(myfunc, full_output=1, tol=tol)
    numpy.seterr(**settings)
    xi = alpha_min*xi
    return squeeze(fret), p+xi, xi

Example 28

Project: scipy Source File: test_measurements.py
def test_standard_deviation06():
    labels = [2, 2, 3, 3, 4]
    olderr = np.seterr(all='ignore')
    try:
        for type in types:
            input = np.array([1, 3, 8, 10, 8], type)
            output = ndimage.standard_deviation(input, labels, [2, 3, 4])
            assert_array_almost_equal(output, [1.0, 1.0, 0.0])
    finally:
        np.seterr(**olderr)

Example 29

Project: tractor Source File: engine.py
def set_fp_err():
    '''Cause all floating-point errors to raise exceptions.
    Returns the current error state so you can revert via:

        olderr = set_fp_err()
        # do stuff
        np.seterr(**olderr)
    '''
    return np.seterr(all='raise')

Example 30

Project: pyhsmm Source File: hmm_states.py
    @staticmethod
    def _maxsum_messages_backwards(trans_matrix, log_likelihoods):
        errs = np.seterr(divide='ignore')
        Al = np.log(trans_matrix)
        np.seterr(**errs)
        aBl = log_likelihoods

        scores = np.zeros_like(aBl)
        args = np.zeros(aBl.shape,dtype=np.int32)

        for t in range(scores.shape[0]-2,-1,-1):
            vals = Al + scores[t+1] + aBl[t+1]
            vals.argmax(axis=1,out=args[t+1])
            vals.max(axis=1,out=scores[t])

        return scores, args

Example 31

Project: discrete_sieve Source File: remainder.py
    def predict_one(self, y, z):
        if not hasattr(self, 'p_dict'):  # Memoize the predictions.
            self.p_dict = {}
        if (y, z) in self.p_dict:
            return self.p_dict[(y, z)]
        pzxy = self.marginal(())
        pzy = self.marginal(1)
        old_settings = np.seterr()
        np.seterr(invalid='ignore')
        px_yz = pzxy / pzy[:, np.newaxis, :]
        np.seterr(**old_settings)
        px = self.marginal((0, 2))
        xind_ml = np.argmax(px)

        yind = self.yset.index(y)
        xind = np.argmax(px_yz[z, :, yind]) if not np.any(np.isnan(px_yz[z, :, yind])) else xind_ml
        label = self.xset[xind]
        self.p_dict[(y, z)] = label
        return label

Example 32

Project: scipy Source File: test_measurements.py
def test_standard_deviation07():
    labels = [1]
    olderr = np.seterr(all='ignore')
    try:
        for type in types:
            input = np.array([-0.00619519], type)
            output = ndimage.standard_deviation(input, labels, [1])
            assert_array_almost_equal(output, [0])
    finally:
        np.seterr(**olderr)

Example 33

Project: robothon Source File: test_machar.py
Function: test_underlow
    def test_underlow(self):
        """Regression testing for #759: instanciating MachAr for dtype =
        np.float96 raises spurious warning."""
        serrstate = seterr(all='raise')
        try:
            try:
                self._run_machar_highprec()
            except FloatingPointError, e:
                self.fail("Caught %s exception, should not have been raised." % e)
        finally:
            seterr(**serrstate)

Example 34

Project: pyhsmm Source File: hmm_states.py
Function: messages_backwards_log
    @staticmethod
    def _messages_backwards_log(trans_matrix,log_likelihoods):
        errs = np.seterr(over='ignore')
        Al = np.log(trans_matrix)
        aBl = log_likelihoods

        betal = np.zeros_like(aBl)

        for t in range(betal.shape[0]-2,-1,-1):
            betal[t] = logsumexp(Al + betal[t+1] + aBl[t+1],axis=1)

        np.seterr(**errs)
        return betal

Example 35

Project: imagen Source File: patternfn.py
@contextmanager
def float_error_ignore():
    """
    Many of the functions in this module use Gaussian smoothing, which
    is based on a calculation like exp(divide(x*x,sigma)).  When sigma
    is zero the value of this expression should be zero at all points
    in the plane, because such a Gaussian is infinitely small.
    Obtaining the correct answer using finite-precision floating-point
    array computations requires allowing infinite values to be
    returned from divide(), and allowing exp() to underflow silently
    to zero when given an infinite value.  In numpy this is achieved
    by using its seterr() function to disable divide-by-zero and
    underflow warnings temporarily while these values are being
    computed.
    """
    oldsettings=np.seterr(divide='ignore',under='ignore')
    yield
    np.seterr(**oldsettings)

Example 36

Project: GPy Source File: prod.py
def numpy_invalid_op_as_exception(func):
    """
    A decorator that allows catching numpy invalid operations
    as exceptions (the default behaviour is raising warnings).
    """
    def func_wrapper(*args, **kwargs):
        np.seterr(invalid='raise')
        result = func(*args, **kwargs)
        np.seterr(invalid='warn')
        return result
    return func_wrapper

Example 37

Project: AWS-Lambda-ML-Microservice-Skeleton Source File: test_continuous_basic.py
def _silence_fp_errors(func):
    # warning: don't apply to test_ functions as is, then those will be skipped
    def wrap(*a, **kw):
        olderr = np.seterr(all='ignore')
        try:
            return func(*a, **kw)
        finally:
            np.seterr(**olderr)
    wrap.__name__ = func.__name__
    return wrap

Example 38

Project: scipy Source File: test_measurements.py
def test_standard_deviation01():
    olderr = np.seterr(all='ignore')
    try:
        with warnings.catch_warnings():
            # Numpy 1.9 gives warnings for mean([])
            warnings.filterwarnings('ignore', message="Mean of empty slice.")
            for type in types:
                input = np.array([], type)
                output = ndimage.standard_deviation(input)
                assert_(np.isnan(output))
    finally:
        np.seterr(**olderr)

Example 39

Project: scipy Source File: test_data.py
Function: test_factory
def _test_factory(test, dtype=np.double):
    """Boost test"""
    olderr = np.seterr(all='ignore')
    try:
        test.check(dtype=dtype)
    finally:
        np.seterr(**olderr)

Example 40

Project: robothon Source File: test_old_ma.py
Function: test_testarithmetic
    def test_testArithmetic (self):
        "Test of basic arithmetic."
        (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
        a2d = array([[1,2],[0,4]])
        a2dm = masked_array(a2d, [[0,0],[1,0]])
        self.failUnless(eq (a2d * a2d, a2d * a2dm))
        self.failUnless(eq (a2d + a2d, a2d + a2dm))
        self.failUnless(eq (a2d - a2d, a2d - a2dm))
        for s in [(12,), (4,3), (2,6)]:
            x = x.reshape(s)
            y = y.reshape(s)
            xm = xm.reshape(s)
            ym = ym.reshape(s)
            xf = xf.reshape(s)
            self.failUnless(eq(-x, -xm))
            self.failUnless(eq(x + y, xm + ym))
            self.failUnless(eq(x - y, xm - ym))
            self.failUnless(eq(x * y, xm * ym))
            olderr = numpy.seterr(divide='ignore', invalid='ignore')
            self.failUnless(eq(x / y, xm / ym))
            numpy.seterr(**olderr)
            self.failUnless(eq(a10 + y, a10 + ym))
            self.failUnless(eq(a10 - y, a10 - ym))
            self.failUnless(eq(a10 * y, a10 * ym))
            olderr = numpy.seterr(divide='ignore', invalid='ignore')
            self.failUnless(eq(a10 / y, a10 / ym))
            numpy.seterr(**olderr)
            self.failUnless(eq(x + a10, xm + a10))
            self.failUnless(eq(x - a10, xm - a10))
            self.failUnless(eq(x * a10, xm * a10))
            self.failUnless(eq(x / a10, xm / a10))
            self.failUnless(eq(x**2, xm**2))
            self.failUnless(eq(abs(x)**2.5, abs(xm) **2.5))
            self.failUnless(eq(x**y, xm**ym))
            self.failUnless(eq(numpy.add(x,y), add(xm, ym)))
            self.failUnless(eq(numpy.subtract(x,y), subtract(xm, ym)))
            self.failUnless(eq(numpy.multiply(x,y), multiply(xm, ym)))
            olderr = numpy.seterr(divide='ignore', invalid='ignore')
            self.failUnless(eq(numpy.divide(x,y), divide(xm, ym)))
            numpy.seterr(**olderr)

Example 41

Project: scipy Source File: test_lambertw.py
Function: test_value_s
def test_values():
    assert_(isnan(lambertw(nan)))
    assert_equal(lambertw(inf,1).real, inf)
    assert_equal(lambertw(inf,1).imag, 2*pi)
    assert_equal(lambertw(-inf,1).real, inf)
    assert_equal(lambertw(-inf,1).imag, 3*pi)

    assert_equal(lambertw(1.), lambertw(1., 0))

    data = [
        (0,0, 0),
        (0+0j,0, 0),
        (inf,0, inf),
        (0,-1, -inf),
        (0,1, -inf),
        (0,3, -inf),
        (e,0, 1),
        (1,0, 0.567143290409783873),
        (-pi/2,0, 1j*pi/2),
        (-log(2)/2,0, -log(2)),
        (0.25,0, 0.203888354702240164),
        (-0.25,0, -0.357402956181388903),
        (-1./10000,0, -0.000100010001500266719),
        (-0.25,-1, -2.15329236411034965),
        (0.25,-1, -3.00899800997004620-4.07652978899159763j),
        (-0.25,-1, -2.15329236411034965),
        (0.25,1, -3.00899800997004620+4.07652978899159763j),
        (-0.25,1, -3.48973228422959210+7.41405453009603664j),
        (-4,0, 0.67881197132094523+1.91195078174339937j),
        (-4,1, -0.66743107129800988+7.76827456802783084j),
        (-4,-1, 0.67881197132094523-1.91195078174339937j),
        (1000,0, 5.24960285240159623),
        (1000,1, 4.91492239981054535+5.44652615979447070j),
        (1000,-1, 4.91492239981054535-5.44652615979447070j),
        (1000,5, 3.5010625305312892+29.9614548941181328j),
        (3+4j,0, 1.281561806123775878+0.533095222020971071j),
        (-0.4+0.4j,0, -0.10396515323290657+0.61899273315171632j),
        (3+4j,1, -0.11691092896595324+5.61888039871282334j),
        (3+4j,-1, 0.25856740686699742-3.85211668616143559j),
        (-0.5,-1, -0.794023632344689368-0.770111750510379110j),
        (-1./10000,1, -11.82350837248724344+6.80546081842002101j),
        (-1./10000,-1, -11.6671145325663544),
        (-1./10000,-2, -11.82350837248724344-6.80546081842002101j),
        (-1./100000,4, -14.9186890769540539+26.1856750178782046j),
        (-1./100000,5, -15.0931437726379218666+32.5525721210262290086j),
        ((2+1j)/10,0, 0.173704503762911669+0.071781336752835511j),
        ((2+1j)/10,1, -3.21746028349820063+4.56175438896292539j),
        ((2+1j)/10,-1, -3.03781405002993088-3.53946629633505737j),
        ((2+1j)/10,4, -4.6878509692773249+23.8313630697683291j),
        (-(2+1j)/10,0, -0.226933772515757933-0.164986470020154580j),
        (-(2+1j)/10,1, -2.43569517046110001+0.76974067544756289j),
        (-(2+1j)/10,-1, -3.54858738151989450-6.91627921869943589j),
        (-(2+1j)/10,4, -4.5500846928118151+20.6672982215434637j),
        (pi,0, 1.073658194796149172092178407024821347547745350410314531),

        # Former bug in generated branch,
        (-0.5+0.002j,0, -0.78917138132659918344 + 0.76743539379990327749j),
        (-0.5-0.002j,0, -0.78917138132659918344 - 0.76743539379990327749j),
        (-0.448+0.4j,0, -0.11855133765652382241 + 0.66570534313583423116j),
        (-0.448-0.4j,0, -0.11855133765652382241 - 0.66570534313583423116j),
    ]
    data = array(data, dtype=complex_)

    def w(x, y):
        return lambertw(x, y.real.astype(int))
    olderr = np.seterr(all='ignore')
    try:
        FuncData(w, data, (0,1), 2, rtol=1e-10, atol=1e-13).check()
    finally:
        np.seterr(**olderr)

Example 42

Project: discomll Source File: naivebayes.py
def predict(dataset, fitmodel_url, m=1, save_results=True, show=False):
    """
    Function starts a job that makes predictions to input data with a given model

    Parameters
    ----------
    input - dataset object with input urls and other parameters
    fitmodel_url - model created in fit phase
    m - m estimate is used with discrete features
    save_results - save results to ddfs
    show - show info about job execution

    Returns
    -------
    Urls of predictions on ddfs
    """
    from disco.worker.pipeline.worker import Worker, Stage
    from disco.core import Job, result_iterator
    import numpy as np

    try:
        m = float(m)
    except ValueError:
        raise Exception("Parameter m should be numerical.")

    if "naivebayes_fitmodel" in fitmodel_url:
        # fit model is loaded from ddfs
        fit_model = dict((k, v) for k, v in result_iterator(fitmodel_url["naivebayes_fitmodel"]))
        if len(fit_model["y_labels"]) < 2:
            print "There is only one class in training data."
            return []
    else:
        raise Exception("Incorrect fit model.")

    if dataset.params["X_meta"].count("d") > 0:  # if there are discrete features in the model
        # code calculates logarithms to optimize predict phase as opposed to calculation by every mapped.
        np.seterr(divide='ignore')
        for iv in fit_model["iv"]:
            dist = [fit_model.pop((y,) + iv, 0) for y in fit_model["y_labels"]]
            fit_model[iv] = np.nan_to_num(
                np.log(np.true_divide(np.array(dist) + m * fit_model["prior"], np.sum(dist) + m))) - fit_model[
                                "prior_log"]
        del (fit_model["iv"])

    # define a job and set save of results to ddfs
    job = Job(worker=Worker(save_results=save_results))

    # job parallelizes execution of mappers
    job.pipeline = [
        ("split", Stage("map", input_chain=dataset.params["input_chain"], init=simple_init, process=map_predict))]

    job.params = dataset.params  # job parameters (dataset object)
    job.params["fit_model"] = fit_model
    # define name of a job and input data urls
    job.run(name="naivebayes_predict", input=dataset.params["data_tag"])
    results = job.wait(show=show)
    return results

Example 43

Project: scipy Source File: test_orthogonal.py
Function: test_call
    def test_call(self):
        poly = []
        for n in xrange(5):
            poly.extend([x.strip() for x in
                ("""
                orth.jacobi(%(n)d,0.3,0.9)
                orth.sh_jacobi(%(n)d,0.3,0.9)
                orth.genlaguerre(%(n)d,0.3)
                orth.laguerre(%(n)d)
                orth.hermite(%(n)d)
                orth.hermitenorm(%(n)d)
                orth.gegenbauer(%(n)d,0.3)
                orth.chebyt(%(n)d)
                orth.chebyu(%(n)d)
                orth.chebyc(%(n)d)
                orth.chebys(%(n)d)
                orth.sh_chebyt(%(n)d)
                orth.sh_chebyu(%(n)d)
                orth.legendre(%(n)d)
                orth.sh_legendre(%(n)d)
                """ % dict(n=n)).split()
            ])
        olderr = np.seterr(all='ignore')
        try:
            for pstr in poly:
                p = eval(pstr)
                assert_almost_equal(p(0.315), np.poly1d(p)(0.315), err_msg=pstr)
        finally:
            np.seterr(**olderr)

Example 44

Project: PyParticles Source File: main.py
Function: main
def main():
    
    #my_test()
    
    np.seterr(all='ignore')

    options = arg.parse_args()
    
    cfg = pc.ParticlesConfig()
    
    if options.version :
        print( py_particle_version() )
        return
    
    if options.about :
        about()
        return
    
    if options.test :
        print("")
        print("Start a test simulation:")
        print(" It compares the simulated solution with the analytical solution in a specific problem")
        tst.test( options.test )
        return
    
    if options.config_model :
        file_name = "example_pyparticles_config.cfg"
        cfg.write_example_config_file("example_pyparticles_config.cfg")
        print( "A file named: %s has been written in the current directory" % file_name )
        print( "" )
        return     
    
    if options.demo == "fountain" :
        print("")
        print("Start the simulation example:")
        print(" 250K Particles fountain")
        fou.fountain()
        return    
    
    if options.demo == "springs" :
        print("")
        print("Start the simulation example:")
        print(" 3 body springs")
        spr.springs()
        return
    
    if options.demo == "cat_spri" :
        print("")
        print("Start the simulation example:")
        print(" catenary springs (constraints demo)")
        spc.spring_constr()
        return
    
    if options.demo == "gas_lj" :
        print("")
        print("Start the simulation example:")
        print(" Pseudo gas with Lennard Jones potential")
        lj.gas_lj()
        return    
    
    if options.demo == "bubble" :
        print("")
        print("Start the simulation example:")
        print(" Pseudo bubble demo")
        bu.bubble()
        return
    
    if options.demo == "el_static" :
        print("")
        print("Start the simulation example:")
        print(" electrostatic")
        eld.electro()
        return  
    
    if options.demo == "elmag_field" :
        print("")
        print("Start the simulation example:")
        print(" electromagnetic fields")
        emd.electromag_field()
        return      
    
    if options.demo == "galaxy" :
        print("")
        print("Start the simulation example:")
        print(" Gravitational clusters")
        grav.gravity_cluster()
        return       
    
    if options.path_name == None or options.demo == "solar_system":
        
        print("")
        print("Start the simulation example:")
        print(" Solar system")
        print(" -- Try to watch the Moon ... around the Earth ")
        print("")
        print(" Use your mouse for rotating, zooming and tranlating the scene.")
        print("")
        print("For more details type:")
        print(" pyparticles --help")
        print("")
            
        sol.solar_system()
        return 
    
    
    
    if options.path_name != None :
        
        cfg.read_config( options.path_name )
        ( an , pset , force , ode_solver ) = cfg.build_problem()
        
        an.build_animation()
        
        print("")
        print("Start the simulation described in: %s ... " % options.path_name )
        
        an.start()
        return 
    
    print("Ops ... ")
    return 

Example 45

Project: bayespy Source File: test_random.py
Function: test
    def test(self):
        """
        Test the results of alpha-beta recursion for Markov chains
        """

        np.seterr(divide='ignore')

        # Deterministic oscillator
        p0 = np.array([1.0, 0.0])
        P = np.array(3*[[[0.0, 1.0],
                         [1.0, 0.0]]])
        (z0, zz, g) = random.alpha_beta_recursion(np.log(p0),
                                                  np.log(P))
        self.assertAllClose(z0,
                            [1.0, 0])
        self.assertAllClose(zz,
                            [ [[0.0, 1.0],
                               [0.0, 0.0]],
                              [[0.0, 0.0],
                               [1.0, 0.0]],
                              [[0.0, 1.0],
                               [0.0, 0.0]] ])
        self.assertAllClose(g,
                            -np.log(np.einsum('a,ab,bc,cd->',
                                              p0, P[0], P[1], P[2])),
                            msg="Cumulant generating function incorrect")

        # Maximum randomness
        p0 = np.array([0.5, 0.5])
        P = np.array(3*[[[0.5, 0.5],
                         [0.5, 0.5]]])
        (z0, zz, g) = random.alpha_beta_recursion(np.log(p0),
                                                  np.log(P))
        self.assertAllClose(z0,
                            [0.5, 0.5])
        self.assertAllClose(zz,
                            [ [[0.25, 0.25],
                               [0.25, 0.25]],
                              [[0.25, 0.25],
                               [0.25, 0.25]],
                              [[0.25, 0.25],
                               [0.25, 0.25]] ])
        self.assertAllClose(g,
                            -np.log(np.einsum('a,ab,bc,cd->',
                                              p0, P[0], P[1], P[2])),
                            msg="Cumulant generating function incorrect")

        # Unnormalized probabilities
        p0 = np.array([2, 2])
        P = np.array([ [[4, 4],
                        [4, 4]],
                       [[8, 8],
                        [8, 8]],
                       [[20, 20],
                        [20, 20]] ])
        (z0, zz, g) = random.alpha_beta_recursion(np.log(p0),
                                                  np.log(P))
        self.assertAllClose(z0,
                            [0.5, 0.5])
        self.assertAllClose(zz,
                            [ [[0.25, 0.25],
                               [0.25, 0.25]],
                              [[0.25, 0.25],
                               [0.25, 0.25]],
                              [[0.25, 0.25],
                               [0.25, 0.25]] ])
        self.assertAllClose(g,
                            -np.log(np.einsum('a,ab,bc,cd->',
                                              p0, P[0], P[1], P[2])),
                            msg="Cumulant generating function incorrect")
        p0 = np.array([2, 6])
        P = np.array([ [[0, 3],
                        [4, 1]],
                       [[3, 5],
                        [6, 4]],
                       [[9, 2],
                        [8, 1]] ])
        (z0, zz, g) = random.alpha_beta_recursion(np.log(p0),
                                                  np.log(P))
        y0 = np.einsum('a,ab,bc,cd->a', p0, P[0], P[1], P[2])
        y1 = np.einsum('a,ab,bc,cd->ab', p0, P[0], P[1], P[2])
        y2 = np.einsum('a,ab,bc,cd->bc', p0, P[0], P[1], P[2])
        y3 = np.einsum('a,ab,bc,cd->cd', p0, P[0], P[1], P[2])
        self.assertAllClose(z0,
                            y0 / np.sum(y0))
        self.assertAllClose(zz,
                            [ y1 / np.sum(y1),
                              y2 / np.sum(y2),
                              y3 / np.sum(y3) ])
        self.assertAllClose(g,
                            -np.log(np.einsum('a,ab,bc,cd->',
                                              p0, P[0], P[1], P[2])),
                            msg="Cumulant generating function incorrect")

        # Test plates
        p0 = np.array([ [1.0, 0.0],
                        [0.5, 0.5] ])
        P = np.array([ [ [[0.0, 1.0],
                          [1.0, 0.0]] ],
                       [ [[0.5, 0.5],
                          [0.5, 0.5]] ] ])
        (z0, zz, g) = random.alpha_beta_recursion(np.log(p0),
                                                  np.log(P))
        self.assertAllClose(z0,
                            [[1.0, 0.0],
                             [0.5, 0.5]])
        self.assertAllClose(zz,
                            [ [ [[0.0, 1.0],
                                 [0.0, 0.0]] ],
                              [ [[0.25, 0.25],
                                 [0.25, 0.25]] ] ])
        self.assertAllClose(g,
                            -np.log(np.einsum('...a,...ab->...',
                                              p0, P[...,0,:,:])),
                            msg="Cumulant generating function incorrect")

        # Test overflow
        logp0 = np.array([1e5, -np.inf])
        logP = np.array([[[-np.inf, 1e5],
                          [-np.inf, 1e5]]])
        (z0, zz, g) = random.alpha_beta_recursion(logp0,
                                                  logP)
        self.assertAllClose(z0,
                            [1.0, 0])
        self.assertAllClose(zz,
                            [ [[0.0, 1.0],
                               [0.0, 0.0]] ])
        ## self.assertAllClose(g,
        ##                     -np.log(np.einsum('a,ab,bc,cd->',
        ##                                       p0, P[0], P[1], P[2])))

        # Test underflow
        logp0 = np.array([-1e5, -np.inf])
        logP = np.array([[[-np.inf, -1e5],
                          [-np.inf, -1e5]]])
        (z0, zz, g) = random.alpha_beta_recursion(logp0,
                                                  logP)
        self.assertAllClose(z0,
                            [1.0, 0])
        self.assertAllClose(zz,
                            [ [[0.0, 1.0],
                               [0.0, 0.0]] ])
        ## self.assertAllClose(g,
        ##                     -np.log(np.einsum('a,ab,bc,cd->',
        ##                                       p0, P[0], P[1], P[2])))

        # Test stability of the algorithm
        logp0 = np.array([-1e5, -np.inf])
        logP = np.array(10*[[[-np.inf, 1e5],
                             [1e0, -np.inf]]])
        (z0, zz, g) = random.alpha_beta_recursion(logp0,
                                                  logP)
        self.assertTrue(np.all(~np.isnan(z0)),
                        msg="Nans in results, algorithm not stable")
        self.assertTrue(np.all(~np.isnan(zz)),
                        msg="Nans in results, algorithm not stable")
        self.assertTrue(np.all(~np.isnan(g)),
                        msg="Nans in results, algorithm not stable")

        pass

Example 46

Project: tvb-framework Source File: abcadapter.py
def nan_not_allowed():
    """
    Annotation that guides NumPy behavior in case of floating point errors.
    The NumPy default is to just print a warning to sys.stdout, this annotation will raise our custom exception.
    This annotation will enforce that an exception is thrown in case a floating point error is produced.

    e.g. If NaN is take as input and not produced inside the context covered by this annotation,
         nothing happens from this method p.o.v.

    e.g. If inside a method annotated with this method we have something like numpy.log(-1),
         then LaunchException is thrown.
    """

    def wrap(func):

        @wraps(func)
        def new_function(*args, **kw):
            old_fp_error_handling = numpy.seterr(divide='raise', invalid='raise')
            try:
                return func(*args, **kw)
            except FloatingPointError:
                raise LaunchException('NaN values were generated during launch. Stopping operation execution.')
            finally:
                numpy.seterr(**old_fp_error_handling)

        return new_function
    return wrap

Example 47

Project: chainer Source File: helper.py
Function: exit
    def __exit__(self, *_):
        numpy.seterr(**self.err)

Example 48

Project: scipy Source File: test__differential_evolution.py
Function: tear_down
    def tearDown(self):
        np.seterr(**self.old_seterr)

Example 49

Project: mystic Source File: constraints.py
Function: solve
def solve(constraints, guess=None, nvars=None, solver=None, \
          lower_bounds=None, upper_bounds=None, termination=None):
    """Use optimization to find a solution to a set of constraints.

Inputs:
    constraints -- a constraints solver function or a penalty function

Additional Inputs:
    guess -- list of parameter values proposed to solve the constraints.
    lower_bounds -- list of lower bounds on solution values.
    upper_bounds -- list of upper bounds on solution values.
    nvars -- number of parameter values.
    solver -- the mystic solver to use in the optimization
    termination -- the mystic termination to use in the optimization

NOTE: The resulting constraints will likely be more expensive to evaluate
    and less accurate than writing the constraints solver from scratch.

NOTE: The ensemble solvers are available, using the default NestedSolver,
    where the keyword 'guess' can be used to set the number of solvers.

NOTE: The default solver is 'diffev', with npop=min(40, ndim*5). The default
    termination is ChangeOverGeneration(), and the default guess is randomly
    selected points between the upper and lower bounds.
    """
    npts = 8
    if type(guess) is int: npts, guess = guess, None

    ndim = 1 #XXX: better, increase in while loop catching IndexError ?
    if nvars is not None: ndim = nvars
    elif guess is not None: ndim = len(guess)
    elif lower_bounds is not None: ndim = len(lower_bounds)
    elif upper_bounds is not None: ndim = len(upper_bounds)

    def cost(x): return 1.

    #XXX: don't allow solver string as a short-cut? #FIXME: add ensemble solvers
    ensemble = False
    if solver is None or solver == 'diffev':
        from mystic.solvers import DifferentialEvolutionSolver as TheSolver
        solver = TheSolver(ndim, min(40, ndim*5))
    elif solver == 'diffev2':
        from mystic.solvers import DifferentialEvolutionSolver2 as TheSolver
        solver = TheSolver(ndim, min(40, ndim*5))
    elif solver == 'fmin_powell': #XXX: better as the default? (it's not random)
        from mystic.solvers import PowellDirectionalSolver as TheSolver
        solver = TheSolver(ndim)
    elif solver == 'fmin':
        from mystic.solvers import NelderMeadSimplexSolver as TheSolver
        solver = TheSolver(ndim)
    elif solver == 'buckshot':
        from mystic.solvers import BuckshotSolver as TheSolver
        solver = TheSolver(ndim, max(8, npts)) #XXX: needs better default?
        ensemble = True
    elif solver == 'lattice':
        from mystic.solvers import LatticeSolver as TheSolver
        solver = TheSolver(ndim, max(8, npts)) #XXX: needs better default?
        ensemble = True
    
    if termination is None:
        from mystic.termination import ChangeOverGeneration as COG
        termination = COG()
    if not ensemble:
        if guess is not None:
            solver.SetInitialPoints(guess) #XXX: nice if 'diffev' had methods
        else:
            solver.SetRandomInitialPoints(lower_bounds, upper_bounds)
    if lower_bounds or upper_bounds:
        solver.SetStrictRanges(lower_bounds, upper_bounds)
    if hasattr(constraints, 'iter') and hasattr(constraints, 'error'):
        solver.SetPenalty(constraints) #i.e. is a penalty function
    else: # is a constraints solver
        solver.SetConstraints(constraints)
    from numpy import seterr
    settings = seterr(all='ignore')
    solver.Solve(cost, termination)
    seterr(**settings)
    soln = solver.bestSolution

    from numpy import ndarray, array
    if isinstance(soln, ndarray) and not isinstance(guess, ndarray):
        soln = soln.tolist()
    elif isinstance(guess, ndarray) and not isinstance(soln, ndarray):
        soln = array(soln)  #XXX: or always return a list ?

    return soln #XXX: check with 'issolution' ?

Example 50

Project: mystic Source File: tools.py
def wrap_bounds(target_function, min=None, max=None):
    "impose bounds on a function object"
    from numpy import asarray, any, inf, seterr
    bounds = True
    if min is not None and max is not None: #has upper & lower bound
        min = asarray(min)
        max = asarray(max)
    elif min is not None: #has lower bound
        min = asarray(min)
        max = asarray([inf for i in min])
    elif max is not None: #has upper bound
        max = asarray(max)
        min = asarray([-inf for i in max])
    else: #not bounded
        bounds = False
    if bounds:
        def function_wrapper(x):
            settings = seterr(all='ignore') #XXX: slow to suppress warnings?
            if any((x<min)|(x>max)): #if violate bounds, evaluate as inf
                seterr(**settings)
                return inf
            seterr(**settings)
            return target_function(x)
    else:
        def function_wrapper(x):
            return target_function(x)
    return function_wrapper
See More Examples - Go to Next Page
Page 1 Selected Page 2