Cody Eilar | 12 Apr 23:10 2015
Picon

Playing Nice with OpenCV Objects

Hello, 

    I have a situation where I would like to wrap custom classes which I wrote in C++ that leverage OpenCV. As you may be aware, OpenCV already provides many wrappers for their interface making much of my work easy. However, I want my wrapped classes to be able to play nice with the OpenCV wrapped class. Here is an example of what I am talking about: 

import cv2
cap
=cv2.VideoCapture("my_video.mp4") #Already available in OpenCV

from my_cython_wrapper import * #My compiled cython wrapper
output=[]# Some list of stuff I need
myclass
=MyAwesomeClass()
myclass
.DoStuffWithVideoCapture(cap, output)
#
# Play with output in python...
#


Is this even possible? Or would I also have to wrap the Video capture object in my cython stuff in order to get this to work? I was hoping to not have to duplicate work.  In the underlying C++ code, the VideoCapture object is just a pointer that I pass around and so I was thinking that OpenCV would just give me a pointer to the VideoCapture object that I could use in Python land. I've asked the stackoverflow community about this as well here: Wrapping C++ Function With OpenCV Parameters in Cython

Thanks for any advice!

~Cody 

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Nathann Cohen | 12 Apr 22:04 2015
Picon

struct and C function with the same name: mallinfo from malloc.h

Hello everybody,

I am trying to call and use mallinfo() defined in malloc.h [1]

As you can see, mallinfo() returns a struct of type mallinfo (the name is the
same), and so in order to call it I must define both the struct and the function
in Cython.

Did I make a mistake somewhere? Or do I guess correctly that Cython does not
like to see the same name twice?

I 'fixed' my problem by writing my short function in a .c file which I then call
through Cython, but I thought I would report this anyway. It would be cleaner in
pure Cython.

The code follows. Thank you for your help!

Cheers,

Nathann

[1] http://man7.org/linux/man-pages/man3/mallinfo.3.html

----- code -------
cdef extern from "malloc.h":
    void malloc_stats()
    struct mallinfo:
        int arena
        int ordblks
        int smblks
        int hblks
        int hblkhd
        int usmblks
        int fsmblks
        int uordblks
        int fordblks
        int keepcost
    mallinfo mallinfo()

def print_uordblks():
    cdef mallinfo a = mallinfo()
    print a.uordblks

------ Cython output ------

warning: _home_ncohen_test_pyx_1.pyx:22:21: Function signature does not match previous declaration

Error compiling Cython file:
------------------------------------------------------------
...
        int fordblks
        int keepcost
    mallinfo mallinfo()

def print_uordblks():
    cdef mallinfo a = mallinfo()
                 ^
------------------------------------------------------------

_home_ncohen_test_pyx_1.pyx:25:18: Non-extern C function 'a' declared but not defined


Error compiling Cython file:
------------------------------------------------------------
...
        int fordblks
        int keepcost
    mallinfo mallinfo()

def print_uordblks():
    cdef mallinfo a = mallinfo()
                             ^
------------------------------------------------------------

_home_ncohen_test_pyx_1.pyx:25:30: 'mallinfo' is not a constant, variable or function identifier


Error compiling Cython file:
------------------------------------------------------------
...
        int fordblks
        int keepcost
    mallinfo mallinfo()

def print_uordblks():
    cdef mallinfo a = mallinfo()
        ^
------------------------------------------------------------

_home_ncohen_test_pyx_1.pyx:25:9: Assignment to non-lvalue 'a'


Error compiling Cython file:
------------------------------------------------------------
...

<at> cname("__Pyx_CFunc_mallinfo_______to_py")
cdef object __Pyx_CFunc_mallinfo_______to_py(mallinfo (*f)() except *):
                                                         ^
------------------------------------------------------------

cfunc.to_py:29:58: Function cannot return a function

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Nicolas meza retamal | 12 Apr 07:31 2015
Picon

Cython IO : Error raising

Hi , 

I tried to compile the .pyx code that appears here : http://www.code-corner.de/?p=183read%20files%

from libc.stdio cimport *

cdef extern from "stdio.h":

#FILE * fopen ( const char *filename, const char *mode )

FILE *fopen(const char*, const char*)

#int fclose ( FILE * stream )

int fclose(FILE *)

#ssize_t getline(char **lineptr, size_t *n, FILE *stream);

ssize_t getline(char **, size_t *, FILE *)


def read_file(filename):

filename_byte_string = filename.encode("UTF-8")

cdef char* fname = filename_byte_string

