numpy.array_equal

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

175 Examples 7

Example 1

Project: theanolm Source File: bigramoptimizer_test.py
    def assert_optimizers_equal(self, numpy_optimizer, theano_optimizer):
        self.assertTrue(numpy.array_equal(numpy_optimizer._word_counts, theano_optimizer._word_counts.get_value()))
        self.assertEqual((numpy_optimizer._ww_counts - theano_optimizer._ww_counts.get_value()).nnz, 0)
        self.assertTrue(numpy.array_equal(numpy_optimizer._class_counts, theano_optimizer._class_counts.get_value()))
        self.assertTrue(numpy.array_equal(numpy_optimizer._cc_counts, theano_optimizer._cc_counts.get_value()))
        self.assertTrue(numpy.array_equal(numpy_optimizer._cw_counts, theano_optimizer._cw_counts.get_value()))
        self.assertTrue(numpy.array_equal(numpy_optimizer._wc_counts, theano_optimizer._wc_counts.get_value()))

Example 2

Project: selective_search_py Source File: test_color_space.py
    def test_convert_color_value(self):
        assert numpy.array_equal(convert_color(self.Irand, 'rgb'), self.Irand)
        assert numpy.array_equal(convert_color(self.Irand, 'lab'), to_Lab(self.Irand))
        assert numpy.array_equal(convert_color(self.Irand, 'rgi'), to_rgI(self.Irand))
        assert numpy.array_equal(convert_color(self.Irand, 'hsv'), to_HSV(self.Irand))
        assert numpy.array_equal(convert_color(self.Irand, 'nrgb'), to_nRGB(self.Irand))
        assert numpy.array_equal(convert_color(self.Irand, 'hue'), to_Hue(self.Irand))

Example 3

Project: nolearn Source File: test_base.py
Function: test_pickle
    def test_pickle(self, net_fitted, X_test, y_pred):
        recursionlimit = sys.getrecursionlimit()
        sys.setrecursionlimit(10000)
        pickled = pickle.dumps(net_fitted, -1)
        net_loaded = pickle.loads(pickled)
        assert np.array_equal(net_loaded.predict(X_test), y_pred)
        sys.setrecursionlimit(recursionlimit)

Example 4

Project: pyphi Source File: utils.py
def independent(repertoire):
    """Check whether the repertoire is independent."""
    marginals = [marginal(repertoire, i) for i in range(repertoire.ndim)]

    # TODO: is there a way to do without an explicit iteration?
    joint = marginals[0]
    for m in marginals[1:]:
        joint = joint * m

    # TODO: should we round here?
    #repertoire = repertoire.round(config.PRECISION)
    #joint = joint.round(config.PRECISION)

    return np.array_equal(repertoire, joint)

Example 5

Project: datasketch Source File: minhash.py
Function: eq
    def __eq__(self, other):
        '''
        Check equivalence between MinHash
        '''
        return self.seed == other.seed and \
                np.array_equal(self.hashvalues, other.hashvalues)

Example 6

Project: abstract_rendering Source File: numericTests.py
Function: test
    def test(self):
        op = numeric.Sqrt()

        out = op.shade([1, 1, 1])
        self.assertTrue(np.array_equal(out, [1, 1, 1]))

        a = np.array([[4,   4,  4],
                      [9,   9,  9],
                      [25, 25, 25]])

        expected = np.array([[2, 2, 2],
                             [3, 3, 3],
                             [5, 5, 5]], dtype=float)

        out = op.shade(a)
        self.assertTrue(np.array_equal(out, expected),
                        "Unequal:\n %s \n = \n %s" % (out, expected))

Example 7

Project: Uranium Source File: Matrix.py
Function: eq
    def __eq__(self, other):
        if self is other:
            return True
        if type(other) is not Matrix:
            return False

        if self._data is None and other._data is None:
            return True
        return numpy.array_equal(self._data, other._data)

Example 8

Project: diogenes Source File: test_modify.py
    def test_col_fewer_than_n_nonzero(self):
        M = cast_list_of_list_to_sa(
            [[0,2,3], [0,3,4], [1,4,5]],
            col_names=['height','weight', 'age'])
        arguments = [{'func': col_fewer_than_n_nonzero,  'vals': 2}]  
        M = remove_cols_where(M, arguments)  
        correct = cast_list_of_list_to_sa(
            [[2,3], [3,4], [4,5]],
            col_names=['weight', 'age'])   
        self.assertTrue(np.array_equal(M, correct))    

