File: utils.pyx

package info (click to toggle)
astra-toolbox 2.3.0-4
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid
  • size: 4,972 kB
  • sloc: cpp: 24,378; python: 5,048; sh: 3,514; ansic: 1,181; makefile: 518
file content (351 lines) | stat: -rw-r--r-- 12,042 bytes parent folder | download | duplicates (2)
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# -----------------------------------------------------------------------
# Copyright: 2010-2022, imec Vision Lab, University of Antwerp
#            2013-2022, CWI, Amsterdam
#
# Contact: astra@astra-toolbox.com
# Website: http://www.astra-toolbox.com/
#
# This file is part of the ASTRA Toolbox.
#
#
# The ASTRA Toolbox is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# The ASTRA Toolbox is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with the ASTRA Toolbox. If not, see <http://www.gnu.org/licenses/>.
#
# -----------------------------------------------------------------------
#
# distutils: language = c++
# distutils: libraries = astra

import sys
cimport numpy as np
import numpy as np
import builtins
from libcpp.string cimport string
from libcpp.vector cimport vector
from libcpp.list cimport list
from libcpp.utility cimport move
from cython.operator cimport dereference as deref, preincrement as inc
from cpython.pycapsule cimport PyCapsule_IsValid

from . cimport PyXMLDocument
from .PyXMLDocument cimport XMLDocument
from .PyXMLDocument cimport XMLNode
from .PyIncludes cimport *

from .pythonutils import GPULink, checkArrayForLink
from .log import AstraError

cdef extern from "Python.h":
    void* PyLong_AsVoidPtr(object)

cdef extern from *:
    XMLConfig* dynamic_cast_XMLConfig "dynamic_cast<astra::XMLConfig*>" (Config*)

cdef extern from "src/dlpack.h":
    CFloat32VolumeData3D* getDLTensor(obj, const CVolumeGeometry3D &pGeom, string &error)
    CFloat32ProjectionData3D* getDLTensor(obj, const CProjectionGeometry3D &pGeom, string &error)



include "config.pxi"


cdef XMLConfig * dictToConfig(string rootname, dc) except NULL:
    cdef XMLConfig * cfg = new XMLConfig(rootname)
    try:
        readDict(cfg.self, dc)
    except:
        del cfg
        raise
    return cfg

def convert_item(item):
    if isinstance(item, str):
        return item.encode('ascii')

    if type(item) is not dict:
        return item

    out_dict = {}
    for k in item:
        out_dict[convert_item(k)] = convert_item(item[k])
    return out_dict


def wrap_to_bytes(value):
    if isinstance(value, bytes):
        return value
    return str(value).encode('ascii')


def wrap_from_bytes(value):
    return value.decode('ascii')


cdef bool readDict(XMLNode root, _dc) except False:
    cdef XMLNode listbase
    cdef XMLNode itm
    cdef int i
    cdef int j
    cdef double* data

    dc = convert_item(_dc)
    for item in dc:
        val = dc[item]
        if isinstance(val, builtins.list) or isinstance(val, tuple):
            val = np.array(val,dtype=np.float64)
        if isinstance(val, np.ndarray):
            if val.size == 0:
                break
            listbase = root.addChildNode(item)
            contig_data = np.ascontiguousarray(val,dtype=np.float64)
            data = <double*>np.PyArray_DATA(contig_data)
            if val.ndim == 2:
                listbase.setContent(data, val.shape[1], val.shape[0], False)
            elif val.ndim == 1:
                listbase.setContent(data, val.shape[0])
            else:
                raise AstraError("Only 1 or 2 dimensions are allowed")
        elif isinstance(val, dict):
            if item == b'option' or item == b'options' or item == b'Option' or item == b'Options':
                readOptions(root, val)
            else:
                itm = root.addChildNode(item)
                readDict(itm, val)
        else:
            if item == b'type':
                root.addAttribute(< string > b'type', <string> wrap_to_bytes(val))
            else:
                if isinstance(val, builtins.bool):
                    val = int(val)
                itm = root.addChildNode(item, wrap_to_bytes(val))
    return True

