Python numpy.seterr() Examples

The following are 30 code examples for showing how to use numpy.seterr(). 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: recruit   Author: Frank-qlu   File: test_core.py    License: Apache License 2.0 6 votes vote down vote up
def setup(self):
        # Base data definition.
        x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
        y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
        a10 = 10.
        m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
        m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
        xm = masked_array(x, mask=m1)
        ym = masked_array(y, mask=m2)
        z = np.array([-.5, 0., .5, .8])
        zm = masked_array(z, mask=[0, 1, 0, 0])
        xf = np.where(m1, 1e+20, x)
        xm.set_fill_value(1e+20)
        self.d = (x, y, a10, m1, m2, xm, ym, z, zm, xf)
        self.err_status = np.geterr()
        np.seterr(divide='ignore', invalid='ignore') 
Example 2
Project: lambda-packs   Author: ryfeus   File: _distn_infrastructure.py    License: MIT License 6 votes vote down vote up
def _entropy(self, *args):
        def integ(x):
            val = self._pdf(x, *args)
            return entr(val)

        # upper limit is often inf, so suppress warnings when integrating
        olderr = np.seterr(over='ignore')
        h = integrate.quad(integ, self.a, self.b)[0]
        np.seterr(**olderr)

        if not np.isnan(h):
            return h
        else:
            # try with different limits if integration problems
            low, upp = self.ppf([1e-10, 1. - 1e-10], *args)
            if np.isinf(self.b):
                upper = upp
            else:
                upper = self.b
            if np.isinf(self.a):
                lower = low
            else:
                lower = self.a
            return integrate.quad(integ, lower, upper)[0] 
Example 3
Project: lambda-packs   Author: ryfeus   File: test_core.py    License: MIT License 6 votes vote down vote up
def setUp(self):
        # Base data definition.
        x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
        y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
        a10 = 10.
        m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
        m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
        xm = masked_array(x, mask=m1)
        ym = masked_array(y, mask=m2)
        z = np.array([-.5, 0., .5, .8])
        zm = masked_array(z, mask=[0, 1, 0, 0])
        xf = np.where(m1, 1e+20, x)
        xm.set_fill_value(1e+20)
        self.d = (x, y, a10, m1, m2, xm, ym, z, zm, xf)
        self.err_status = np.geterr()
        np.seterr(divide='ignore', invalid='ignore') 
Example 4
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_core.py    License: MIT License 6 votes vote down vote up
def setUp(self):
        # Base data definition.
        x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
        y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
        a10 = 10.
        m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
        m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
        xm = masked_array(x, mask=m1)
        ym = masked_array(y, mask=m2)
        z = np.array([-.5, 0., .5, .8])
        zm = masked_array(z, mask=[0, 1, 0, 0])
        xf = np.where(m1, 1e+20, x)
        xm.set_fill_value(1e+20)
        self.d = (x, y, a10, m1, m2, xm, ym, z, zm, xf)
        self.err_status = np.geterr()
        np.seterr(divide='ignore', invalid='ignore') 
Example 5
Project: vnpy_crypto   Author: birforce   File: test_core.py    License: MIT License 6 votes vote down vote up
def setup(self):
        # Base data definition.
        x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
        y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
        a10 = 10.
        m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
        m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
        xm = masked_array(x, mask=m1)
        ym = masked_array(y, mask=m2)
        z = np.array([-.5, 0., .5, .8])
        zm = masked_array(z, mask=[0, 1, 0, 0])
        xf = np.where(m1, 1e+20, x)
        xm.set_fill_value(1e+20)
        self.d = (x, y, a10, m1, m2, xm, ym, z, zm, xf)
        self.err_status = np.geterr()
        np.seterr(divide='ignore', invalid='ignore') 