cdef FILE* cfile

cfile = fopen(fname, "rb")

if cfile == NULL:

raise FileNotFoundError(2, "No such file or directory: '%s'" % filename)

cdef char * line = NULL

cdef size_t l = 0

cdef ssize_t read

while True:

read = getline(&line, &l, cfile)

printf("%s", line)

if read == -1: break

#yield line

fclose(cfile)

return []





When compiling i get the following : 


Error compiling Cython file:

------------------------------------------------------------

...

    cdef char* fname = filename_byte_string

 

    cdef FILE* cfile

    cfile = fopen(fname, "rb")

    if cfile == NULL:

        raise FileNotFoundError(2, "No such file or directory: '%s'" % filename)

                              ^

------------------------------------------------------------


cython_test.pyx:18:31: undeclared name not builtin: FileNotFoundError

Traceback (most recent call last):

  File "setup_test.py", line 14, in <module>

    ext_modules = cythonize(ext_modules)

  File "/usr/local/lib/python2.7/dist-packages/Cython/Build/Dependencies.py", line 865, in cythonize

    cythonize_one(*args[1:])

  File "/usr/local/lib/python2.7/dist-packages/Cython/Build/Dependencies.py", line 985, in cythonize_one

    raise CompileError(None, pyx_file)

Cython.Compiler.Errors.CompileError: cython_test.pyx


I dont know whats wrong. Any help ? 



Thanks 

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
henry tang | 11 Apr 14:51 2015
Picon

PyrexScanner' object has no attribute 'position'

I was trying to compile pylearn2 but

File "/usr/local/lib/python2.7/site-packages/Cython-0.19.1-py2.7-linux-x86_64.egg/Cython/Compiler/Parsing.py", line 1916, in p_statement_list
pos = s.position()
AttributeError: 'Cython.Compiler.Scanning.PyrexScanner' object has no attribute 'position'

I googled and there is similar topic before, but I still don't know how to solve my problem. Please help. Thanks!

That's because position() is compiled as a cdef method here:
https://github.com/cython/cython/blob/master/Cython/Plex/Scanners.pxd


--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Zahra Sheikh | 10 Apr 19:02 2015
Picon

declare a method pointer in cython

I have a question regarding to declaration of a method of a class. I have written the cosmology class and now I would like to declare a method of this class (Da) since I would like to use it in another class but since my C knowledge is not enough and by googling my problem I couldn't find any answer I will appreciate if I will get a tip:

ctypedef double* (* Da)(double* z, double z_ref, int length)

cdef extern from "gsl/gsl_math.h":
    ctypedef struct gsl_function:
        double (* function) (double x, void * params)
        void * params

cdef extern from "gsl/gsl_integration.h":
    ctypedef struct gsl_integration_workspace
    gsl_integration_workspace *  gsl_integration_workspace_alloc(size_t n)
    void  gsl_integration_workspace_free(gsl_integration_workspace * w)
    int  gsl_integration_qags(const gsl_function * f, double a, double b, double epsabs, double epsrel, size_t limit, gsl_integration_workspace * workspace, double *result, double *abserr)

cdef double func_callback(double x, void* params): 
     return (<cosmology>params).__angKernel(x) 

cdef class cosmology(object):
    cdef public double omega_m, omega_l, h, w, omega_r, G, v_c
    cdef object omega_c
    def __init__(self,double omega_m = 0.3, double omega_l = 0.7, double h = 0.7, double w = -1, double omega_r = 0., double G = std_G):

        self.omega_m = omega_m
        self.omega_l = omega_l
        self.omega_r = omega_r
        self.omega_c = (1. - omega_m - omega_l)
        self.h = h
        self.w = w
        self.G = G
        self.v_c = v_c

    def __copy__(self):

        return cosmology(omega_m = self.omega_m, omega_l = self.omega_l, h = self.h, w = self.w, omega_r = self.omega_r, G = self.G)

    property H0:
       def __get__(self):
           return 100*self.h  #km/s/MPC
    
    cpdef double a(self, double z):
        return 1./(1.+z)

    cpdef double E(self, double a):
        return (self.omega_r*a**(-4) + self.omega_m*a**(-3) + self.omega_c*a**(-2) + self.omega_l)**0.5
        
    <at> cython.boundscheck(False)
    <at> cython.wraparound(False)
    <at> cython.cdivision(True)   
    cdef double __angKernel(self, double x):
         return self.E(x**-1)**-1

    <at> cython.cdivision(True)    
    <at> cython.boundscheck(False)
    <at> cython.wraparound(False)
    cdef double* Da(self, double* z, double z_ref=0, int N):
          cdef gsl_integration_workspace* w =gsl_integration_workspace_alloc(1000)

          cdef gsl_function F
          F.function = &func_callback
          F.params = <void*>self

          cdef double result = 3, error = 5
          cdef double err, rk, zs, omc, tmp
          omc=self.omega_c
          cdef double[::1] d = np.empty((N))
          cdef double* Dptr = &d[0]
          cdef int i
          for i in range(N):
              if z[i] < 0:
                 raise ValueError("Redshift z must not be negative")
              if z[i] < z_ref:
                 raise ValueError("Redshift z must not be smaller than the reference redshift")
              gsl_integration_qags(&F, z_ref+1, z[i]+1, 0, 1e-7, 1000, w, &result, &error)
              tmp, err = result, error 
              # check for curvature
              rk = (fabs(omc))**0.5
              if (rk*tmp > 0.01):
                 if omc > 0:
                    tmp = sinh(rk*tmp)/rk
                 if omc < 0:
                    tmp = sin(rk*tmp)/rk
                    
              Dptr[i]=tmp/(z[i]+1.)
              
          gsl_integration_workspace_free(w) 
          return d