cdef bool readOptions(XMLNode node, dc) except False:
    cdef XMLNode listbase
    cdef XMLNode itm
    cdef int i
    cdef int j
    cdef double* data
    for item in dc:
        val = dc[item]
        if node.hasOption(item):
            raise AstraError('Duplicate Option: %s' % item)
        if isinstance(val, builtins.list) or isinstance(val, tuple):
            val = np.array(val,dtype=np.float64)
        if isinstance(val, np.ndarray):
            if val.size == 0:
                break
            listbase = node.addChildNode(b'Option')
            listbase.addAttribute(< string > b'key', < string > item)
            contig_data = np.ascontiguousarray(val,dtype=np.float64)
            data = <double*>np.PyArray_DATA(contig_data)
            if val.ndim == 2:
                listbase.setContent(data, val.shape[1], val.shape[0], False)
            elif val.ndim == 1:
                listbase.setContent(data, val.shape[0])
            else:
                raise AstraError("Only 1 or 2 dimensions are allowed")
        else:
            if isinstance(val, builtins.bool):
                val = int(val)
            node.addOption(item, wrap_to_bytes(val))
    return True

cdef configToDict(Config *cfg):
    cdef XMLConfig* xmlcfg;
    xmlcfg = dynamic_cast_XMLConfig(cfg);
    if not xmlcfg:
        return None
    return XMLNode2dict(xmlcfg.self)

def castString(input):
    return input.decode('utf-8')

def stringToPythonValue(inputIn):
    input = castString(inputIn)
    # matrix
    if ';' in input:
        input = input.rstrip(';')
        row_strings = input.split(';')
        col_strings = row_strings[0].split(',')
        nRows = len(row_strings)
        nCols = len(col_strings)

        out = np.empty((nRows,nCols))
        for ridx, row in enumerate(row_strings):
            col_strings = row.split(',')
            for cidx, col in enumerate(col_strings):
                out[ridx,cidx] = float(col)
        return out

    # vector
    if ',' in input:
        input = input.rstrip(',')
        items = input.split(',')
        out = np.empty(len(items))
        for idx,item in enumerate(items):
            out[idx] = float(item)
        return out

    try:
        # integer
        return int(input)
    except ValueError:
        try:
            #float
            return float(input)
        except ValueError:
            # string
            return str(input)


cdef XMLNode2dict(XMLNode node):
    cdef XMLNode subnode
    cdef list[XMLNode] nodes
    cdef list[XMLNode].iterator it
    dct = {}
    opts = {}
    if node.hasAttribute(b'type'):
        dct['type'] = castString(node.getAttribute(b'type'))
    nodes = node.getNodes()
    it = nodes.begin()
    while it != nodes.end():
        subnode = deref(it)
        if castString(subnode.getName())=="Option":
            if subnode.hasAttribute(b'value'):
                opts[castString(subnode.getAttribute(b'key'))] = stringToPythonValue(subnode.getAttribute(b'value'))
            else:
                opts[castString(subnode.getAttribute(b'key'))] = stringToPythonValue(subnode.getContent())
        else:
            dct[castString(subnode.getName())] = stringToPythonValue(subnode.getContent())
        inc(it)
    if len(opts)>0: dct['options'] = opts
    return dct

def getDLPackCapsule(data):
    # backward compatibility: check if the object is a dltensor capsule already
    if PyCapsule_IsValid(data, "dltensor"):
        return data
    if not hasattr(data, "__dlpack__"):
        return None
    capsule = None
    # TODO: investigate the stream argument to __dlpack__().
    try:
        capsule = data.__dlpack__(max_version = (1,0))
    except AttributeError:
        return None
    except TypeError:
        # unsupported max_version argument raises a TypeError
        pass
    if capsule is not None:
        return capsule

    try:
        capsule = data.__dlpack__()
    except AttributeError:
        return None
    return capsule