Example 9

Project: GPy Source File: rbf_inv.py
Function: k_computations
    def _K_computations(self, X, X2):
        if not (np.array_equal(X, self._X) and np.array_equal(X2, self._X2) and np.array_equal(self._params , self._get_params())):
            self._X = X.copy()
            self._params = self._get_params().copy()
            if X2 is None:
                self._X2 = None
                X = X * self.inv_lengthscale
                Xsquare = np.sum(np.square(X), 1)
                self._K_dist2 = -2.*tdot(X) + (Xsquare[:, None] + Xsquare[None, :])
            else:
                self._X2 = X2.copy()
                X = X * self.inv_lengthscale
                X2 = X2 * self.inv_lengthscale
                self._K_dist2 = -2.*np.dot(X, X2.T) + (np.sum(np.square(X), 1)[:, None] + np.sum(np.square(X2), 1)[None, :])
            self._K_dvar = np.exp(-0.5 * self._K_dist2)

Example 10

Project: distarray Source File: test_distributed_io.py
Function: check_hdf5_file
def check_hdf5_file(output_path, expected, dataset="buffer"):
    import h5py
    import numpy

    with h5py.File(output_path, 'r') as fp:
        if dataset not in fp:
            return False
        if not numpy.array_equal(expected, fp[dataset]):
            return False

    return True

Example 11

Project: TensorVision Source File: test_utils.py
def test_overlay_segmentation():
    """Test overlay_segmentation."""
    from tensorvision.utils import overlay_segmentation
    import scipy.ndimage
    import numpy as np
    seg_image = 'tensorvision/tests/Crocodylus-johnsoni-3-seg.png'
    original_image = 'tensorvision/tests/Crocodylus-johnsoni-3.jpg'
    target_path = 'tensorvision/tests/croco-overlay-new.png'
    correct_path = 'tensorvision/tests/croco-overlay.png'
    input_image = scipy.misc.imread(original_image)
    segmentation = scipy.misc.imread(seg_image)
    color_changes = {0: (0, 255, 0, 127),
                     'default': (0, 0, 0, 0)}
    res = overlay_segmentation(input_image, segmentation, color_changes)
    scipy.misc.imsave(target_path, res)
    img1 = scipy.ndimage.imread(correct_path)
    img2 = scipy.ndimage.imread(target_path)
    assert np.array_equal(img1, img2)

Example 12

Project: scikit-bio Source File: test_base.py
Function: test_data
    def test_data(self):
        for dm, exp in zip(self.dms, self.dm_redundant_forms):
            obs = dm.data
            self.assertTrue(np.array_equal(obs, exp))

        with self.assertRaises(AttributeError):
            self.dm_3x3.data = 'foo'

Example 13

Project: pyDive Source File: test_h5_ndarray.py
Function: test_h5
def test_h5(init_pyDive):
    test_array = pyDive.h5.open(input_file, "particles/pos")

    ref_array_x = h5.File(input_file, "r")["particles/pos/x"][:]
    ref_array_y = h5.File(input_file, "r")["particles/pos/y"][:]

    assert np.array_equal(ref_array_x, test_array["x"].load().gather())
    assert np.array_equal(ref_array_y, test_array["y"].load().gather())
    assert np.array_equal(ref_array_x, test_array.load()["x"].gather())
    assert np.array_equal(ref_array_y, test_array.load()["y"].gather())

Example 14

Project: spark-tk Source File: inspect_dicom_test.py
    def test_image_content_inspect_dcm_basic(self):
        """content test of image data for dicom"""
        # load the files so we can compare with the dicom result
        files = []
        for filename in os.listdir(self.image_directory):
            pixel_data = dicom.read_file(self.image_directory + filename).pixel_array
            files.append(pixel_data)

        # iterate through the data in the files and in the dicom frame
        # and ensure that they match
        image_inspect = self.dicom.pixeldata.inspect().rows
        for dcm_image in image_inspect:
            result = any(numpy.array_equal(dcm_image[1], file_image) for file_image in files)
            self.assertTrue(result)

