Python numpy.shares_memory() Examples

The following are 30 code examples for showing how to use numpy.shares_memory(). 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: numcodecs   Author: zarr-developers   File: test_compat.py    License: MIT License 6 votes vote down vote up
def test_ensure_contiguous_ndarray_shares_memory():
    typed_bufs = [
        ('u', 1, b'adsdasdas'),
        ('u', 1, bytes(20)),
        ('i', 8, np.arange(100, dtype=np.int64)),
        ('f', 8, np.linspace(0, 1, 100, dtype=np.float64)),
        ('i', 4, array.array('i', b'qwertyuiqwertyui')),
        ('u', 4, array.array('I', b'qwertyuiqwertyui')),
        ('f', 4, array.array('f', b'qwertyuiqwertyui')),
        ('f', 8, array.array('d', b'qwertyuiqwertyui')),
        ('i', 1, array.array('b', b'qwertyuiqwertyui')),
        ('u', 1, array.array('B', b'qwertyuiqwertyui')),
        ('u', 1, mmap.mmap(-1, 10))
    ]
    for expected_kind, expected_itemsize, buf in typed_bufs:
        a = ensure_contiguous_ndarray(buf)
        assert isinstance(a, np.ndarray)
        assert expected_kind == a.dtype.kind
        if isinstance(buf, array.array):
            assert buf.itemsize == a.dtype.itemsize
        else:
            assert expected_itemsize == a.dtype.itemsize
        assert np.shares_memory(a, memoryview(buf)) 
Example 2
Project: MyGrad   Author: rsokl   File: test_sliding_window.py    License: MIT License 6 votes vote down vote up
def test_memory_details(dtype):
    """ Ensure that:
          - function handles non C-contiguous layouts correctly
          - output is view of input
          - output is not writeable"""
    x = np.arange(20).reshape(2, 10).astype(dtype)
    x = np.asfortranarray(x)
    y = sliding_window_view(x, (5,), 5)
    soln = np.array(
        [
            [[0, 1, 2, 3, 4], [10, 11, 12, 13, 14]],
            [[5, 6, 7, 8, 9], [15, 16, 17, 18, 19]],
        ]
    )
    assert not y.flags["WRITEABLE"]
    assert_allclose(actual=y, desired=soln)

    x = np.arange(20).reshape(2, 10)
    x = np.ascontiguousarray(x)
    y = sliding_window_view(x, (5,), 5)
    assert not y.flags["WRITEABLE"]
    assert np.shares_memory(x, y)
    assert_allclose(actual=y, desired=soln) 
Example 3
Project: MyGrad   Author: rsokl   File: test_strategies.py    License: MIT License 6 votes vote down vote up
def test_basic_index(shape: Tuple[int, ...], data: st.SearchStrategy):
    min_dim = data.draw(st.integers(0, len(shape) + 2), label="min_dim")
    max_dim = data.draw(st.integers(min_dim, min_dim + len(shape)), label="max_dim")
    index = data.draw(
        basic_indices(shape=shape, min_dims=min_dim, max_dims=max_dim), label="index"
    )
    x = np.zeros(shape, dtype=int)
    o = x[index]  # raises if invalid index

    note(f"`x[index]`: {o}")
    if o.size and o.ndim > 0:
        assert np.shares_memory(x, o), (
            "The basic index should produce a " "view of the original array."
        )
    assert min_dim <= o.ndim <= max_dim, (
        "The dimensionality input constraints " "were not obeyed"
    ) 
Example 4
Project: Cirq   Author: quantumlib   File: density_matrix_simulator_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_density_matrix_copy():
    sim = cirq.DensityMatrixSimulator()

    q = cirq.LineQubit(0)
    circuit = cirq.Circuit(cirq.H(q), cirq.H(q))

    matrices = []
    for step in sim.simulate_moment_steps(circuit):
        matrices.append(step.density_matrix(copy=True))
    assert all(np.isclose(np.trace(x), 1.0) for x in matrices)
    for x, y in itertools.combinations(matrices, 2):
        assert not np.shares_memory(x, y)

    # If the density matrix is not copied, then applying second Hadamard
    # causes old state to be modified.
    matrices = []
    traces = []
    for step in sim.simulate_moment_steps(circuit):
        matrices.append(step.density_matrix(copy=False))
        traces.append(np.trace(step.density_matrix(copy=False)))
    assert any(not np.isclose(np.trace(x), 1.0) for x in matrices)
    assert all(np.isclose(x, 1.0) for x in traces)
    assert all(not np.shares_memory(x, y)
               for x, y in itertools.combinations(matrices, 2)) 