Example 6
Project: few   Author: lacava   File: evaluation.py    License: GNU General Public License v3.0 6 votes vote down vote up
def evaluate(self,n, features, stack_float, stack_bool,labels=None):
        """evaluate node in program"""
        np.seterr(all='ignore')
        if len(stack_float) >= n.arity['f'] and len(stack_bool) >= n.arity['b']:
            if n.out_type == 'f':
                stack_float.append(
                    self.safe(self.eval_dict[n.name](n,features,stack_float,
                                                     stack_bool,labels)))
                if (np.isnan(stack_float[-1]).any() or
                    np.isinf(stack_float[-1]).any()):
                    print("problem operator:",n)
            else:
                stack_bool.append(self.safe(self.eval_dict[n.name](n,features,
                                                                   stack_float,
                                                                   stack_bool,
                                                                   labels)))
                if np.isnan(stack_bool[-1]).any() or np.isinf(stack_bool[-1]).any():
                    print("problem operator:",n) 
Example 7
Project: ngraph-python   Author: NervanaSystems   File: decorators.py    License: Apache License 2.0 6 votes vote down vote up
def with_error_settings(**new_settings):
    """
    TODO.

    Arguments:
      **new_settings: TODO

    Returns:
    """
    @decorator.decorator
    def dec(f, *args, **kwargs):
        old_settings = np.geterr()

        np.seterr(**new_settings)
        ret = f(*args, **kwargs)

        np.seterr(**old_settings)

        return ret

    return dec 
Example 8
Project: data-validation   Author: tensorflow   File: basic_stats_generator_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_basic_stats_generator_no_runtime_warnings_close_to_max_int(self):
    # input has batches with values that are slightly smaller than the maximum
    # integer value.
    less_than_max_int_value = np.iinfo(np.int64).max - 1
    batches = ([
        pa.RecordBatch.from_arrays([pa.array([[less_than_max_int_value]])],
                                   ['a'])
    ] * 2)
    generator = basic_stats_generator.BasicStatsGenerator()
    old_nperr = np.geterr()
    np.seterr(over='raise')
    accumulators = [
        generator.add_input(generator.create_accumulator(), batch)
        for batch in batches
    ]
    generator.merge_accumulators(accumulators)
    np.seterr(**old_nperr) 
Example 9
def test_get_metrics(cls):
        np.seterr(divide='ignore', invalid='ignore')

        bins = 1000
        diff = 0.01
        metric = MultilabelAveragePrecision(bins=bins)
        size = [1000, 100]
        pred = Tensor(np.random.uniform(0, 1, size))
        gold = Tensor(np.random.randint(0, 2, size))
        metric.__call__(pred, gold)
        fast_ap = metric.get_metric()  # calls the fast get_metric
        ap = metric.get_metric(reset=True)  # calls the accurate get_metric
        assert (abs(ap - fast_ap)) < diff

        metric.__call__(pred, gold)
        metric.__call__(pred, gold)
        metric.__call__(pred, gold)
        fast_ap = metric.get_metric()
        ap = metric.get_metric(reset=True)
        assert (abs(ap - fast_ap)) < diff 
Example 10
Project: Computable   Author: ktraunmueller   File: test_core.py    License: MIT License 6 votes vote down vote up
def setUp (self):
        "Base data definition."
        x = np.array([1., 1., 1., -2., pi / 2.0, 4., 5., -10., 10., 1., 2., 3.])
        y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
        a10 = 10.
        m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
        m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
        xm = masked_array(x, mask=m1)
        ym = masked_array(y, mask=m2)
        z = np.array([-.5, 0., .5, .8])
        zm = masked_array(z, mask=[0, 1, 0, 0])
        xf = np.where(m1, 1e+20, x)
        xm.set_fill_value(1e+20)
        self.d = (x, y, a10, m1, m2, xm, ym, z, zm, xf)
        self.err_status = np.geterr()
        np.seterr(divide='ignore', invalid='ignore') 
