如何在Python中创建dtype cl.cltypes.uint2的变量

问题描述 投票:0回答:1

我需要在Python中为pyopencl创建类型为cl.cltypes.uint2的变量。现在我以这种方式创建它:

key = np.array([(0x01020304, 0x05060708)], dtype=cl.cltypes.uint2)[0]

它肯定是肮脏的hack(如何以更干净的方式创建它?

此:key = cl.cltypes.uint2((0x01020304, 0x05060708))

由于错误而无法使用:'numpy.dtype' object is not callable

python numpy opencl pyopencl
1个回答
0
投票

快速阅读您的链接表明它正在生成复合dtype。不用加载并运行它,我认为您的示例类似于

In [164]: dt = np.dtype([('x',np.uint16),('y',np.uint16)])                                             
In [165]: np.array([(0x01020304, 0x05060708)], dtype=dt)                                               
Out[165]: array([(772, 1800)], dtype=[('x', '<u2'), ('y', '<u2')])
In [166]: dt((0x01020304, 0x05060708))                                                                 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-166-d71cce4777b9> in <module>
----> 1 dt((0x01020304, 0x05060708))

TypeError: 'numpy.dtype' object is not callable

并从数组中提取一条记录:

In [167]: np.array([(0x01020304, 0x05060708)], dtype=dt)[0]                                            
Out[167]: (772, 1800)
In [168]: _.dtype                                                                                      
Out[168]: dtype([('x', '<u2'), ('y', '<u2')])

化合物dtype永远不可调用。

我认为0d'标量'数组比用dtype函数创建的对象要好(尽管它们具有相似的方法)。

对于复合dtype:

In [228]: v = np.array((0x01020304, 0x05060708), dtype=dt)                                             
In [229]: v                                                                                            
Out[229]: array((772, 1800), dtype=[('x', '<u2'), ('y', '<u2')])
In [230]: type(v)                                                                                      
Out[230]: numpy.ndarray
In [231]: v[()]                                                                                        
Out[231]: (772, 1800)
In [232]: type(_)                                                                                      
Out[232]: numpy.void
In [233]: _231.dtype                                                                                   
Out[233]: dtype([('x', '<u2'), ('y', '<u2')])

您可以将这样的数组强制转换为recarray并获得record对象,但我认为创建它们并不容易。

In [234]: v.view(np.recarray)                                                                          
Out[234]: 
rec.array((772, 1800),
          dtype=[('x', '<u2'), ('y', '<u2')])
In [235]: _.x                                                                                          
Out[235]: array(772, dtype=uint16)
In [238]: v.view(np.recarray)[()]                                                                      
Out[238]: (772, 1800)
In [239]: type(_)                                                                                      
Out[239]: numpy.record
© www.soinside.com 2019 - 2024. All rights reserved.