[cctbxbb] flex and numpy caveats

James Stroud xtald00d at gmail.com
Thu Apr 4 00:35:58 PDT 2013

Hello All,

I've noticed some incompatibilities between numpy and cctbx, which is understandable. However, the incompatibilities manifest either as nonsense errors or, worse, not at all.

Following are a couple of examples I have found.

1. The first example should really throw an exception, because silent failures like this can be catastrophic:

py> from numpy import random
py> r = random.randint(2, size=10)
py> r
array([1, 0, 1, 1, 0, 1, 0, 1, 1, 1])
py> list(flex.bool(r))
[True, False, False, False, False, False, False, False, False, False]

This example is clearly due to incorrect assumptions about the internal representations of numpy ndarrays.

Much better behavior can be seen when using a sequence of python `int` objects:

py> list(flex.bool(range(10)))
TypeError                                 Traceback (most recent call last)
/Users/jstroud/Unison/Code/radialx/testdata/<ipython-input-754-dce96b02979e> in <module>()
----> 1 list(flex.bool(range(10)))

TypeError: No registered converter was able to produce a C++ rvalue of type bool from this Python object of type int

2. Although not as potentially catastrophic as the first, the second example should (in a perfect world) either work or throw a more meaningful exception:

py> flex.int(range(10))[r[0]]
TypeError                                 Traceback (most recent call last)
/Users/jstroud/Unison/Code/radialx/testdata/<ipython-input-753-f14587f0ceeb> in <module>()
----> 1 flex.int(range(10))[r[0]]

TypeError: 'numpy.int64' object is not iterable

This example is obviously a result of type checking for a python `int`. The usual python approach of duck-type checking would avoid this problem:

def __getitem__(self, i):
    i = int(i)
  return do_whatever_with_i(i)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://phenix-online.org/pipermail/cctbxbb/attachments/20130404/1c2f0ead/attachment.htm>

More information about the cctbxbb mailing list