Example 11
Project: hadrian   Author: modelop   File: testKMeans.py    License: Apache License 2.0 5 votes vote down vote up
def testKMeans(self):
        random.seed(12345)
        numpy.seterr(divide="ignore", invalid="ignore")

        dataset = numpy.empty((100000, 3), dtype=numpy.dtype(float))
        for i, x in enumerate(TestProducerKMeans.data([1, 1, 1], [3, 2, 5], [8, 2, 7], [5, 8, 5], [1, 1, 9])):
            if i >= dataset.shape[0]:
                break
            dataset[i,:] = x

        kmeans = KMeans(5, dataset)
        kmeans.optimize(whileall(moving(), maxIterations(1000)))

        centers = kmeans.centers()
        self.assertArrayAlmostEqual(centers[0], [1.00, 1.01, 1.00], places=2)
        self.assertArrayAlmostEqual(centers[1], [1.01, 1.00, 9.01], places=2)
        self.assertArrayAlmostEqual(centers[2], [3.01, 2.01, 5.00], places=2)
        self.assertArrayAlmostEqual(centers[3], [4.99, 8.00, 4.99], places=2)
        self.assertArrayAlmostEqual(centers[4], [8.02, 2.00, 7.01], places=2)

        doc = kmeans.pfaDocument("Cluster", ["one", "two", "three", "four", "five"])
        # look(doc, maxDepth=8)

        self.assertArrayAlmostEqual(doc["cells"]["clusters"]["init"][0]["center"], [1.00, 1.01, 1.00], places=2)
        self.assertArrayAlmostEqual(doc["cells"]["clusters"]["init"][1]["center"], [1.01, 1.00, 9.01], places=2)
        self.assertArrayAlmostEqual(doc["cells"]["clusters"]["init"][2]["center"], [3.01, 2.01, 5.00], places=2)
        self.assertArrayAlmostEqual(doc["cells"]["clusters"]["init"][3]["center"], [4.99, 8.00, 4.99], places=2)
        self.assertArrayAlmostEqual(doc["cells"]["clusters"]["init"][4]["center"], [8.02, 2.00, 7.01], places=2)

        engine, = PFAEngine.fromJson(doc)

        self.assertEqual(engine.action([1.00, 1.01, 1.00]), "one")
        self.assertEqual(engine.action([1.01, 1.00, 9.01]), "two")
        self.assertEqual(engine.action([3.01, 2.01, 5.00]), "three")
        self.assertEqual(engine.action([4.99, 8.00, 4.99]), "four")
        self.assertEqual(engine.action([8.02, 2.00, 7.01]), "five") 
Example 12
Project: hadrian   Author: modelop   File: testKMeans.py    License: Apache License 2.0 5 votes vote down vote up
def testKMeansTransform(self):
        random.seed(12345)
        numpy.seterr(divide="ignore", invalid="ignore")

        dataset = numpy.empty((100000, 3), dtype=numpy.dtype(float))
        for i, (x, y, z) in enumerate(TestProducerKMeans.data([1, 1, 1], [3, 2, 5], [8, 2, 7], [5, 8, 5], [1, 1, 9])):
            if i >= dataset.shape[0]:
                break
            dataset[i,:] = [x * 10.0, y * 20.0, z * 30.0]

        trans = Transformation("x/10.0", "y/20.0", "z/30.0")
        kmeans = KMeans(5, trans.transform(dataset, ["x", "y", "z"]))
        kmeans.optimize(whileall(moving(), maxIterations(1000)))

        centers = kmeans.centers()
        self.assertArrayAlmostEqual(centers[0], [1.00, 1.01, 1.00], places=1)
        self.assertArrayAlmostEqual(centers[1], [1.01, 1.00, 9.01], places=1)
        self.assertArrayAlmostEqual(centers[2], [3.01, 2.01, 5.00], places=1)
        self.assertArrayAlmostEqual(centers[3], [4.99, 8.00, 4.99], places=1)
        self.assertArrayAlmostEqual(centers[4], [8.02, 2.00, 7.01], places=1)

        doc = kmeans.pfaDocument("Cluster",
                                 ["one", "two", "three", "four", "five"],
                                 preprocess=trans.new(AvroArray(AvroDouble()),
                                                      x="input[0]", y="input[1]", z="input[2]"))
        # look(doc, maxDepth=10)

        self.assertArrayAlmostEqual(doc["cells"]["clusters"]["init"][0]["center"], [1.00, 1.01, 1.00], places=2)
        self.assertArrayAlmostEqual(doc["cells"]["clusters"]["init"][1]["center"], [1.01, 1.00, 9.01], places=2)
        self.assertArrayAlmostEqual(doc["cells"]["clusters"]["init"][2]["center"], [3.01, 2.01, 5.00], places=2)
        self.assertArrayAlmostEqual(doc["cells"]["clusters"]["init"][3]["center"], [4.99, 8.00, 4.99], places=2)
        self.assertArrayAlmostEqual(doc["cells"]["clusters"]["init"][4]["center"], [8.02, 2.00, 7.01], places=2)

        engine, = PFAEngine.fromJson(doc)

        self.assertEqual(engine.action([1.00 * 10, 1.01 * 20, 1.00 * 30]), "one")
        self.assertEqual(engine.action([1.01 * 10, 1.00 * 20, 9.01 * 30]), "two")
        self.assertEqual(engine.action([3.01 * 10, 2.01 * 20, 5.00 * 30]), "three")
        self.assertEqual(engine.action([4.99 * 10, 8.00 * 20, 4.99 * 30]), "four")
        self.assertEqual(engine.action([8.02 * 10, 2.00 * 20, 7.01 * 30]), "five") 
