summaryrefslogtreecommitdiff
path: root/silx/opencl/test/test_sparse.py
blob: 56f1ba43e94154b5e69234c048bed3ab06fd593e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#!/usr/bin/env python
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2018-2019 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ###########################################################################*/
"""Test of the sparse module"""

import numpy as np
import unittest
import logging
from itertools import product
from ..common import ocl
if ocl:
    import pyopencl.array as parray
    from silx.opencl.sparse import CSR
try:
    import scipy.sparse as sp
except ImportError:
    sp = None
logger = logging.getLogger(__name__)



def generate_sparse_random_data(
    shape=(1000,),
    data_min=0, data_max=100,
    density=0.1,
    use_only_integers=True,
    dtype="f"):
    """
    Generate random sparse data where.

    Parameters
    ------------
    shape: tuple
        Output data shape.
    data_min: int or float
        Minimum value of data
    data_max: int or float
        Maximum value of data
    density: float
        Density of non-zero elements in the output data.
        Low value of density mean low number of non-zero elements.
    use_only_integers: bool
        If set to True, the output data items will be primarily integers,
        possibly casted to float if dtype is a floating-point type.
        This can be used for ease of debugging.
    dtype: str or numpy.dtype
        Output data type
    """
    mask = np.random.binomial(1, density, size=shape)
    if use_only_integers:
        d = np.random.randint(data_min, high=data_max, size=shape)
    else:
        d = data_min + (data_max - data_min) * np.random.rand(*shape)
    return (d * mask).astype(dtype)



@unittest.skipUnless(ocl and sp, "PyOpenCl/scipy is missing")
class TestCSR(unittest.TestCase):
    """Test CSR format"""

    def setUp(self):
        self.array = generate_sparse_random_data(shape=(512, 511))
        # Compute reference sparsification
        a_s = sp.csr_matrix(self.array)
        self.ref_data = a_s.data
        self.ref_indices = a_s.indices
        self.ref_indptr = a_s.indptr
        self.ref_nnz = a_s.nnz
        # Test possible configurations
        input_on_device = [False, True]
        output_on_device = [False, True]
        self._test_configs = list(product(input_on_device, output_on_device))


    def test_sparsification(self):
        for input_on_device, output_on_device in self._test_configs:
            self._test_sparsification(input_on_device, output_on_device)


    def _test_sparsification(self, input_on_device, output_on_device):
        current_config = "input on device: %s, output on device: %s" % (
            str(input_on_device), str(output_on_device)
        )
        # Sparsify on device
        csr = CSR(self.array.shape)
        if input_on_device:
            # The array has to be flattened
            arr = parray.to_device(csr.queue, self.array.ravel())
        else:
            arr = self.array
        if output_on_device:
            d_data = parray.zeros_like(csr.data)
            d_indices = parray.zeros_like(csr.indices)
            d_indptr = parray.zeros_like(csr.indptr)
            output = (d_data, d_indices, d_indptr)
        else:
            output = None
        data, indices, indptr = csr.sparsify(arr, output=output)
        if output_on_device:
            data = data.get()
            indices = indices.get()
            indptr = indptr.get()
        # Compare
        nnz = self.ref_nnz
        self.assertTrue(
            np.allclose(data[:nnz], self.ref_data),
            "something wrong with sparsified data (%s)"
            % current_config
        )
        self.assertTrue(
            np.allclose(indices[:nnz], self.ref_indices),
            "something wrong with sparsified indices (%s)"
            % current_config
        )
        self.assertTrue(
            np.allclose(indptr, self.ref_indptr),
            "something wrong with sparsified indices pointers (indptr) (%s)"
            % current_config
        )


    def test_desparsification(self):
        for input_on_device, output_on_device in self._test_configs:
            self._test_desparsification(input_on_device, output_on_device)


    def _test_desparsification(self, input_on_device, output_on_device):
        current_config = "input on device: %s, output on device: %s" % (
            str(input_on_device), str(output_on_device)
        )
        # De-sparsify on device
        csr = CSR(self.array.shape, max_nnz=self.ref_nnz)
        if input_on_device:
            data = parray.to_device(csr.queue, self.ref_data)
            indices = parray.to_device(csr.queue, self.ref_indices)
            indptr = parray.to_device(csr.queue, self.ref_indptr)
        else:
            data = self.ref_data
            indices = self.ref_indices
            indptr = self.ref_indptr
        if output_on_device:
            d_arr = parray.zeros_like(csr.array)
            output = d_arr
        else:
            output = None
        arr = csr.densify(data, indices, indptr, output=output)
        if output_on_device:
            arr = arr.get()
        # Compare
        self.assertTrue(
            np.allclose(arr.reshape(self.array.shape), self.array),
            "something wrong with densified data (%s)"
            % current_config
        )



def suite():
    suite = unittest.TestSuite()
    suite.addTest(
        unittest.defaultTestLoader.loadTestsFromTestCase(TestCSR)
    )
    return suite


if __name__ == '__main__':
    unittest.main(defaultTest="suite")