Example 5
Project: landlab   Author: landlab   File: test_graph_fields.py    License: MIT License 6 votes vote down vote up
def test_grid_field_as_array():
    """Test adding an array as a grid field."""
    fields = ModelDataFields()
    fields.new_field_location("grid", 1)

    fields.at_grid["const"] = [1.0, 2.0]
    assert_array_equal(fields.at_grid["const"], [[1.0, 2.0]])

    val = np.array([1.0, 2.0])
    fields.at_grid["const"] = val
    assert np.shares_memory(val, fields.at_grid["const"])

    val.shape = (1, 1, 2, 1)
    fields.at_grid["const"] = val
    assert_array_equal(fields.at_grid["const"], np.array([[1.0, 2.0]]))
    assert np.shares_memory(val, fields.at_grid["const"]) 
Example 6
Project: recruit   Author: Frank-qlu   File: test_mem_overlap.py    License: Apache License 2.0 5 votes vote down vote up
def test_shares_memory_api():
    x = np.zeros([4, 5, 6], dtype=np.int8)

    assert_equal(np.shares_memory(x, x), True)
    assert_equal(np.shares_memory(x, x.copy()), False)

    a = x[:,::2,::3]
    b = x[:,::3,::2]
    assert_equal(np.shares_memory(a, b), True)
    assert_equal(np.shares_memory(a, b, max_work=None), True)
    assert_raises(np.TooHardError, np.shares_memory, a, b, max_work=1)
    assert_raises(np.TooHardError, np.shares_memory, a, b, max_work=long(1)) 
Example 7
Project: recruit   Author: Frank-qlu   File: test_mem_overlap.py    License: Apache License 2.0 5 votes vote down vote up
def test_may_share_memory_bad_max_work():
    x = np.zeros([1])
    assert_raises(OverflowError, np.may_share_memory, x, x, max_work=10**100)
    assert_raises(OverflowError, np.shares_memory, x, x, max_work=10**100) 
Example 8
Project: recruit   Author: Frank-qlu   File: test_mem_overlap.py    License: Apache License 2.0 5 votes vote down vote up
def test_non_ndarray_inputs():
    # Regression check for gh-5604

    class MyArray(object):
        def __init__(self, data):
            self.data = data

        @property
        def __array_interface__(self):
            return self.data.__array_interface__

    class MyArray2(object):
        def __init__(self, data):
            self.data = data

        def __array__(self):
            return self.data

    for cls in [MyArray, MyArray2]:
        x = np.arange(5)

        assert_(np.may_share_memory(cls(x[::2]), x[1::2]))
        assert_(not np.shares_memory(cls(x[::2]), x[1::2]))

        assert_(np.shares_memory(cls(x[1::3]), x[::2]))
        assert_(np.may_share_memory(cls(x[1::3]), x[::2])) 
Example 9
Project: recruit   Author: Frank-qlu   File: test_umath.py    License: Apache License 2.0 5 votes vote down vote up
def test_prepare_out(self):

        class with_prepare(np.ndarray):
            __array_priority__ = 10

            def __array_prepare__(self, arr, context):
                return np.array(arr).view(type=with_prepare)

        a = np.array([1]).view(type=with_prepare)
        x = np.add(a, a, a)
        # Returned array is new, because of the strange
        # __array_prepare__ above
        assert_(not np.shares_memory(x, a))
        assert_equal(x, np.array([2]))
        assert_equal(type(x), with_prepare) 