Thanks in advance.

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Jeroen Demeyer | 10 Apr 15:23 2015
Picon

Disabling exception checking?

Hello Cython users/developers,

this is most likely a wishlist item, but in case there is a very simple 
solution for the issue below, I'd like to know.

What I would like to do is to be able to selectively disable checking 
for exceptions in Cython code. Something like

with cython.exceptioncheck(False):
     a = foo()

if <PyObject*>a == NULL:
     handle_exception()

Or analogously

cdef int foo() except -1

with cython.exceptioncheck(False):
     a = foo()

if a == -1:
     handle_exception()

The function handle_exception() would be some custom exception handler 
which inspects PyErr_Occurred.

So far, I have solved this problem by using the C/API or redeclaring 
functions with a different signature. This works, but it's not really clean.

--

-- 

--- 
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Nathann Cohen | 9 Apr 09:35 2015
Picon

Type checking specializations: define variables conditionally

Hello everybody,

Yesterday I used type checking specializations for the first time. Following the
example given at [1]. I wrote a code similar to that:

if my_fused_type is int:
   <do something>
else:
   <do something>

Because my 'second type' is more complicated than int, I need to create helper
variables to write my code. The helper variables are only useful in the second
branch. But:

if my_fused_type is int:
   <do something>
else:
   cdef fancy_type my_helper_variables
   <do something>

Cython, however, complains that I should not define new variables inside of a
'if'. Now,

1) I understand that I can define my_helper_variable before the 'if'. That's
   what I did, and it works fine.

2) I expect that gcc will discard it during compilation as it is never used.

This being said, I still think that allowing this specific kind of conditional
declaration (for type checking specializations only) would make the code easier
to understand: "the code which appears inside the 'if' applies to a specific
specialization", and the rest applies to both.

Anyway thanks for the language you develop. It is the best I know, for
absolutely everything.

Nathann

[1] http://docs.cython.org/src/userguide/fusedtypes.html#type-checking-specializations

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Hai Nguyen | 9 Apr 06:59 2015
Picon

Problems compiling on OSX 10.10: cythonized code

hi all,

I am working on a package included in another program suite that needs to distribute cythonized c++ code for those who does not have Cython (targeted audience is not only for Python community).

All the compiling stuff and testing passed nicely on travis with/without cython supported.

My friend tried to compile with OSX 10.10 and to the error like "error: call to 'toupper' is ambiguous
*buf = toupper(*buf);"

I believe the `toupper(*buf)` is from buffer.c in Cython/Utility/ folder.

Is there any suggestion how to overcome this error. Thanks. Below is the full error

arch i386 -pipe -I/Users/rcw/amber/amber//AmberTools/src/cpptraj//src/ -I/Users/rcw/Dropbox/amber/amber/AmberTools/src/pytraj/pytraj/ -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c /Users/rcw/Dropbox/amber/amber/AmberTools/src/pytraj/pytraj/gdt/gdt.cpp -o build/temp.macosx-10.10-intel-2.7/Users/rcw/Dropbox/amber/amber/AmberTools/src/pytraj/pytraj/gdt/gdt.o -O0 -ggdb
/Users/rcw/Dropbox/amber/amber/AmberTools/src/pytraj/pytraj/gdt/gdt.cpp:1010:9: warning: conversion from string literal to 'char *' is
      deprecated [-Wc++11-compat-deprecated-writable-strings]
        PyErr_BadInternalCall();
        ^
