Domanda

I'm using

p = VN.vtk_to_numpy(data.GetCellData().GetArray('p'))

to read a 3D scalar from a .vtk file written this way :

p_x1y1z1 p_x2y1z1 p_x3y1z1 p_x4y1z1 p_x1y2z1 p_x2y2z1 p_x3y2z1 p_x4y2z1

and so on, with loops aroud x, y and z.

I'd like to fill a 3D numpy array with these data (it's a regular grid), something like p(i,j,k)=p_ijk so I can use the gradient and other operators from the numpy toolbox.

Any ideas?

Regards

È stato utile?

Soluzione

If I understand your situation correctly, you can just reshape it.

In [132]: p = np.array("p_x1y1z1 p_x2y1z1 p_x3y1z1 p_x4y1z1 p_x1y2z1 p_x2y2z1 p_x3y2z1 p_x4y2z1".split())

In [133]: p
Out[133]: 
array(['p_x1y1z1', 'p_x2y1z1', 'p_x3y1z1', 'p_x4y1z1', 'p_x1y2z1', 'p_x2y2z1', 'p_x3y2z1', 'p_x4y2z1'], 
      dtype='|S8')

It appears to me that your array is ordered in what numpy calls 'F' ordering:

In [168]: p.reshape(4, 2, order='F')
Out[168]: 
array([['p_x1y1z1', 'p_x1y2z1'],
       ['p_x2y1z1', 'p_x2y2z1'],
       ['p_x3y1z1', 'p_x3y2z1'],
       ['p_x4y1z1', 'p_x4y2z1']], 
      dtype='|S8')

If you have z variance, too, simply reshape to three dimensions:

In [169]: q
Out[169]: 
array(['p_x1y1z1', 'p_x2y1z1', 'p_x3y1z1', 'p_x4y1z1', 'p_x1y2z1',
       'p_x2y2z1', 'p_x3y2z1', 'p_x4y2z1', 'p_x1y1z2', 'p_x2y1z2',
       'p_x3y1z2', 'p_x4y1z2', 'p_x1y2z2', 'p_x2y2z2', 'p_x3y2z2',
       'p_x4y2z2', 'p_x1y1z3', 'p_x2y1z3', 'p_x3y1z3', 'p_x4y1z3',
       'p_x1y2z3', 'p_x2y2z3', 'p_x3y2z3', 'p_x4y2z3'], 
      dtype='|S8')

In [170]: q.reshape(4,2,3,order='F')
Out[170]: 
array([[['p_x1y1z1', 'p_x1y1z2', 'p_x1y1z3'],
        ['p_x1y2z1', 'p_x1y2z2', 'p_x1y2z3']],

       [['p_x2y1z1', 'p_x2y1z2', 'p_x2y1z3'],
        ['p_x2y2z1', 'p_x2y2z2', 'p_x2y2z3']],

       [['p_x3y1z1', 'p_x3y1z2', 'p_x3y1z3'],
        ['p_x3y2z1', 'p_x3y2z2', 'p_x3y2z3']],

       [['p_x4y1z1', 'p_x4y1z2', 'p_x4y1z3'],
        ['p_x4y2z1', 'p_x4y2z2', 'p_x4y2z3']]], 
      dtype='|S8')

This assumes x,y,z should map to i+1,j+1,k+1, as seen here:

In [175]: r = q.reshape(4,2,3,order='F')

In [176]: r[0]   #all x==1
Out[176]: 
array([['p_x1y1z1', 'p_x1y1z2', 'p_x1y1z3'],
       ['p_x1y2z1', 'p_x1y2z2', 'p_x1y2z3']], 
      dtype='|S8')

In [177]: r[:,0]  # all y==1
Out[177]: 
array([['p_x1y1z1', 'p_x1y1z2', 'p_x1y1z3'],
       ['p_x2y1z1', 'p_x2y1z2', 'p_x2y1z3'],
       ['p_x3y1z1', 'p_x3y1z2', 'p_x3y1z3'],
       ['p_x4y1z1', 'p_x4y1z2', 'p_x4y1z3']], 
      dtype='|S8')

In [178]: r[:,:,0]  #all z==1
Out[178]: 
array([['p_x1y1z1', 'p_x1y2z1'],
       ['p_x2y1z1', 'p_x2y2z1'],
       ['p_x3y1z1', 'p_x3y2z1'],
       ['p_x4y1z1', 'p_x4y2z1']], 
      dtype='|S8')
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top