cdef CFloat32VolumeData3D* linkVolFromGeometry(const CVolumeGeometry3D &pGeometry, data) except NULL:
    cdef CFloat32VolumeData3D * pDataObject3D = NULL
    cdef CDataStorage * pStorage
    cdef string dlerror = b""

    # TODO: investigate the stream argument to __dlpack__().
    capsule = getDLPackCapsule(data)
    if capsule is not None:
        pDataObject3D = getDLTensor(capsule, pGeometry, dlerror)
        if not pDataObject3D:
            raise ValueError("Failed to link dlpack array: " + wrap_from_bytes(dlerror))
        return pDataObject3D

    if isinstance(data, GPULink):
        geom_shape = (pGeometry.getGridSliceCount(), pGeometry.getGridRowCount(), pGeometry.getGridColCount())
        data_shape = (data.z, data.y, data.x)
        if geom_shape != data_shape:
            raise ValueError("The dimensions of the data {} do not match those "
                             "specified in the geometry {}".format(data_shape, geom_shape))

        IF HAVE_CUDA==True:
            hnd = wrapHandle(<float*>PyLong_AsVoidPtr(data.ptr), data.x, data.y, data.z, data.pitch/4)
            pStorage = new CDataGPU(hnd)
        ELSE:
            raise AstraError("CUDA support is not enabled in ASTRA")
        pDataObject3D = new CFloat32VolumeData3D(pGeometry, pStorage)
        return pDataObject3D

    raise TypeError("Data should be an array with DLPack support, or a GPULink object")


cdef CFloat32ProjectionData3D* linkProjFromGeometry(const CProjectionGeometry3D &pGeometry, data) except NULL:
    cdef CFloat32ProjectionData3D * pDataObject3D = NULL
    cdef CDataStorage * pStorage
    cdef string dlerror = b""

    # TODO: investigate the stream argument to __dlpack__().
    capsule = getDLPackCapsule(data)
    if capsule is not None:
        pDataObject3D = getDLTensor(capsule, pGeometry, dlerror)
        if not pDataObject3D:
            raise ValueError("Failed to link dlpack array: " + wrap_from_bytes(dlerror))
        return pDataObject3D

    if isinstance(data, GPULink):
        geom_shape = (pGeometry.getDetectorRowCount(), pGeometry.getProjectionCount(), pGeometry.getDetectorColCount())
        data_shape = (data.z, data.y, data.x)
        if geom_shape != data_shape:
            raise ValueError("The dimensions of the data {} do not match those "
                             "specified in the geometry {}".format(data_shape, geom_shape))

        IF HAVE_CUDA==True:
            hnd = wrapHandle(<float*>PyLong_AsVoidPtr(data.ptr), data.x, data.y, data.z, data.pitch/4)
            pStorage = new CDataGPU(hnd)
        ELSE:
            raise AstraError("CUDA support is not enabled in ASTRA")
        pDataObject3D = new CFloat32ProjectionData3D(pGeometry, pStorage)
        return pDataObject3D

    raise TypeError("Data should be an array with DLPack support, or a GPULink object")

cdef unique_ptr[CProjectionGeometry3D] createProjectionGeometry3D(geometry) except *:
    cdef XMLConfig *cfg
    cdef unique_ptr[CProjectionGeometry3D] pGeometry

    cfg = dictToConfig(b'ProjectionGeometry', geometry)
    tpe = cfg.self.getAttribute(b'type')
    pGeometry = constructProjectionGeometry3D(tpe)
    if not pGeometry:
        raise ValueError("'{}' is not a valid 3D geometry type".format(tpe))

    if not pGeometry.get().initialize(cfg[0]):
        del cfg
        raise AstraError('Geometry class could not be initialized', append_log=True)

    del cfg

    return move(pGeometry)

cdef unique_ptr[CVolumeGeometry3D] createVolumeGeometry3D(geometry) except *:
    cdef XMLConfig *cfg
    cdef CVolumeGeometry3D * pGeometry
    cfg = dictToConfig(b'VolumeGeometry', geometry)
    pGeometry = new CVolumeGeometry3D()
    if not pGeometry.initialize(cfg[0]):
        del cfg
        del pGeometry
        raise AstraError('Geometry class could not be initialized', append_log=True)

    del cfg

    return unique_ptr[CVolumeGeometry3D](pGeometry)