Example 10
Project: recruit   Author: Frank-qlu   File: test_numpy.py    License: Apache License 2.0 5 votes vote down vote up
def test_constructor_copy():
    arr = np.array([0, 1])
    result = PandasArray(arr, copy=True)

    assert np.shares_memory(result._ndarray, arr) is False 
Example 11
Project: recruit   Author: Frank-qlu   File: test_base.py    License: Apache License 2.0 5 votes vote down vote up
def test_to_numpy_copy(arr, as_series):
    obj = pd.Index(arr, copy=False)
    if as_series:
        obj = pd.Series(obj.values, copy=False)

    # no copy by default
    result = obj.to_numpy()
    assert np.shares_memory(arr, result) is True

    result = obj.to_numpy(copy=False)
    assert np.shares_memory(arr, result) is True

    # copy=True
    result = obj.to_numpy(copy=True)
    assert np.shares_memory(arr, result) is False 
Example 12
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_mem_overlap.py    License: MIT License 5 votes vote down vote up
def test_shares_memory_api():
    x = np.zeros([4, 5, 6], dtype=np.int8)

    assert_equal(np.shares_memory(x, x), True)
    assert_equal(np.shares_memory(x, x.copy()), False)

    a = x[:,::2,::3]
    b = x[:,::3,::2]
    assert_equal(np.shares_memory(a, b), True)
    assert_equal(np.shares_memory(a, b, max_work=None), True)
    assert_raises(np.TooHardError, np.shares_memory, a, b, max_work=1)
    assert_raises(np.TooHardError, np.shares_memory, a, b, max_work=long(1)) 
Example 13
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_mem_overlap.py    License: MIT License 5 votes vote down vote up
def test_non_ndarray_inputs():
    # Regression check for gh-5604

    class MyArray(object):
        def __init__(self, data):
            self.data = data

        @property
        def __array_interface__(self):
            return self.data.__array_interface__

    class MyArray2(object):
        def __init__(self, data):
            self.data = data

        def __array__(self):
            return self.data

    for cls in [MyArray, MyArray2]:
        x = np.arange(5)

        assert_(np.may_share_memory(cls(x[::2]), x[1::2]))
        assert_(not np.shares_memory(cls(x[::2]), x[1::2]))

        assert_(np.shares_memory(cls(x[1::3]), x[::2]))
        assert_(np.may_share_memory(cls(x[1::3]), x[::2])) 
Example 14
Project: vnpy_crypto   Author: birforce   File: test_mem_overlap.py    License: MIT License 5 votes vote down vote up
def test_shares_memory_api():
    x = np.zeros([4, 5, 6], dtype=np.int8)

    assert_equal(np.shares_memory(x, x), True)
    assert_equal(np.shares_memory(x, x.copy()), False)

    a = x[:,::2,::3]
    b = x[:,::3,::2]
    assert_equal(np.shares_memory(a, b), True)
    assert_equal(np.shares_memory(a, b, max_work=None), True)
    assert_raises(np.TooHardError, np.shares_memory, a, b, max_work=1)
    assert_raises(np.TooHardError, np.shares_memory, a, b, max_work=long(1)) 
Example 15
Project: vnpy_crypto   Author: birforce   File: test_mem_overlap.py    License: MIT License 5 votes vote down vote up
def test_may_share_memory_bad_max_work():
    x = np.zeros([1])
    assert_raises(OverflowError, np.may_share_memory, x, x, max_work=10**100)
    assert_raises(OverflowError, np.shares_memory, x, x, max_work=10**100) 
Example 16
Project: vnpy_crypto   Author: birforce   File: test_mem_overlap.py    License: MIT License 5 votes vote down vote up
def test_non_ndarray_inputs():
    # Regression check for gh-5604

    class MyArray(object):
        def __init__(self, data):
            self.data = data

        @property
        def __array_interface__(self):
            return self.data.__array_interface__

    class MyArray2(object):
        def __init__(self, data):
            self.data = data

        def __array__(self):
            return self.data

    for cls in [MyArray, MyArray2]:
        x = np.arange(5)

        assert_(np.may_share_memory(cls(x[::2]), x[1::2]))
        assert_(not np.shares_memory(cls(x[::2]), x[1::2]))

        assert_(np.shares_memory(cls(x[1::3]), x[::2]))
        assert_(np.may_share_memory(cls(x[1::3]), x[::2])) 