Example 13
Project: hadrian   Author: modelop   File: testCart.py    License: Apache License 2.0 5 votes vote down vote up
def testCartMustBuildNumericalNumerical(self):
        random.seed(12345)
        numpy.seterr(divide="ignore", invalid="ignore")
        dataset = Dataset.fromIterable(((x, y, z) for (x, y, z, a, b, c) in TestProducerCart.data()), 100000, ("x", "y", "z"))

        tree = TreeNode.fromWholeDataset(dataset, "z")
        tree.splitMaxDepth(2)

        doc = tree.pfaDocument({"type": "record", "name": "Datum", "fields": [{"name": "x", "type": "double"}, {"name": "y", "type": "double"}]}, "TreeNode")
        # look(doc, maxDepth=8)

        self.assertEqual(doc["cells"]["tree"]["init"]["field"], "x")
        self.assertAlmostEqual(doc["cells"]["tree"]["init"]["value"], 4.00, places=2)
        self.assertEqual(doc["cells"]["tree"]["init"]["pass"]["TreeNode"]["field"], "y")
        self.assertAlmostEqual(doc["cells"]["tree"]["init"]["pass"]["TreeNode"]["value"], 6.00, places=2)
        self.assertAlmostEqual(doc["cells"]["tree"]["init"]["pass"]["TreeNode"]["pass"]["double"], 5.00, places=2)
        self.assertAlmostEqual(doc["cells"]["tree"]["init"]["pass"]["TreeNode"]["fail"]["double"], 8.02, places=2)
        self.assertEqual(doc["cells"]["tree"]["init"]["fail"]["TreeNode"]["field"], "y")
        self.assertAlmostEqual(doc["cells"]["tree"]["init"]["fail"]["TreeNode"]["value"], 2.00, places=2)
        self.assertAlmostEqual(doc["cells"]["tree"]["init"]["fail"]["TreeNode"]["pass"]["double"], 1.09, places=2)
        self.assertAlmostEqual(doc["cells"]["tree"]["init"]["fail"]["TreeNode"]["fail"]["double"], 2.00, places=2)

        engine, = PFAEngine.fromJson(doc)
        self.assertAlmostEqual(engine.action({"x": 2.0, "y": 3.0}), 5.00, places=2)
        self.assertAlmostEqual(engine.action({"x": 2.0, "y": 8.0}), 8.02, places=2)
        self.assertAlmostEqual(engine.action({"x": 7.0, "y": 1.0}), 1.09, places=2)
        self.assertAlmostEqual(engine.action({"x": 7.0, "y": 5.0}), 2.00, places=2)

        doc = tree.pfaDocument(
            {"type": "record", "name": "Datum", "fields": [{"name": "x", "type": "double"}, {"name": "y", "type": "double"}]},
            "TreeNode",
            nodeScores=True, datasetSize=True, predictandUnique=True, nTimesVariance=True, gain=True)
        # look(doc, maxDepth=8)
        engine, = PFAEngine.fromJson(doc) 
