Cython: "error fatal: numpy / arrayobject.h: No hay tal archivo o directorio"


Estoy tratando de acelerar la respuesta aquí usando Cython. Intento compilar el código (después de hacer el hack cygwinccompiler.py explicado aquí), pero obtengo un error fatal error: numpy/arrayobject.h: No such file or directory...compilation terminated. ¿Alguien puede decirme si es un problema con mi código, o alguna sutileza esotérica con Cython?

A continuación está mi código. Gracias de antemano:

import numpy as np
import scipy as sp
cimport numpy as np
cimport cython

cdef inline np.ndarray[np.int, ndim=1] fbincount(np.ndarray[np.int_t, ndim=1] x):
    cdef int m = np.amax(x)+1
    cdef int n = x.size
    cdef unsigned int i
    cdef np.ndarray[np.int_t, ndim=1] c = np.zeros(m, dtype=np.int)

    for i in xrange(n):
        c[<unsigned int>x[i]] += 1

    return c

cdef packed struct Point:
    np.float64_t f0, f1

@cython.boundscheck(False)
def sparsemaker(np.ndarray[np.float_t, ndim=2] X not None,
                np.ndarray[np.float_t, ndim=2] Y not None,
                np.ndarray[np.float_t, ndim=2] Z not None):

    cdef np.ndarray[np.float64_t, ndim=1] counts, factor
    cdef np.ndarray[np.int_t, ndim=1] row, col, repeats
    cdef np.ndarray[Point] indices

    cdef int x_, y_

    _, row = np.unique(X, return_inverse=True); x_ = _.size
    _, col = np.unique(Y, return_inverse=True); y_ = _.size
    indices = np.rec.fromarrays([row,col])
    _, repeats = np.unique(indices, return_inverse=True)
    counts = 1. / fbincount(repeats)
    Z.flat *= counts.take(repeats)

    return sp.sparse.csr_matrix((Z.flat,(row,col)), shape=(x_, y_)).toarray()
Author: Community, 2013-02-02

4 answers

En su setup.py, el Extension debe tener el argumento include_dirs=[numpy.get_include()].

Además, te falta np.import_array() en tu código.

--

Ejemplo setup.py:

from distutils.core import setup, Extension
from Cython.Build import cythonize
import numpy

setup(
    ext_modules=[
        Extension("my_module", ["my_module.c"],
                  include_dirs=[numpy.get_include()]),
    ],
)

# Or, if you use cythonize() to make the ext_modules list,
# include_dirs can be passed to setup()

setup(
    ext_modules=cythonize("my_module.pyx"),
    include_dirs=[numpy.get_include()]
)    
 134
Author: Robert Kern,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-26 15:54:01

Para un proyecto de un solo archivo como el suyo, otra alternativa es usar pyximport. No es necesario crear un setup.py ... no necesita siquiera abrir una línea de comandos si usa IPython ... todo es muy conveniente. En su caso, intente ejecutar estos comandos en IPython o en un script Python normal:

import numpy
import pyximport
pyximport.install(setup_args={"script_args":["--compiler=mingw32"],
                              "include_dirs":numpy.get_include()},
                  reload_support=True)

import my_pyx_module

print my_pyx_module.some_function(...)
...

Es posible que necesite editar el compilador, por supuesto. Esto hace que la importación y la recarga funcionen igual para los archivos .pyx que para los archivos .py.

Fuente: http://wiki.cython.org/InstallingOnWindows

 35
Author: Steve Byrnes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-03 23:24:34

El error significa que no se encuentra un archivo de encabezado numpy durante la compilación.

Intenta hacer export CFLAGS=-I/usr/lib/python2.7/site-packages/numpy/core/include/, y luego compilar. Este es un problema con algunos paquetes diferentes. Hay un error archivado en ArchLinux por el mismo problema: https://bugs.archlinux.org/task/22326

 11
Author: John Brodie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-02 00:46:54

Respuesta simple

Una forma más sencilla es agregar la ruta a su archivo distutils.cfg. Su nombre de ruta de Windows 7 es por defecto C:\Python27\Lib\distutils\. Simplemente afirme los siguientes contenidos y debería funcionar:

[build_ext]
include_dirs= C:\Python27\Lib\site-packages\numpy\core\include

Archivo de configuración completo

Para darle un ejemplo de cómo podría ser el archivo de configuración, mi archivo completo dice:

[build]
compiler = mingw32

[build_ext]
include_dirs= C:\Python27\Lib\site-packages\numpy\core\include
compiler = mingw32
 1
Author: strpeter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-14 12:42:15