Example 15

Project: abstract_rendering Source File: numpyglyphTests.py
Function: run_spread
    def run_spread(self, spread, in_vals, expected, **kwargs):
        op = npg.Spread(factor=spread, **kwargs)
        out = op.shade(in_vals)

        self.assertTrue(np.array_equal(out, expected),
                        'incorrect value spreading\n %s' % str(out))

Example 16

Project: theanolm Source File: vocabulary_test.py
    def test_from_state(self):
        self.classes_file.seek(0)
        vocabulary1 = Vocabulary.from_file(self.classes_file, 'srilm-classes')
        f = h5py.File('in-memory.h5', driver='core', backing_store=False)
        vocabulary1.get_state(f)
        vocabulary2 = Vocabulary.from_state(f)
        self.assertTrue(numpy.array_equal(vocabulary1.id_to_word,
                                          vocabulary2.id_to_word))
        self.assertDictEqual(vocabulary1.word_to_id, vocabulary2.word_to_id)
        self.assertTrue(numpy.array_equal(vocabulary1.word_id_to_class_id,
                                          vocabulary2.word_id_to_class_id))
        self.assertListEqual(list(vocabulary1._word_classes),
                             list(vocabulary2._word_classes))

Example 17

Project: diogenes Source File: test_modify.py
    def test_col_val_eq(self):
        M = cast_list_of_list_to_sa(
            [[1,2,3], [1,3,4], [1,4,5]],
            col_names=['height','weight', 'age'])
        
        arguments = [{'func': col_val_eq,  'vals': 1}]  
        M = remove_cols_where(M, arguments)  
        correct = cast_list_of_list_to_sa(
            [[2,3], [3,4], [4,5]],
            col_names=['weight', 'age'])    
        self.assertTrue(np.array_equal(M, correct))

Example 18

Project: bhmm Source File: test_bhmm.py
    def test_transition_matrix_samples(self):
        Psamples = self.sampled_hmm_lag10.transition_matrix_samples
        # shape
        assert np.array_equal(Psamples.shape, (self.nsamples, self.nstates, self.nstates))
        # consistency
        import msmtools.analysis as msmana
        for P in Psamples:
            assert msmana.is_transition_matrix(P)
            assert msmana.is_reversible(P)

Example 19

Project: butterflow Source File: test_source.py
    def test_seek_forward_then_backward(self):
        self.src_3.seek_to_fr(2)
        f1 = self.src_3.read()
        f2 = avutil_fr_at_idx(self.src_3.src, self.imagefile, 2)
        self.assertTrue(np.array_equal(f1,f2))
        self.src_3.seek_to_fr(1)
        f1 = self.src_3.read()
        f2 = avutil_fr_at_idx(self.src_3.src, self.imagefile, 1)
        self.assertTrue(np.array_equal(f1,f2))
        self.src_3.seek_to_fr(0)
        f1 = self.src_3.read()
        f2 = avutil_fr_at_idx(self.src_3.src, self.imagefile, 0)
        self.assertTrue(np.array_equal(f1,f2))

Example 20

Project: attention-lvcsr Source File: test_opt.py
    def test_append_inplace(self):
        mySymbolicMatricesList = TypedListType(T.TensorType(
                                               theano.config.floatX, (False, False)))()
        mySymbolicMatrix = T.matrix()
        z = Append()(mySymbolicMatricesList, mySymbolicMatrix)
        m = theano.compile.mode.get_default_mode().including("typed_list_inplace_opt")
        f = theano.function([In(mySymbolicMatricesList, borrow=True,
                                mutable=True),
                            In(mySymbolicMatrix, borrow=True,
                               mutable=True)], z, accept_inplace=True, mode=m)
        self.assertTrue(f.maker.fgraph.toposort()[0].op.inplace)

        x = rand_ranged_matrix(-1000, 1000, [100, 101])

        y = rand_ranged_matrix(-1000, 1000, [100, 101])

        self.assertTrue(numpy.array_equal(f([x], y), [x, y]))

Example 21