Example 14
Project: hadrian   Author: modelop   File: testCart.py    License: Apache License 2.0 5 votes vote down vote up
def testCartMustBuildNumericalCategorical(self):
        random.seed(12345)
        numpy.seterr(divide="ignore", invalid="ignore")
        dataset = Dataset.fromIterable(((x, y, c) for (x, y, z, a, b, c) in TestProducerCart.data()), 100000, ("x", "y", "c"))

        tree = TreeNode.fromWholeDataset(dataset, "c")
        tree.splitMaxDepth(2)

        doc = tree.pfaDocument({"type": "record", "name": "Datum", "fields": [{"name": "x", "type": "double"}, {"name": "y", "type": "double"}]}, "TreeNode")
        # look(doc, maxDepth=8)

        self.assertEqual(doc["cells"]["tree"]["init"]["field"], "x")
        self.assertAlmostEqual(doc["cells"]["tree"]["init"]["value"], 4.00, places=2)
        self.assertEqual(doc["cells"]["tree"]["init"]["pass"]["TreeNode"]["field"], "y")
        self.assertAlmostEqual(doc["cells"]["tree"]["init"]["pass"]["TreeNode"]["value"], 6.00, places=2)
        self.assertEqual(doc["cells"]["tree"]["init"]["pass"]["TreeNode"]["pass"]["string"], "C3")
        self.assertEqual(doc["cells"]["tree"]["init"]["pass"]["TreeNode"]["fail"]["string"], "C6")
        self.assertEqual(doc["cells"]["tree"]["init"]["fail"]["TreeNode"]["field"], "y")
        self.assertAlmostEqual(doc["cells"]["tree"]["init"]["fail"]["TreeNode"]["value"], 2.00, places=2)
        self.assertEqual(doc["cells"]["tree"]["init"]["fail"]["TreeNode"]["pass"]["string"], "C0")
        self.assertEqual(doc["cells"]["tree"]["init"]["fail"]["TreeNode"]["fail"]["string"], "C0")

        engine, = PFAEngine.fromJson(doc)
        self.assertEqual(engine.action({"x": 2.0, "y": 3.0}), "C3")
        self.assertEqual(engine.action({"x": 2.0, "y": 8.0}), "C6")
        self.assertEqual(engine.action({"x": 7.0, "y": 1.0}), "C0")
        self.assertEqual(engine.action({"x": 7.0, "y": 5.0}), "C0")

        doc = tree.pfaDocument(
            {"type": "record", "name": "Datum", "fields": [{"name": "x", "type": "double"}, {"name": "y", "type": "double"}]},
            "TreeNode",
            nodeScores=True, datasetSize=True, predictandDistribution=True, predictandUnique=True, entropy=True, gain=True)
        # look(doc, maxDepth=8)
        engine, = PFAEngine.fromJson(doc) 
Example 15
Project: hadrian   Author: modelop   File: testCart.py    License: Apache License 2.0 5 votes vote down vote up
def testCartMustBuildCategoricalNumerical(self):
        random.seed(12345)
        numpy.seterr(divide="ignore", invalid="ignore")
        dataset = Dataset.fromIterable(((a, b, z) for (x, y, z, a, b, c) in TestProducerCart.data()), 100000, ("a", "b", "z"))

        tree = TreeNode.fromWholeDataset(dataset, "z")
        tree.splitMaxDepth(2)

        doc = tree.pfaDocument({"type": "record", "name": "Datum", "fields": [{"name": "a", "type": "string"}, {"name": "b", "type": "string"}]}, "TreeNode")
        # look(doc, maxDepth=8)

        self.assertEqual(doc["cells"]["tree"]["init"]["field"], "a")
        self.assertEqual(doc["cells"]["tree"]["init"]["value"], ["A0", "A1", "A2", "A3"])
        self.assertEqual(doc["cells"]["tree"]["init"]["pass"]["TreeNode"]["field"], "b")
        self.assertEqual(doc["cells"]["tree"]["init"]["pass"]["TreeNode"]["value"], ["B6", "B8"])
        self.assertAlmostEqual(doc["cells"]["tree"]["init"]["pass"]["TreeNode"]["pass"]["double"], 8.02, places=2)
        self.assertAlmostEqual(doc["cells"]["tree"]["init"]["pass"]["TreeNode"]["fail"]["double"], 5.00, places=2)
        self.assertEqual(doc["cells"]["tree"]["init"]["fail"]["TreeNode"]["field"], "b")
        self.assertEqual(doc["cells"]["tree"]["init"]["fail"]["TreeNode"]["value"], ["B0"])
        self.assertAlmostEqual(doc["cells"]["tree"]["init"]["fail"]["TreeNode"]["pass"]["double"], 1.09, places=2)
        self.assertAlmostEqual(doc["cells"]["tree"]["init"]["fail"]["TreeNode"]["fail"]["double"], 2.00, places=2)

        engine, = PFAEngine.fromJson(doc)
        self.assertAlmostEqual(engine.action({"a": "A1", "b": "B6"}), 8.02, places=2)
        self.assertAlmostEqual(engine.action({"a": "A1", "b": "B2"}), 5.00, places=2)
        self.assertAlmostEqual(engine.action({"a": "A5", "b": "B0"}), 1.09, places=2)
        self.assertAlmostEqual(engine.action({"a": "A5", "b": "B4"}), 2.00, places=2)

        doc = tree.pfaDocument(
            {"type": "record", "name": "Datum", "fields": [{"name": "a", "type": "string"}, {"name": "b", "type": "string"}]},
            "TreeNode",
            nodeScores=True, datasetSize=True, predictandUnique=True, nTimesVariance=True, gain=True)
        # look(doc, maxDepth=8)
        engine, = PFAEngine.fromJson(doc) 
