Python numpy.shares_memory() Examples

The following are 30 code examples of numpy.shares_memory(). 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 also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: test_sliding_window.py    From MyGrad with 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 #2
Source File: test_strategies.py    From MyGrad with 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 #3
Source File: test_compat.py    From numcodecs with 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 #4
Source File: test_graph_fields.py    From landlab with 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 #5
Source File: density_matrix_simulator_test.py    From Cirq with 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 #6
Source File: test_mem_overlap.py    From twitter-stock-recommendation with 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 #7
Source File: testing.py    From numerox with GNU General Public License v3.0 5 votes vote down vote up
def shares_memory(data1, data_or_array2):
    "True if `data1` shares memory with `data_or_array2`; False otherwise"

    isdata_like = isinstance(data_or_array2, nx.Data)
    isdata_like = isdata_like or isinstance(data_or_array2, nx.Prediction)

    if hasattr(data1, 'column_list'):
        cols = data1.column_list()
    else:
        cols = data1.pairs(as_str=False)
    cols += ['ids']

    for col in cols:
        if col == 'ids':
            a1 = data1.df.index.values
        else:
            a1 = data1.df[col].values
        if isdata_like:
            if col == 'ids':
                a2 = data_or_array2.df.index.values
            else:
                if col not in data_or_array2.df:
                    continue
                a2 = data_or_array2.df[col].values
        else:
            a2 = data_or_array2
        if np.shares_memory(a1, a2):
            return True
    return False 
Example #8
Source File: test_mem_overlap.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with 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 #9
Source File: test_mem_overlap.py    From keras-lambda with 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 #10
Source File: test_mem_overlap.py    From keras-lambda with 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 #11
Source File: test_umath.py    From twitter-stock-recommendation with 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 #12
Source File: test_mem_overlap.py    From twitter-stock-recommendation with 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 #13
Source File: test_mem_overlap.py    From elasticintel with GNU General Public License v3.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 #14
Source File: test_mem_overlap.py    From twitter-stock-recommendation with 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
Source File: test_umath.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with 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 #16
Source File: test_mem_overlap.py    From coffeegrindsize with 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
Source File: test_umath.py    From coffeegrindsize with 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
Source File: test_numpy.py    From coffeegrindsize with MIT License 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 #19
Source File: test_umath.py    From elasticintel with GNU General Public License v3.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 #20
Source File: test_mem_overlap.py    From elasticintel with GNU General Public License v3.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 #21
Source File: test_mem_overlap.py    From coffeegrindsize with 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
Source File: test_mem_overlap.py    From elasticintel with GNU General Public License v3.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 #23
Source File: density_matrix_simulator_test.py    From Cirq with Apache License 2.0 5 votes vote down vote up
def test_final_density_matrix_is_not_last_object():
    sim = cirq.DensityMatrixSimulator()

    q = cirq.LineQubit(0)
    initial_state = np.array([[1, 0], [0, 0]], dtype=np.complex64)
    circuit = cirq.Circuit(cirq.WaitGate(0)(q))
    result = sim.simulate(circuit, initial_state=initial_state)
    assert result.final_density_matrix is not initial_state
    assert not np.shares_memory(result.final_density_matrix, initial_state)
    np.testing.assert_equal(result.final_density_matrix, initial_state) 
Example #24
Source File: test_umath.py    From mxnet-lambda with 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 #25
Source File: test_mem_overlap.py    From mxnet-lambda with 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 #26
Source File: test_mem_overlap.py    From mxnet-lambda with 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 #27
Source File: test_mem_overlap.py    From mxnet-lambda with 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 #28
Source File: test_strategies.py    From MyGrad with MIT License 5 votes vote down vote up
def test_slice_index(size: int, data: st.SearchStrategy):
    index = data.draw(slice_index(size), label="index")
    x = np.empty((size,))
    o = x[index]  # raises if invalid index
    assert isinstance(o, np.ndarray) and o.ndim == 1, (
        "A slice index should produce " "a 1D array from a 1D array"
    )
    if o.size:
        assert np.shares_memory(o, x), "A slice should produce a view of `x`"

    if index.start is not None:
        assert -size <= index.start <= size

    if index.stop is not None:
        assert -size <= index.stop <= size 
Example #29
Source File: test_mem_overlap.py    From recruit with 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 #30
Source File: test_mem_overlap.py    From pySINDy with 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]))