Project: datasketch Source File: weighted_minhash.py
Function: jaccard
    def jaccard(self, other):
        '''
        Estimate Jaccard similarity (resemblance) using this WeightedMinHash
        and the other.
        '''
        if other.seed != self.seed:
            raise ValueError("Cannot compute Jaccard given WeightedMinHash objects with\
                    different seeds")
        if len(self) != len(other):
            raise ValueError("Cannot compute Jaccard given WeightedMinHash objects with\
                    different numbers of hash values")
        # Check how many pairs of (k, t) hashvalues are equal
        intersection = 0
        for this, that in zip(self.hashvalues, other.hashvalues):
            if np.array_equal(this, that):
                intersection += 1
        return float(intersection) / float(len(self))

Example 22

Project: pyphi Source File: test_convert.py
def test_state_by_state2state_by_node():
    result = convert.state_by_state2state_by_node(state_by_state)
    expected = convert.to_n_dimensional(state_by_node)
    print("Result:")
    print(result)
    print("Expected:")
    print(expected)
    assert np.array_equal(result, expected)

Example 23

Project: pyphi Source File: test_convert.py
def test_nondet_state_by_node2state_by_state():
    # Test for nondeterministic TPM.
    result = convert.state_by_node2state_by_state(state_by_node_nondet)
    expected = state_by_state_nondet
    print("Result:")
    print(result)
    print("Expected:")
    print(expected)
    assert np.array_equal(result, expected)

Example 24

Project: attention-lvcsr Source File: test_opt.py
    def test_extend_inplace(self):
        mySymbolicMatricesList1 = TypedListType(T.TensorType(
                                                theano.config.floatX, (False, False)))()

        mySymbolicMatricesList2 = TypedListType(T.TensorType(
                                                theano.config.floatX, (False, False)))()

        z = Extend()(mySymbolicMatricesList1, mySymbolicMatricesList2)
        m = theano.compile.mode.get_default_mode().including("typed_list_inplace_opt")
        f = theano.function([In(mySymbolicMatricesList1, borrow=True,
                             mutable=True), mySymbolicMatricesList2],
                            z, mode=m)
        self.assertTrue(f.maker.fgraph.toposort()[0].op.inplace)

        x = rand_ranged_matrix(-1000, 1000, [100, 101])

        y = rand_ranged_matrix(-1000, 1000, [100, 101])

        self.assertTrue(numpy.array_equal(f([x], [y]), [x, y]))

Example 25

Project: scikit-bio Source File: test_base.py
Function: test_copy
    def test_copy(self):
        copy = self.dm_2x2.copy()
        self.assertEqual(copy, self.dm_2x2)
        self.assertFalse(copy.data is self.dm_2x2.data)
        # deepcopy doesn't actually create a copy of the IDs because it is a
        # tuple of strings, which is fully immutable.
        self.assertTrue(copy.ids is self.dm_2x2.ids)

        new_ids = ['hello', 'world']
        copy.ids = new_ids
        self.assertNotEqual(copy.ids, self.dm_2x2.ids)

        copy = self.dm_2x2.copy()
        copy.data[0, 1] = 0.0001
        self.assertFalse(np.array_equal(copy.data, self.dm_2x2.data))

Example 26

Project: TensorVision Source File: test_utils.py
def test_soft_overlay_segmentation():
    """Test soft_overlay_segmentation."""
    from tensorvision.utils import soft_overlay_segmentation
    import scipy.ndimage
    import numpy as np
    seg_image = 'tensorvision/tests/Crocodylus-johnsoni-3-seg-prob.png'
    original_image = 'tensorvision/tests/Crocodylus-johnsoni-3.jpg'
    target_path = 'tensorvision/tests/croco-overlay-new-soft.png'
    correct_path = 'tensorvision/tests/croco-overlay-soft.png'
    input_image = scipy.misc.imread(original_image)
    segmentation = scipy.misc.imread(seg_image) / 255.0
    res = soft_overlay_segmentation(input_image, segmentation)
    scipy.misc.imsave(target_path, res)
    img1 = scipy.ndimage.imread(correct_path)
    img2 = scipy.ndimage.imread(target_path)
    assert np.array_equal(img1, img2)

Example 27

