Skip to content

Slicing flex arrays

Graeme Winter edited this page May 26, 2017 · 2 revisions

CCTBX flex arrays have a deliberately NumPy-like syntax, allowing e.g. slicing, array addition in a syntactically clean way. Every so often this can catch you out - for example, if you have a three dimensional flex array, the following code may make sense for printing one "layer":

nz, ny, nx = profile.focus()
for j in range(nz):
  print profile[j,:,:].as_numpy_array()

This will however not work and will raise:

TypeError: All items must be of same type.

If slicing you need to have all of the indices ranges i.e.

for j in range(nz):
  print profile[j:j+1,:,:].as_numpy_array()

This will give you back a 3D array with dimensions (1, ny, nx) - if you want it to be a 2D slice then you will need to take a reference to this and reshape i.e.

for j in range(nz):
  slab = profile[j:j+1,:,:]
  slab.reshape(flex.grid((ny, nx)))
  print slab.as_numpy_array()

This does however take a copy of the data so assigning to slab will not alter the contents of profile.

Clone this wiki locally