Example 16
Project: hadrian   Author: modelop   File: testClustering.py    License: Apache License 2.0 5 votes vote down vote up
def doKmeans(self):
        numpy.seterr(divide="ignore", invalid="ignore")

        # get a dataset for the k-means generator
        dataset = []
        for record in DataFileReader(open("test/prettypfa/exoplanets.avro", "r"), DatumReader()):
            mag, dist, mass, radius = record.get("mag"), record.get("dist"), record.get("mass"), record.get("radius")
            if mag is not None and dist is not None and mass is not None and radius is not None:
                dataset.append([mag, dist, mass, radius])

        # set up and run the k-means generator
        TestClustering.kmeansResult = KMeans(len(self.clusterNames), numpy.array(dataset))
        TestClustering.kmeansResult.optimize(whileall(moving(), maxIterations(1000))) 
Example 17
Project: simnibs   Author: simnibs   File: electrode_placement.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _calc_triangle_angles(p, eps=1e-5):
    p1 = p[:, 0]
    p2 = p[:, 1]
    p3 = p[:, 2]

    e1 = np.linalg.norm(p2 - p1, axis=1)
    e2 = np.linalg.norm(p3 - p1, axis=1)
    e3 = np.linalg.norm(p3 - p2, axis=1)
    # Law Of Cossines
    state = np.geterr()['invalid']
    np.seterr(invalid='ignore')
    a = np.zeros((p.shape[0], 3))
    v = (e1 > eps) * (e2 > eps)
    a[v, 0] = np.arccos((e2[v] ** 2 + e1[v] ** 2 - e3[v] ** 2) / (2 * e1[v] * e2[v]))
    a[~v, 0] = 0

    v = (e1 > eps) * (e3 > eps)
    a[v, 1] = np.arccos((e1[v] ** 2 + e3[v] ** 2 - e2[v] ** 2) / (2 * e1[v] * e3[v]))
    a[~v, 1] = 0

    v = (e2 > eps) * (e3 > eps)
    a[v, 2] = np.arccos((e2[v] ** 2 + e3[v] ** 2 - e1[v] ** 2) / (2 * e2[v] * e3[v]))
    a[~v, 2] = 0
    np.seterr(invalid=state)
    a[np.isnan(a)] = np.pi

    return a 
Example 18
Project: pyGSTi   Author: pyGSTio   File: matrixforwardsim.py    License: Apache License 2.0 5 votes vote down vote up
def _scaleExp(self, scaleExps):
        old_err = _np.seterr(over='ignore')
        scaleVals = _np.exp(scaleExps)  # may overflow, but OK if infs occur here
        _np.seterr(**old_err)
        return scaleVals 