Project: orange3-text Source File: corpus.py
    def __eq__(self, other):
        def arrays_equal(a, b):
            if sp.issparse(a) != sp.issparse(b):
                return False
            elif sp.issparse(a) and sp.issparse(b):
                return (a != b).nnz == 0
            else:
                return np.array_equal(a, b)

        return (self.text_features == other.text_features and
                self._dictionary == other._dictionary and
                np.array_equal(self._tokens, other._tokens) and
                arrays_equal(self.X, other.X) and
                arrays_equal(self.Y, other.Y) and
                arrays_equal(self.metas, other.metas) and
                np.array_equal(self.pos_tags, other.pos_tags) and
                self.domain == other.domain and
                self.ngram_range == other.ngram_range)

Example 28

Project: pyDive Source File: test_h5_ndarray.py
def test_h5_ndarray1(init_pyDive):
    dataset = "particles/pos/x"

    test_array = pyDive.h5.open(input_file, dataset)

    ref_array = h5.File(input_file, "r")[dataset][:]

    assert np.array_equal(ref_array, test_array.load().gather())

Example 29

Project: spark-tk Source File: create_dicom_test.py
    def test_image_content_import_dcm_basic(self):
        """content test of image data for dicom"""
        # load the files so we can compare with the dicom result
        files = []
        for filename in os.listdir(self.image_directory):
            pixel_data = dicom.read_file(self.image_directory + filename).pixel_array
            files.append(pixel_data)

        # iterate through the data in the files and in the dicom frame
        # and ensure that they match
        image_pandas = self.dicom.pixeldata.to_pandas()["imagematrix"]
        for dcm_image in image_pandas:
            result = any(numpy.array_equal(dcm_image, file_image) for file_image in files)
            self.assertTrue(result)

Example 30

Project: abstract_rendering Source File: numericTests.py
Function: test
    def test(self):
        op = numeric.Cuberoot()

        out = op.shade([1, 1, 1])
        self.assertTrue(np.array_equal(out, [1, 1, 1]))

        a = np.array([[27],
                      [64],
                      [125]])

        # Calculates in-place because of floating point round-off
        expected = np.array([[pow(27, 1/3.0)],
                             [pow(64, 1/3.0)],
                             [pow(125, 1/3.0)]], dtype=float)

        out = op.shade(a)
        self.assertTrue(np.array_equal(out, expected),
                        "Unequal:\n %s \n = \n %s" % (out, expected))

Example 31

Project: attention-lvcsr Source File: test_type.py
    def test_filter_sanity_check(self):
        """
        Simple test on typed list type filter
        """
        myType = TypedListType(T.TensorType(theano.config.floatX,
                                            (False, False)))

        x = rand_ranged_matrix(-1000, 1000, [100, 100])

        self.assertTrue(numpy.array_equal(myType.filter([x]), [x]))

Example 32

Project: abstract_rendering Source File: numericTests.py
Function: run_spread
    def run_spread(self, spread, in_vals, expected):
        op = numeric.Spread(factor=spread)
        out = op.shade(in_vals)

        self.assertTrue(np.array_equal(out, expected),
                        'incorrect value spreading\ni %s' % str(out))

Example 33

Project: spark-tk Source File: take_dicom_test.py
    def test_image_content_take_dcm_basic(self):
        """content test of image data for dicom"""
        # load the files so we can compare with the dicom result
        files = []
        for filename in os.listdir(self.image_directory):
            pixel_data = dicom.read_file(self.image_directory + filename).pixel_array
            files.append(pixel_data)

        # iterate through the data in the files and in the dicom frame
        # and ensure that they match
        image_inspect = self.dicom.pixeldata.take(self.count)
        for dcm_image in image_inspect:
            result = any(numpy.array_equal(dcm_image[1], file_image) for file_image in files)
            self.assertTrue(result)

Example 34

Project: deepchem Source File: test_datasets.py
  def test_consistent_ordering(self):
    """Test that ordering of labels is consistent over time."""
    solubility_dataset = dc.data.tests.load_solubility_data()

    ids1 = solubility_dataset.ids
    ids2 = solubility_dataset.ids

    assert np.array_equal(ids1, ids2)

Example 35