/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/pyerrors.h:220:56: note: expanded from macro
      'PyErr_BadInternalCall'
#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
                                                       ^
<scratch space>:406:1: note: expanded from here
"/Users/rcw/Dropbox/amber/amber/AmberTools/src/pytraj/pytraj/gdt/gdt.cpp"
^
/Users/rcw/Dropbox/amber/amber/AmberTools/src/pytraj/pytraj/gdt/gdt.cpp:16626:24: error: call to 'toupper' is ambiguous
                *buf = toupper(*buf);
                       ^~~~~~~
/usr/include/ctype.h:298:1: note: candidate function
toupper(int _c)
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/cctype:157:38: note: candidate
      function
inline _LIBCPP_INLINE_VISIBILITY int toupper(int __c) {return __libcpp_toupper(__c);}
                                     ^
1 warning and 1 error generated.
error: command 'cc' failed with exit status 1
make[2]: *** [pytraj] Error 1
make[1]: *** [serial] Error 2
make: *** [install] Error 2

Hai 


--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Hai Nguyen | 9 Apr 00:30 2015
Picon

<at> x.setter does not work in Cython?

Hi all,

I have been using old way __set__ and __get__ (to work with Cython) but still prefer to use `settter`.

When using this `settter`, I got "TypeError: 'property' object is not callable". I've googled but don't have the answer yet (there is open ticket for this 4 years ago).



I've looked at Cython test folder: $CYTHONHOME/tests/run and find only one test cast (for pure python): property_decorator_T593.py

Is this technical problem so we can not have in cython? thanks.

Hai

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
AMAN singh | 7 Apr 13:01 2015
Picon

Optimize given function

Hi everyone 

Can you help me in optimizing the following function in cython:

cdef fun1(k, x):
    b = np.sqrt(2 / np.pi) * np.exp(k) / k
    z = b * np.sin(x / 2.)
    return b * z
 
k and x can be either scalar or numpy arrays of any dimension.

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Dominique | 7 Apr 05:25 2015
Picon

Performance of Numpy arrays vs. typed memory views

I like the flexibility offered by typed memory views but I'm not understanding why they seem so slow compared to using Numpy arrays. Here's an example where I wrap the BLAS function sswap(). I wrote two interfaces: one for arrays, and one for memory views, and placed them in a module named "mini".

Here's an example where I check that the functions work correctly, and then time both interfaces:

In [1]: import numpy as np
In [2]: import mini
In [3]: n = 5; x = np.array(np.random.rand(n), dtype=np.float32); y = np.array(np.random.rand(n), dtype=np.float32);
In [4]: x
Out[4]: array([ 0.83145463,  0.41686392,  0.00640774,  0.56666642,  0.67668194], dtype=float32)
In [5]: y
Out[5]: array([ 0.45275971,  0.94341093,  0.05329667,  0.76240462,  0.6809091 ], dtype=float32)
In [6]: mini.sswap(x,y)  # Check that sswap() swaps...
In [7]: x
Out[7]: array([ 0.45275971,  0.94341093,  0.05329667,  0.76240462,  0.6809091 ], dtype=float32)
In [8]: y
Out[8]: array([ 0.83145463,  0.41686392,  0.00640774,  0.56666642,  0.67668194], dtype=float32)   # Ok!
In [9]: mini.sswap_np(x,y)
In [10]: x
Out[10]: array([ 0.83145463,  0.41686392,  0.00640774,  0.56666642,  0.67668194], dtype=float32)
In [11]: y
Out[11]: array([ 0.45275971,  0.94341093,  0.05329667,  0.76240462,  0.6809091 ], dtype=float32)  # Ok!

In [12]: n = 200; x = np.array(np.random.rand(n), dtype=np.float32); y = np.array(np.random.rand(n), dtype=np.float32);
In [13]: %timeit mini.sswap(x,y)
100000 loops, best of 3: 2.57 µs per loop
In [14]: %timeit mini.sswap_np(x,y)
10000000 loops, best of 3: 194 ns per loop

I'm linking against the Accelerate framework on OSX 10.9 but I get similar results with OpenBLAS. My code is here so you can check it: https://gist.github.com/55bce28972ba424c3c74

Why is the memory view interface slower by about a factor of 4?

Thanks.

--

---
You received this message because you are subscribed to the Google Groups "cython-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cython-users+unsubscribe <at> googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Gmane