Example 17
Project: vnpy_crypto   Author: birforce   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_prepare_out(self):

        class with_prepare(np.ndarray):
            __array_priority__ = 10

            def __array_prepare__(self, arr, context):
                return np.array(arr).view(type=with_prepare)

        a = np.array([1]).view(type=with_prepare)
        x = np.add(a, a, a)
        # Returned array is new, because of the strange
        # __array_prepare__ above
        assert_(not np.shares_memory(x, a))
        assert_equal(x, np.array([2]))
        assert_equal(type(x), with_prepare) 
Example 18
Project: dimod   Author: dwavesystems   File: test_sampleset.py    License: Apache License 2.0 5 votes vote down vote up
def test_copy_false(self):
        samples_like = np.ones((5, 5))
        labels = list('abcde')
        arr, lab = dimod.as_samples((samples_like, labels))
        np.testing.assert_array_equal(arr, np.ones((5, 5)))
        self.assertEqual(lab, list('abcde'))
        self.assertIs(labels, lab)
        self.assertTrue(np.shares_memory(arr, samples_like)) 
Example 19
Project: dimod   Author: dwavesystems   File: test_sampleset.py    License: Apache License 2.0 5 votes vote down vote up
def test_view(self):
        # make sure that the vectors are views
        ss = dimod.SampleSet.from_samples([[-1, 1], [1, 1]], dimod.SPIN, energy=[5, 5])

        self.assertEqual(set(ss.data_vectors), {'energy', 'num_occurrences'})
        for field, vector in ss.data_vectors.items():
            np.shares_memory(vector, ss.record) 
Example 20
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_mem_overlap.py    License: MIT License 5 votes vote down vote up
def test_shares_memory_api():
    x = np.zeros([4, 5, 6], dtype=np.int8)

    assert_equal(np.shares_memory(x, x), True)
    assert_equal(np.shares_memory(x, x.copy()), False)

    a = x[:,::2,::3]
    b = x[:,::3,::2]
    assert_equal(np.shares_memory(a, b), True)
    assert_equal(np.shares_memory(a, b, max_work=None), True)
    assert_raises(np.TooHardError, np.shares_memory, a, b, max_work=1)
    assert_raises(np.TooHardError, np.shares_memory, a, b, max_work=long(1)) 
Example 21
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_mem_overlap.py    License: MIT License 5 votes vote down vote up
def test_may_share_memory_bad_max_work():
    x = np.zeros([1])
    assert_raises(OverflowError, np.may_share_memory, x, x, max_work=10**100)
    assert_raises(OverflowError, np.shares_memory, x, x, max_work=10**100) 
Example 22
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_mem_overlap.py    License: MIT License 5 votes vote down vote up
def test_non_ndarray_inputs():
    # Regression check for gh-5604

    class MyArray(object):
        def __init__(self, data):
            self.data = data

        @property
        def __array_interface__(self):
            return self.data.__array_interface__

    class MyArray2(object):
        def __init__(self, data):
            self.data = data

        def __array__(self):
            return self.data

    for cls in [MyArray, MyArray2]:
        x = np.arange(5)

        assert_(np.may_share_memory(cls(x[::2]), x[1::2]))
        assert_(not np.shares_memory(cls(x[::2]), x[1::2]))

        assert_(np.shares_memory(cls(x[1::3]), x[::2]))
        assert_(np.may_share_memory(cls(x[1::3]), x[::2])) 
Example 23
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_prepare_out(self):

        class with_prepare(np.ndarray):
            __array_priority__ = 10

            def __array_prepare__(self, arr, context):
                return np.array(arr).view(type=with_prepare)

        a = np.array([1]).view(type=with_prepare)
        x = np.add(a, a, a)
        # Returned array is new, because of the strange
        # __array_prepare__ above
        assert_(not np.shares_memory(x, a))
        assert_equal(x, np.array([2]))
        assert_equal(type(x), with_prepare) 