Project: gensim Source File: test_sharded_corpus.py
    def test_getitem(self):

        _ = self.corpus[130]
        # Does retrieving the item load the correct shard?
        self.assertEqual(self.corpus.current_shard_n, 1)

        item = self.corpus[220:227]

        self.assertEqual((7, self.corpus.dim), item.shape)
        self.assertEqual(self.corpus.current_shard_n, 2)

        for i in xrange(220, 227):
            self.assertTrue(numpy.array_equal(self.corpus[i], item[i-220]))

Example 36

Project: nolearn Source File: test_base.py
    def test_save_params_to_path(self, net_fitted, X_test, y_pred):
        path = '/tmp/test_lasagne_functional_mnist.params'
        net_fitted.save_params_to(path)
        net_loaded = clone(net_fitted)
        net_loaded.load_params_from(path)
        assert np.array_equal(net_loaded.predict(X_test), y_pred)

Example 37

Project: Uranium Source File: Polygon.py
Function: eq
    def __eq__(self, other):
        if self is other:
            return True
        if type(other) is not Polygon:
            return False

        point_count = len(self._points) if self._points is not None else 0
        point_count2 = len(other.getPoints()) if other.getPoints() is not None else 0
        if point_count != point_count2:
            return False
        return numpy.array_equal(self._points, other.getPoints())

Example 38

Project: diogenes Source File: test_modify.py
    def test_col_val_eq_any(self):
        M = cast_list_of_list_to_sa(
            [[1,2,3], [1,3,4], [1,4,5]],
            col_names=['height','weight', 'age'])
        arguments = [{'func': col_val_eq_any,  'vals': None}]  
        M = remove_cols_where(M, arguments)  
        correct = cast_list_of_list_to_sa(
            [[2,3], [3,4], [4,5]],
            col_names=['weight', 'age'])    
        self.assertTrue(np.array_equal(M, correct)) 

Example 39

Project: butterflow Source File: test_source.py
    def test_read_after_seek_to_fr_at_edges(self):
        self.src_3.seek_to_fr(0)
        f1 = self.src_3.read()
        f2 = avutil_fr_at_idx(self.src_3.src, self.imagefile, 0)
        self.assertTrue(np.array_equal(f1,f2))
        self.src_3.seek_to_fr(2)
        f1 = self.src_3.read()
        f2 = avutil_fr_at_idx(self.src_3.src, self.imagefile, 2)
        self.assertTrue(np.array_equal(f1,f2))

Example 40

Project: bhmm Source File: test_bhmm.py
    def test_transition_matrix_stats(self):
        import msmtools.analysis as msmana
        # mean
        Pmean = self.sampled_hmm_lag10.transition_matrix_mean
        # test shape and consistency
        assert np.array_equal(Pmean.shape, (self.nstates, self.nstates))
        assert msmana.is_transition_matrix(Pmean)
        # std
        Pstd = self.sampled_hmm_lag10.transition_matrix_std
        # test shape
        assert np.array_equal(Pstd.shape, (self.nstates, self.nstates))
        # conf
        L, R = self.sampled_hmm_lag10.transition_matrix_conf
        # test shape
        assert np.array_equal(L.shape, (self.nstates, self.nstates))
        assert np.array_equal(R.shape, (self.nstates, self.nstates))
        # test consistency
        assert np.all(L <= Pmean)
        assert np.all(R >= Pmean)

Example 41

Project: datasketch Source File: hyperloglog.py
Function: eq
    def __eq__(self, other):
        '''
        Check equivalence between two HyperLogLogs
        '''
        if self.p != other.p:
            return False
        if self.m != other.m:
            return False
        if not np.array_equal(self.reg, other.reg):
            return False
        return True

Example 42

Project: molecular-design-toolkit Source File: molecule.py
    def get_property(self, name):
        """ Return the given property if already calculated; raise NotCalculatedError otherwise

        Args:
            name (str): name of the property (e.g. 'potential_energy', 'forces', etc.)

        Raises:
            NotCalculatedError: If the molecular property has not yet been calculated at this
                geometry

        Returns:
            object: the requested property
        """
        if name in self.properties and np.array_equal(self.properties.positions, self.positions):
            return self.properties[name]
        else:
            raise NotCalculatedError(
                    ("The '{0}' property hasn't been calculated yet. "
                     "Calculate it with the molecule.calculate_{0}() method").format(name))