Example 19
Project: recruit   Author: Frank-qlu   File: test_old_ma.py    License: Apache License 2.0 5 votes vote down vote up
def test_testUfuncRegression(self):
        f_invalid_ignore = [
            'sqrt', 'arctanh', 'arcsin', 'arccos',
            'arccosh', 'arctanh', 'log', 'log10', 'divide',
            'true_divide', 'floor_divide', 'remainder', 'fmod']
        for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate',
                  'sin', 'cos', 'tan',
                  'arcsin', 'arccos', 'arctan',
                  'sinh', 'cosh', 'tanh',
                  'arcsinh',
                  'arccosh',
                  'arctanh',
                  'absolute', 'fabs', 'negative',
                  'floor', 'ceil',
                  'logical_not',
                  'add', 'subtract', 'multiply',
                  'divide', 'true_divide', 'floor_divide',
                  'remainder', 'fmod', 'hypot', 'arctan2',
                  'equal', 'not_equal', 'less_equal', 'greater_equal',
                  'less', 'greater',
                  'logical_and', 'logical_or', 'logical_xor']:
            try:
                uf = getattr(umath, f)
            except AttributeError:
                uf = getattr(fromnumeric, f)
            mf = getattr(np.ma, f)
            args = self.d[:uf.nin]
            with np.errstate():
                if f in f_invalid_ignore:
                    np.seterr(invalid='ignore')
                if f in ['arctanh', 'log', 'log10']:
                    np.seterr(divide='ignore')
                ur = uf(*args)
                mr = mf(*args)
            assert_(eq(ur.filled(0), mr.filled(0), f))
            assert_(eqmask(ur.mask, mr.mask)) 
Example 20
Project: recruit   Author: Frank-qlu   File: test_core.py    License: Apache License 2.0 5 votes vote down vote up
def teardown(self):
        np.seterr(**self.err_status) 
Example 21
Project: recruit   Author: Frank-qlu   File: test_core.py    License: Apache License 2.0 5 votes vote down vote up
def setup(self):
        # Base data definition.
        self.d = (array([1.0, 0, -1, pi / 2] * 2, mask=[0, 1] + [0] * 6),
                  array([1.0, 0, -1, pi / 2] * 2, mask=[1, 0] + [0] * 6),)
        self.err_status = np.geterr()
        np.seterr(divide='ignore', invalid='ignore') 
Example 22
Project: recruit   Author: Frank-qlu   File: test_core.py    License: Apache License 2.0 5 votes vote down vote up
def teardown(self):
        np.seterr(**self.err_status) 
Example 23
Project: recruit   Author: Frank-qlu   File: numeric.py    License: Apache License 2.0 5 votes vote down vote up
def __enter__(self):
        self.oldstate = seterr(**self.kwargs)
        if self.call is not _Unspecified:
            self.oldcall = seterrcall(self.call) 
Example 24
Project: recruit   Author: Frank-qlu   File: numeric.py    License: Apache License 2.0 5 votes vote down vote up
def __exit__(self, *exc_info):
        seterr(**self.oldstate)
        if self.call is not _Unspecified:
            seterrcall(self.oldcall) 
Example 25
Project: recruit   Author: Frank-qlu   File: test_umath_complex.py    License: Apache License 2.0 5 votes vote down vote up
def setup(self):
        self.olderr = np.seterr(invalid='ignore') 
Example 26
Project: recruit   Author: Frank-qlu   File: test_umath_complex.py    License: Apache License 2.0 5 votes vote down vote up
def teardown(self):
        np.seterr(**self.olderr) 
Example 27
Project: recruit   Author: Frank-qlu   File: test_umath_complex.py    License: Apache License 2.0 5 votes vote down vote up
def teardown(self):
        np.seterr(**self.olderr) 
Example 28
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 5 votes vote down vote up
def test_set(self):
        with np.errstate():
            err = np.seterr()
            old = np.seterr(divide='print')
            assert_(err == old)
            new = np.seterr()
            assert_(new['divide'] == 'print')
            np.seterr(over='raise')
            assert_(np.geterr()['over'] == 'raise')
            assert_(new['divide'] == 'print')
            np.seterr(**old)
            assert_(np.geterr() == old) 
Example 29
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 5 votes vote down vote up
def test_divide_err(self):
        with np.errstate(divide='raise'):
            with assert_raises(FloatingPointError):
                np.array([1.]) / np.array([0.])

            np.seterr(divide='ignore')
            np.array([1.]) / np.array([0.]) 
Example 30
Project: recruit   Author: Frank-qlu   File: test_numeric.py    License: Apache License 2.0 5 votes vote down vote up
def setup(self):
        self.olderr = np.seterr(invalid='ignore')