Example 24
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_mem_overlap.py    License: MIT License 5 votes vote down vote up
def test_shares_memory_api():
    x = np.zeros([4, 5, 6], dtype=np.int8)

    assert_equal(np.shares_memory(x, x), True)
    assert_equal(np.shares_memory(x, x.copy()), False)

    a = x[:,::2,::3]
    b = x[:,::3,::2]
    assert_equal(np.shares_memory(a, b), True)
    assert_equal(np.shares_memory(a, b, max_work=None), True)
    assert_raises(np.TooHardError, np.shares_memory, a, b, max_work=1)
    assert_raises(np.TooHardError, np.shares_memory, a, b, max_work=long(1)) 
Example 25
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_mem_overlap.py    License: MIT License 5 votes vote down vote up
def test_may_share_memory_bad_max_work():
    x = np.zeros([1])
    assert_raises(OverflowError, np.may_share_memory, x, x, max_work=10**100)
    assert_raises(OverflowError, np.shares_memory, x, x, max_work=10**100) 
Example 26
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_mem_overlap.py    License: MIT License 5 votes vote down vote up
def test_non_ndarray_inputs():
    # Regression check for gh-5604

    class MyArray(object):
        def __init__(self, data):
            self.data = data

        @property
        def __array_interface__(self):
            return self.data.__array_interface__

    class MyArray2(object):
        def __init__(self, data):
            self.data = data

        def __array__(self):
            return self.data

    for cls in [MyArray, MyArray2]:
        x = np.arange(5)

        assert_(np.may_share_memory(cls(x[::2]), x[1::2]))
        assert_(not np.shares_memory(cls(x[::2]), x[1::2]))

        assert_(np.shares_memory(cls(x[1::3]), x[::2]))
        assert_(np.may_share_memory(cls(x[1::3]), x[::2])) 
Example 27
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_prepare_out(self):

        class with_prepare(np.ndarray):
            __array_priority__ = 10

            def __array_prepare__(self, arr, context):
                return np.array(arr).view(type=with_prepare)

        a = np.array([1]).view(type=with_prepare)
        x = np.add(a, a, a)
        # Returned array is new, because of the strange
        # __array_prepare__ above
        assert_(not np.shares_memory(x, a))
        assert_equal(x, np.array([2]))
        assert_equal(type(x), with_prepare) 
Example 28
def test_shares_memory_api():
    x = np.zeros([4, 5, 6], dtype=np.int8)

    assert_equal(np.shares_memory(x, x), True)
    assert_equal(np.shares_memory(x, x.copy()), False)

    a = x[:,::2,::3]
    b = x[:,::3,::2]
    assert_equal(np.shares_memory(a, b), True)
    assert_equal(np.shares_memory(a, b, max_work=None), True)
    assert_raises(np.TooHardError, np.shares_memory, a, b, max_work=1)
    assert_raises(np.TooHardError, np.shares_memory, a, b, max_work=long(1)) 
Example 29
def test_may_share_memory_bad_max_work():
    x = np.zeros([1])
    assert_raises(OverflowError, np.may_share_memory, x, x, max_work=10**100)
    assert_raises(OverflowError, np.shares_memory, x, x, max_work=10**100) 
Example 30
def test_non_ndarray_inputs():
    # Regression check for gh-5604

    class MyArray(object):
        def __init__(self, data):
            self.data = data

        @property
        def __array_interface__(self):
            return self.data.__array_interface__

    class MyArray2(object):
        def __init__(self, data):
            self.data = data

        def __array__(self):
            return self.data

    for cls in [MyArray, MyArray2]:
        x = np.arange(5)

        assert_(np.may_share_memory(cls(x[::2]), x[1::2]))
        assert_(not np.shares_memory(cls(x[::2]), x[1::2]))

        assert_(np.shares_memory(cls(x[1::3]), x[::2]))
        assert_(np.may_share_memory(cls(x[1::3]), x[::2]))