Example 43

Project: datasketch Source File: weighted_minhash.py
Function: eq
    def __eq__(self, other):
        '''
        Check equivalence between WeightedMinHash
        '''
        return self.seed == other.seed and \
                np.array_equal(self.hashvalues, other.hashvalues)

Example 44

Project: pyphi Source File: test_convert.py
def test_to_n_dimensional():
    N = state_by_node.shape[-1]
    S = state_by_node.shape[0]
    result = convert.to_n_dimensional(state_by_node)
    for i in range(S):
        state = convert.loli_index2state(i, N)
        assert np.array_equal(result[state], state_by_node[i])

Example 45

Project: plip Source File: supplemental.py
def vecangle(v1, v2, deg=True):
    """Calculate the angle between two vectors
    :param v1: coordinates of vector v1
    :param v2: coordinates of vector v2
    :returns : angle in degree or rad
    """
    if np.array_equal(v1, v2):
        return 0.0
    dm = np.dot(v1, v2)
    cm = np.linalg.norm(v1) * np.linalg.norm(v2)
    angle = np.arccos(round(dm / cm, 10))  # Round here to prevent floating point errors
    return np.degrees([angle, ])[0] if deg else angle

Example 46

Project: python-rasterstats Source File: test_io.py
Function: test_raster
def test_Raster():
    import numpy as np

    bounds = (244156, 1000258, 245114, 1000968)
    r1 = Raster(raster, band=1).read(bounds)

    with rasterio.open(raster) as src:
        arr = src.read(1)
        affine = src.affine
        nodata = src.nodata

    r2 = Raster(arr, affine, nodata, band=1).read(bounds)

    # If the abstraction is correct, the arrays are equal
    assert np.array_equal(r1.array, r2.array)

Example 47

Project: molecular-design-toolkit Source File: test_data_structures.py
def test_h2_cache_flush(h2_harmonic):
    h2 = h2_harmonic
    pe = h2.calc_potential_energy()
    f = h2.forces
    h2.atoms[0].x += 0.1285*u.ang
    pe2 = h2.calc_potential_energy()
    f2 = h2.forces
    assert pe != pe2
    assert not np.array_equal(f, f2)

Example 48

Project: attention-lvcsr Source File: test_opt.py
    def test_remove_inplace(self):
        mySymbolicMatricesList = TypedListType(T.TensorType(
                                               theano.config.floatX, (False, False)))()
        mySymbolicMatrix = T.matrix()
        z = Remove()(mySymbolicMatricesList, mySymbolicMatrix)
        m = theano.compile.mode.get_default_mode().including("typed_list_inplace_opt")
        f = theano.function([In(mySymbolicMatricesList, borrow=True,
                            mutable=True), In(mySymbolicMatrix, borrow=True,
                            mutable=True)], z, accept_inplace=True, mode=m)
        self.assertTrue(f.maker.fgraph.toposort()[0].op.inplace)

        x = rand_ranged_matrix(-1000, 1000, [100, 101])

        y = rand_ranged_matrix(-1000, 1000, [100, 101])

        self.assertTrue(numpy.array_equal(f([x, y], y), [x]))

Example 49

Project: bolt Source File: test_spark_chunking.py
Function: test_map_generic
def test_map_generic(sc):

    x = arange(2*8*8).reshape(2, 8, 8)
    b = array(x, sc)

    c = b.chunk(size=(8, 5))
    d = c.map_generic(lambda x: [0, 1]).toarray()

    truth = empty(2*1*2, dtype=object)
    for i in range(truth.shape[0]):
        truth[i] = [0, 1]
    truth = truth.reshape(2, 1, 2)

    assert array_equal(d, truth)

Example 50

Project: pyDive Source File: multiple_axes.py
    def is_distributed_like(self, other):
        if self.distaxes == other.distaxes:
          if all(np.array_equal(my_target_offsets, other_target_offsets) \
            for my_target_offsets, other_target_offsets in zip(self.target_offsets, other.target_offsets)):
              if self.target_ranks == other.target_ranks:
                  return True
        return False
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4