示例#1
0
    def test_noargs_with_args_not_instantiated(self):
        # calling a function that doesn't take args with args should fail.
        # Note: difference between this test add ``test_noargs_with_args``
        # below is that here Foo is not instantiated.
        def Foo():
            return "blah"

        code = """
               py::tuple args(2);
               args[0] = 1;
               args[1] = "hello";
               return_val = Foo.call(args);
               """
        try:
            first = sys.getrefcount(Foo)
            inline_tools.inline(code,['Foo'])
        except TypeError:
            second = sys.getrefcount(Foo)
            try:
                inline_tools.inline(code,['Foo'])
            except TypeError:
                third = sys.getrefcount(Foo)

        # first should == second, but the weird refcount error
        assert_equal(second,third)
示例#2
0
 def test_set_complex(self):
     a = UserDict()
     key = 1+1j
     inline_tools.inline("a[key] = 1234;",['a','key'])
     assert_equal(sys.getrefcount(key),4) # should be 3
     assert_equal(sys.getrefcount(a[key]),2)
     assert_equal(a[key],1234)
    def test_int_add_speed(self):
        N = 1000000
        print "int add -- b[i] = a[i] + 1 for N =", N
        a = [0] * N
        desired = [1] * N
        t1 = time.time()
        for i in xrange(N):
            desired[i] = a[i] + 1
        t2 = time.time()
        print "python:", t2 - t1

        a = [0] * N
        b = [0] * N
        code = """
               const int N = a.length();
               for(int i=0; i < N; i++)
                   b[i] = (int)a[i] + 1;
               """
        # compile not included in timing
        inline_tools.inline(code, ["a", "b"])
        t1 = time.time()
        inline_tools.inline(code, ["a", "b"])
        t2 = time.time()
        print "weave:", t2 - t1
        assert_(b == desired)
示例#4
0
    def test_int_add_speed(self):
        N = 1000000
        debug_print('int add -- b[i] = a[i] + 1 for N =', N)
        a = [0] * N
        desired = [1] * N
        t1 = time.time()
        for i in xrange(N):
            desired[i] = a[i] + 1
        t2 = time.time()
        debug_print('python:', t2 - t1)

        a = [0] * N
        b = [0] * N
        code = """
               const int N = a.length();
               for(int i=0; i < N; i++)
                   b[i] = (int)a[i] + 1;
               """
        # compile not included in timing
        inline_tools.inline(code,['a','b'])
        t1 = time.time()
        inline_tools.inline(code,['a','b'])
        t2 = time.time()
        debug_print('weave:', t2 - t1)
        assert_(b == desired)
    def test_string_add_speed(self):
        N = 1000000
        print 'string add -- b[i] = a[i] + "blah" for N =', N
        a = ["blah"] * N
        desired = [1] * N
        t1 = time.time()
        for i in xrange(N):
            desired[i] = a[i] + "blah"
        t2 = time.time()
        print "python:", t2 - t1

        a = ["blah"] * N
        b = [1] * N
        code = """
               const int N = a.length();
               std::string blah = std::string("blah");
               for(int i=0; i < N; i++)
                   b[i] = convert_to_string(a[i],"a") + blah;
               """
        # compile not included in timing
        inline_tools.inline(code, ["a", "b"])
        t1 = time.time()
        inline_tools.inline(code, ["a", "b"])
        t2 = time.time()
        print "weave:", t2 - t1
        assert_(b == desired)
    def test_set_item_operator_equal(self):
        a = self.seq_type([1, 2, 3])
        # temporary refcount fix until I understand why it incs by one.
        inline_tools.inline("a[1] = 1234;", ["a"])
        before1 = sys.getrefcount(a)

        # check overloaded insert(int ndx, int val) method
        inline_tools.inline("a[1] = 1234;", ["a"])
        assert_(sys.getrefcount(a[1]) == 2)
        assert_(a[1] == 1234)

        # check overloaded insert(int ndx, double val) method
        inline_tools.inline("a[1] = 123.0;", ["a"])
        assert_(sys.getrefcount(a[1]) == 2)
        assert_(a[1] == 123.0)

        # check overloaded insert(int ndx, char* val) method
        inline_tools.inline('a[1] = "bubba";', ["a"])
        assert_(sys.getrefcount(a[1]) == 2)
        assert_(a[1] == "bubba")

        # check overloaded insert(int ndx, std::string val) method
        code = """
               std::string val = std::string("sissy");
               a[1] = val;
               """
        inline_tools.inline(code, ["a"])
        assert_(sys.getrefcount(a[1]) == 2)
        assert_(a[1] == "sissy")

        after1 = sys.getrefcount(a)
        assert_(after1 == before1)
    def test_access_speed(self):
        N = 1000000
        print "%s access -- val = a[i] for N =", (self.seq_type, N)
        a = self.seq_type([0]) * N
        val = 0
        t1 = time.time()
        for i in xrange(N):
            val = a[i]
        t2 = time.time()
        print "python1:", t2 - t1
        t1 = time.time()
        for i in a:
            val = i
        t2 = time.time()
        print "python2:", t2 - t1

        code = """
               const int N = a.length();
               py::object val;
               for(int i=0; i < N; i++)
                   val = a[i];
               """
        # compile not included in timing
        inline_tools.inline(code, ["a"])
        t1 = time.time()
        inline_tools.inline(code, ["a"])
        t2 = time.time()
        print "weave:", t2 - t1
示例#8
0
 def test_set_double_new(self):
     a = UserDict()
     key = 1.0
     inline_tools.inline('a[key] = 123.0;',['a','key'])
     assert_equal(sys.getrefcount(key),4) # should be 3
     assert_equal(sys.getrefcount(a[key]),2)
     assert_equal(a[key],123.0)
    def test_access_set_speed(self):
        N = 1000000
        print "%s access/set -- b[i] = a[i] for N =", (self.seq_type, N)
        a = self.seq_type([0]) * N
        # b is always a list so we can assign to it.
        b = [1] * N
        t1 = time.time()
        for i in xrange(N):
            b[i] = a[i]
        t2 = time.time()
        print "python:", t2 - t1

        a = self.seq_type([0]) * N
        b = [1] * N
        code = """
               const int N = a.length();
               for(int i=0; i < N; i++)
                   b[i] = a[i];
               """
        # compile not included in timing
        inline_tools.inline(code, ["a", "b"])
        t1 = time.time()
        inline_tools.inline(code, ["a", "b"])
        t2 = time.time()
        print "weave:", t2 - t1
        assert_(list(b) == list(a))
    def test_append(self):
        a = []
        # temporary refcount fix until I understand why it incs by one.
        inline_tools.inline("a.append(1);", ["a"])
        del a[0]

        before1 = sys.getrefcount(a)

        # check overloaded append(int val) method
        inline_tools.inline("a.append(1234);", ["a"])
        assert_(sys.getrefcount(a[0]) == 2)
        assert_(a[0] == 1234)
        del a[0]

        # check overloaded append(double val) method
        inline_tools.inline("a.append(123.0);", ["a"])
        assert_(sys.getrefcount(a[0]) == 2)
        assert_(a[0] == 123.0)
        del a[0]

        # check overloaded append(char* val) method
        inline_tools.inline('a.append("bubba");', ["a"])
        assert_(sys.getrefcount(a[0]) == 2)
        assert_(a[0] == "bubba")
        del a[0]

        # check overloaded append(std::string val) method
        inline_tools.inline('a.append(std::string("sissy"));', ["a"])
        assert_(sys.getrefcount(a[0]) == 2)
        assert_(a[0] == "sissy")
        del a[0]

        after1 = sys.getrefcount(a)
        assert_(after1 == before1)
示例#11
0
 def test_list_refcount(self):
     a = UserList([1,2,3])
     # temporary refcount fix until I understand why it incs by one.
     inline_tools.inline("a[1] = 1234;",['a'])
     before1 = sys.getrefcount(a)
     after1 = sys.getrefcount(a)
     assert_equal(after1,before1)
    def test_count(self):
        """ Test the "count" method for lists.  We'll assume
            it works for sequences if it works hre.
        """
        a = self.seq_type([1, 2, "alpha", 3.1416])

        item = 1
        code = "return_val = a.count(item);"
        res = inline_tools.inline(code, ["a", "item"])
        assert_(res == 1)

        # check overloaded count(int val) method
        code = "return_val = a.count(1);"
        res = inline_tools.inline(code, ["a"])
        assert_(res == 1)

        # check overloaded count(double val) method
        code = "return_val = a.count(3.1416);"
        res = inline_tools.inline(code, ["a"])
        assert_(res == 1)

        # check overloaded count(char* val) method
        code = 'return_val = a.count("alpha");'
        res = inline_tools.inline(code, ["a"])
        assert_(res == 1)

        # check overloaded count(std::string val) method
        code = """
               std::string alpha = std::string("alpha");
               return_val = a.count(alpha);
               """
        res = inline_tools.inline(code, ["a"])
        assert_(res == 1)
示例#13
0
    def test_string_add_speed(self):
        N = 1000000
        debug_print('string add -- b[i] = a[i] + "blah" for N =', N)
        a = ["blah"] * N
        desired = [1] * N
        t1 = time.time()
        for i in xrange(N):
            desired[i] = a[i] + 'blah'
        t2 = time.time()
        debug_print('python:', t2 - t1)

        a = ["blah"] * N
        b = [1] * N
        code = """
               const int N = a.length();
               std::string blah = std::string("blah");
               for(int i=0; i < N; i++)
                   b[i] = convert_to_string(a[i],"a") + blah;
               """
        # compile not included in timing
        inline_tools.inline(code,['a','b'])
        t1 = time.time()
        inline_tools.inline(code,['a','b'])
        t2 = time.time()
        debug_print('weave:', t2 - t1)
        assert_(b == desired)
示例#14
0
    def test_access_speed(self):
        N = 1000000
        debug_print('%s access -- val = a[i] for N =', (self.seq_type, N))
        a = self.seq_type([0]) * N
        val = 0
        t1 = time.time()
        for i in xrange(N):
            val = a[i]
        t2 = time.time()
        debug_print('python1:', t2 - t1)
        t1 = time.time()
        for i in a:
            val = i
        t2 = time.time()
        debug_print('python2:', t2 - t1)

        code = """
               const int N = a.length();
               py::object val;
               for(int i=0; i < N; i++)
                   val = a[i];
               """
        # compile not included in timing
        inline_tools.inline(code,['a'])
        t1 = time.time()
        inline_tools.inline(code,['a'])
        t2 = time.time()
        debug_print('weave:', t2 - t1)
示例#15
0
 def test_complex_cast(self):
     code = """
            std::complex<double> num = std::complex<double>(1.0, 1.0);
            py::object val = num;
            std::complex<double> raw_val __attribute__ ((unused)) = val;
            """
     inline_tools.inline(code)
示例#16
0
 def test_set_item_operator_equal_fail(self):
     # Tuples should only allow setting of variables
     # immediately after creation.
     a = (1,2,3)
     try:
         inline_tools.inline("a[1] = 1234;",['a'])
     except TypeError:
         pass
示例#17
0
 def test_attr_call(self):
     a = Foo()
     res = inline_tools.inline('return_val = a.attr("bar").call();',['a'])
     first = sys.getrefcount(res)
     del res
     res = inline_tools.inline('return_val = a.attr("bar").call();',['a'])
     second = sys.getrefcount(res)
     assert_equal(res,"bar results")
     assert_equal(first,second)
示例#18
0
 def test_conversion(self):
     a = self.seq_type([1])
     before = sys.getrefcount(a)
     inline_tools.inline(" ",['a'])
     # first call is goofing up refcount.
     before = sys.getrefcount(a)
     inline_tools.inline(" ",['a'])
     after = sys.getrefcount(a)
     assert_(after == before)
示例#19
0
 def test_noargs(self):
     a = Foo()
     res = inline_tools.inline('return_val = a.mcall("bar");',['a'])
     assert_equal(res,"bar results")
     first = sys.getrefcount(res)
     del res
     res = inline_tools.inline('return_val = a.mcall("bar");',['a'])
     assert_equal(res,"bar results")
     second = sys.getrefcount(res)
     assert_equal(first,second)
示例#20
0
 def test_py_to_file(self):
     file_name = os.path.join(test_dir, "testfile")
     file = open(file_name,'w')
     code = """
            fprintf(file,"hello bob");
            """
     inline_tools.inline(code,['file'],compiler=self.compiler,force=1)
     file.close()
     file = open(file_name,'r')
     assert_(file.read() == "hello bob")
 def test_conversion(self):
     a = self.seq_type([1])
     before = sys.getrefcount(a)
     inline_tools.inline(" ", ["a"])
     # print 'first:',before
     # first call is goofing up refcount.
     before = sys.getrefcount(a)
     inline_tools.inline(" ", ["a"])
     after = sys.getrefcount(a)
     # print '2nd,3rd:', before, after
     assert_(after == before)
 def test_std_noargs(self):
     a = Foo()
     method = "bar"
     res = inline_tools.inline("return_val = a.mcall(method);", ["a", "method"])
     assert_equal(res, "bar results")
     first = sys.getrefcount(res)
     del res
     res = inline_tools.inline("return_val = a.mcall(method);", ["a", "method"])
     assert_equal(res, "bar results")
     second = sys.getrefcount(res)
     assert_equal(first, second)
示例#23
0
 def test_py_to_file(self):
     import tempfile
     file_name = tempfile.mktemp()
     file = open(file_name,'w')
     code = """
            fprintf(file,"hello bob");
            """
     inline_tools.inline(code,['file'],compiler=self.compiler,force=1)
     file.close()
     file = open(file_name,'r')
     assert_(file.read() == "hello bob")
示例#24
0
 def generic_new(self,key,val):
     # test that value is set correctly and that reference counts
     # on dict, key, and val are being handled correctly.
     a = {}
     # call once to handle mysterious addition of one ref count
     # on first call to inline.
     inline_tools.inline("a[key] = val;",['a','key','val'])
     assert_(a[key] == val)
     before = sys.getrefcount(a), sys.getrefcount(key), sys.getrefcount(val)
     inline_tools.inline("a[key] = val;",['a','key','val'])
     assert_(a[key] == val)
     after = sys.getrefcount(a), sys.getrefcount(key), sys.getrefcount(val)
     assert_(before == after)
示例#25
0
 def test_set_double_exists(self):
     a = UserDict()
     key = 10.0
     a[key] = 100.0
     inline_tools.inline('a[key] = 123.0;',['a','key'])
     first = sys.getrefcount(key)
     inline_tools.inline('a[key] = 123.0;',['a','key'])
     second = sys.getrefcount(key)
     assert_equal(first,second)
     # !! I think the following should be 3
     assert_equal(sys.getrefcount(key),5)
     assert_equal(sys.getrefcount(a[key]),2)
     assert_equal(a[key],123.0)
示例#26
0
def _cast_copy_transpose(type,a_2d):
    assert(len(shape(a_2d)) == 2)
    new_array = zeros(shape(a_2d),type)
    code = """
           for(int i = 0; i < Na_2d[0]; i++)
               for(int j = 0; j < Na_2d[1]; j++)
                   new_array(i,j) = a_2d(j,i);
           """
    inline_tools.inline(code,['new_array','a_2d'],
                        type_converters=cblitz,
                        compiler='gcc',
                        verbose=1)
    return new_array
    def test_in(self):
        """ Test the "in" method for lists.  We'll assume
            it works for sequences if it works here.
        """
        a = self.seq_type([1, 2, "alpha", 3.1416])

        item = 1
        code = "return_val = a.in(item);"
        res = inline_tools.inline(code, ["a", "item"])
        assert_(res == 1)
        item = 0
        res = inline_tools.inline(code, ["a", "item"])
        assert_(res == 0)

        # check overloaded in(int val) method
        code = "return_val = a.in(1);"
        res = inline_tools.inline(code, ["a"])
        assert_(res == 1)
        code = "return_val = a.in(0);"
        res = inline_tools.inline(code, ["a"])
        assert_(res == 0)

        # check overloaded in(double val) method
        code = "return_val = a.in(3.1416);"
        res = inline_tools.inline(code, ["a"])
        assert_(res == 1)
        code = "return_val = a.in(3.1417);"
        res = inline_tools.inline(code, ["a"])
        assert_(res == 0)

        # check overloaded in(char* val) method
        code = 'return_val = a.in("alpha");'
        res = inline_tools.inline(code, ["a"])
        assert_(res == 1)
        code = 'return_val = a.in("beta");'
        res = inline_tools.inline(code, ["a"])
        assert_(res == 0)

        # check overloaded in(std::string val) method
        code = """
               std::string val = std::string("alpha");
               return_val = a.in(val);
               """
        res = inline_tools.inline(code, ["a"])
        assert_(res == 1)
        code = """
               std::string val = std::string("beta");
               return_val = a.in(val);
               """
        res = inline_tools.inline(code, ["a"])
        assert_(res == 0)
示例#28
0
 def generic(self,key):
     # test that value is set correctly and that reference counts
     # on dict, key, are being handled correctly. after deletion,
     # the keys refcount should be one less than before.
     a = {key: 1}
     inline_tools.inline("a.del(key);",['a','key'])
     assert_(key not in a)
     a[key] = 1
     before = sys.getrefcount(a), sys.getrefcount(key)
     inline_tools.inline("a.del(key);",['a','key'])
     assert_(key not in a)
     after = sys.getrefcount(a), sys.getrefcount(key)
     assert_(before[0] == after[0])
     assert_(before[1] == after[1] + 1)
示例#29
0
 def test_unicode(self):
     class Foo:
         def __repr__(self):
             return "repr return"
         def __str__(self):
             return "unicode"
     a= Foo()
     res = inline_tools.inline('return_val = a.unicode();',['a'])
     first = sys.getrefcount(res)
     del res
     res = inline_tools.inline('return_val = a.unicode();',['a'])
     second = sys.getrefcount(res)
     assert_equal(first,second)
     assert_equal(res,"unicode")
示例#30
0
 def test_str(self):
     class Foo:
         def __str__(self):
             return "str return"
         def __repr__(self):
             return "repr return"
     a = Foo()
     res = inline_tools.inline('return_val = a.str();',['a'])
     first = sys.getrefcount(res)
     del res
     res = inline_tools.inline('return_val = a.str();',['a'])
     second = sys.getrefcount(res)
     assert_equal(first,second)
     print res
     assert_equal(res,"str return")
示例#31
0
    def test_set_class(self):
        a = UserDict()

        class Foo:
            def __init__(self, val):
                self.val = val

            def __hash__(self):
                return self.val

        key = Foo(4)
        inline_tools.inline('a[key] = "bubba";', ['a', 'key'])
        first = sys.getrefcount(key)
        inline_tools.inline('a[key] = "bubba";', ['a', 'key'])
        second = sys.getrefcount(key)
        # I don't think we're leaking if this is true
        assert_equal(first, second)
        # !! BUT -- I think this should be 3
        assert_equal(sys.getrefcount(key), 4)
        assert_equal(sys.getrefcount(a[key]), 2)
        assert_equal(a[key], 'bubba')
示例#32
0
 def test_noargs_with_args(self):
     # calling a function that does take args with args
     # should fail.
     a = Foo()
     code = """
            py::tuple args(2);
            args[0] = 1;
            args[1] = "hello";
            return_val = a.mcall("bar",args);
            """
     try:
         first = sys.getrefcount(a)
         res = inline_tools.inline(code, ['a'])
     except TypeError:
         second = sys.getrefcount(a)
         try:
             res = inline_tools.inline(code, ['a'])
         except TypeError:
             third = sys.getrefcount(a)
     # first should == second, but the weird refcount error
     assert_equal(second, third)
示例#33
0
 def test_set_item_operator_equal(self):
     code = """
            py::tuple a(3);
            a[0] = 1;
            a[1] = 2;
            a[2] = 3;
            return_val = a;
            """
     a = inline_tools.inline(code)
     assert a == (1,2,3)
     # returned value should only have a single refcount
     assert sys.getrefcount(a) == 2
示例#34
0
 def test_std_args(self):
     a = Foo()
     method = "bar2"
     code = """
            py::tuple args(2);
            args[0] = 1;
            args[1] = "hello";
            return_val = a.mcall(method,args);
            """
     res = inline_tools.inline(code, ['a', 'method'])
     assert_equal(res, (1, "hello"))
     assert_equal(sys.getrefcount(res), 2)
示例#35
0
 def test_args_kw(self):
     a = Foo()
     code = """
            py::tuple args(2);
            args[0] = 1;
            args[1] = "hello";
            py::dict kw;
            kw["val3"] = 3;
            return_val = a.mcall("bar3",args,kw);
            """
     res = inline_tools.inline(code,['a'])
     assert_equal(res,(1,"hello",3))
     assert_equal(sys.getrefcount(res),2)
示例#36
0
    def test_args(self):
        def Foo(val1,val2):
            return (val1,val2)

        code = """
               py::tuple args(2);
               args[0] = 1;
               args[1] = "hello";
               return_val = Foo.call(args);
               """
        res = inline_tools.inline(code,['Foo'])
        assert_equal(res,(1,"hello"))
        assert_equal(sys.getrefcount(res),2)
    def test_insert(self):
        a = [1, 2, 3]

        a.insert(1, 234)
        del a[1]

        # temporary refcount fix until I understand why it incs by one.
        inline_tools.inline("a.insert(1,1234);", ['a'])
        del a[1]

        before1 = sys.getrefcount(a)

        # check overloaded insert(int ndx, int val) method
        inline_tools.inline("a.insert(1,1234);", ['a'])
        assert_(sys.getrefcount(a[1]) == 2)
        assert_(a[1] == 1234)
        del a[1]

        # check overloaded insert(int ndx, double val) method
        inline_tools.inline("a.insert(1,123.0);", ['a'])
        assert_(sys.getrefcount(a[1]) == 2)
        assert_(a[1] == 123.0)
        del a[1]

        # check overloaded insert(int ndx, char* val) method
        inline_tools.inline('a.insert(1,"bubba");', ['a'])
        assert_(sys.getrefcount(a[1]) == 2)
        assert_(a[1] == 'bubba')
        del a[1]

        # check overloaded insert(int ndx, std::string val) method
        inline_tools.inline('a.insert(1,std::string("sissy"));', ['a'])
        assert_(sys.getrefcount(a[1]) == 2)
        assert_(a[1] == 'sissy')
        del a[0]

        after1 = sys.getrefcount(a)
        assert_(after1 == before1)
示例#38
0
 def test_args_kw(self):
     def Foo(val1,val2,val3=1):
         return (val1,val2,val3)
     code = """
            py::tuple args(2);
            args[0] = 1;
            args[1] = "hello";
            py::dict kw;
            kw["val3"] = 3;
            return_val = Foo.call(args,kw);
            """
     res = inline_tools.inline(code,['Foo'])
     assert_equal(res,(1,"hello",3))
     assert_equal(sys.getrefcount(res),2)
示例#39
0
 def test_file_to_py(self):
     file_name = os.path.join(test_dir, "testfile")
     # not sure I like Py::String as default -- might move to std::sting
     # or just plain char*
     code = """
            const char* _file_name = file_name.c_str();
            FILE* file = fopen(_file_name, "w");
            return_val = file_to_py(file, _file_name, "w");
            """
     file = inline_tools.inline(code,['file_name'], compiler=self.compiler,
                                force=1)
     file.write("hello fred")
     file.close()
     file = open(file_name,'r')
     assert_(file.read() == "hello fred")
示例#40
0
 def test_call_function(self):
     func = string.find
     search_str = "hello world hello"
     sub_str = "world"
     # * Not sure about ref counts on search_str and sub_str.
     # * Is the Py::String necessary? (it works anyways...)
     code = """
            py::tuple args(2);
            args[0] = search_str;
            args[1] = sub_str;
            return_val = func.call(args);
            """
     actual = inline_tools.inline(code,['func','search_str','sub_str'],
                                  compiler=self.compiler,force=1)
     desired = func(search_str,sub_str)
     assert_(desired == actual)
示例#41
0
 def test_file_to_py(self):
     import tempfile
     file_name = tempfile.mktemp()
     # not sure I like Py::String as default -- might move to std::sting
     # or just plain char*
     code = """
            char* _file_name = (char*) file_name.c_str();
            FILE* file = fopen(_file_name,"w");
            return_val = file_to_py(file,_file_name,"w");
            """
     file = inline_tools.inline(code, ['file_name'],
                                compiler=self.compiler,
                                force=1)
     file.write("hello fred")
     file.close()
     file = open(file_name, 'r')
     assert (file.read() == "hello fred")
示例#42
0
def vq(obs, code_book):
    # make sure we're looking at arrays.
    obs = asarray(obs)
    code_book = asarray(code_book)
    # check for 2d arrays and compatible sizes.
    obs_sh = shape(obs)
    code_book_sh = shape(code_book)
    assert (len(obs_sh) == 2 and len(code_book_sh) == 2)
    assert (obs_sh[1] == code_book_sh[1])
    type = c_spec.num_to_c_types[obs.typecode()]
    # band aid for now.
    ar_type = 'PyArray_FLOAT'
    code = """
            #line 37 "vq.py"
            // Use tensor notation.
            blitz::Array<%(type)s,2> dist_sq(Ncode_book[0],Nobs[0]);
                blitz::firstIndex i;
            blitz::secondIndex j;
            blitz::thirdIndex k;
            dist_sq = sum(pow2(obs(j,k) - code_book(i,k)),k);
            // Surely there is a better way to do this...
            PyArrayObject* py_code = (PyArrayObject*) PyArray_FromDims(1,&Nobs[0],PyArray_LONG);
                blitz::Array<int,1> code((int*)(py_code->data),
                                     blitz::shape(Nobs[0]), blitz::neverDeleteData);
                code = minIndex(dist_sq(j,i),j);

                PyArrayObject* py_min_dist = (PyArrayObject*) PyArray_FromDims(1,&Nobs[0],PyArray_FLOAT);
                blitz::Array<float,1> min_dist((float*)(py_min_dist->data),
                                               blitz::shape(Nobs[0]), blitz::neverDeleteData);
                min_dist = sqrt(min(dist_sq(j,i),j));
                py::tuple results(2);
                results[0] = py_code;
                results[1] = py_min_dist;
                return_val = results;
            """ % locals()
    code, distortion = inline_tools.inline(
        code, ['obs', 'code_book'],
        type_converters=blitz_type_converters,
        compiler='gcc',
        verbose=1)
    return code, distortion
示例#43
0
def c_int_search(seq, t, chk=1):
    # do partial type checking in Python.
    # checking that list items are ints should happen in py_to_scalar<int>
    # if chk:
    #    assert(type(t) is int)
    #    assert(type(seq) is list)
    code = """
           #line 33 "binary_search.py"
           if (!PyList_Check(py_seq))
               py::fail(PyExc_TypeError, "seq must be a list");
           if (!PyInt_Check(py_t))
               py::fail(PyExc_TypeError, "t must be an integer");
           int val, m, min = 0;
           int max = seq.len()- 1;
           for(;;)
           {
               if (max < min )
               {
                   return_val = -1;
                   break;
               }
               m = (min + max) / 2;
               val = py_to_int(PyList_GET_ITEM(py_seq,m),"val");
               if (val < t)
                   min = m + 1;
               else if (val > t)
                   max = m - 1;
               else
               {
                   return_val = m;
                   break;
               }
           }
           """
    # return inline_tools.inline(code,['seq','t'],compiler='msvc')
    return inline_tools.inline(code, ['seq', 't'], verbose=2)
示例#44
0
 def test_set_string1(self):
     a = UserList([1,2,3])
     inline_tools.inline('a[1] = std::string("sissy");',['a'])
     assert_equal(sys.getrefcount(a[1]),2)
     assert_equal(a[1],'sissy')
示例#45
0
 def test_unsigned_long(self):
     a = 1
     res = inline_tools.inline('return_val = (a == (unsigned long)1);',['a'])
     assert_equal(res,(a == 1))
示例#46
0
 def test_double(self):
     a = 1
     res = inline_tools.inline('return_val = (a == 1.0);',['a'])
     assert_equal(res,(a == 1.0))
示例#47
0
 def test_char(self):
     a = "hello"
     res = inline_tools.inline('return_val = (a == "hello");',['a'])
     assert_equal(res,(a == "hello"))
示例#48
0
 def test_noargs(self):
     def Foo():
         return (1,2,3)
     res = inline_tools.inline('return_val = Foo.call();',['Foo'])
     assert_equal(res,(1,2,3))
     assert_equal(sys.getrefcount(res),3)  # should be 2?
示例#49
0
def vq2(obs, code_book):
    """ doesn't use blitz (except in conversion)
        ALSO DOES NOT HANDLE STRIDED ARRAYS CORRECTLY
    """
    # make sure we're looking at arrays.
    obs = asarray(obs)
    code_book = asarray(code_book)
    # check for 2d arrays and compatible sizes.
    obs_sh = shape(obs)
    code_book_sh = shape(code_book)
    assert (len(obs_sh) == 2 and len(code_book_sh) == 2)
    assert (obs_sh[1] == code_book_sh[1])
    assert (obs.typecode() == code_book.typecode())
    type = c_spec.num_to_c_types[obs.typecode()]
    # band aid for now.
    ar_type = 'PyArray_FLOAT'
    code = """
            #line 83 "vq.py"
            // THIS DOES NOT HANDLE STRIDED ARRAYS CORRECTLY
            // Surely there is a better way to do this...
            PyArrayObject* py_code = (PyArrayObject*) PyArray_FromDims(1,&Nobs[0],PyArray_LONG);
                PyArrayObject* py_min_dist = (PyArrayObject*) PyArray_FromDims(1,&Nobs[0],PyArray_FLOAT);

            int* raw_code = (int*)(py_code->data);
            float* raw_min_dist = (float*)(py_min_dist->data);
            %(type)s* raw_obs = obs.data();
            %(type)s* raw_code_book = code_book.data();
            %(type)s* this_obs = NULL;
            %(type)s* this_code = NULL;
            int Nfeatures = Nobs[1];
            float diff,dist;
            for(int i=0; i < Nobs[0]; i++)
            {
                this_obs = &raw_obs[i*Nfeatures];
                raw_min_dist[i] = (%(type)s)10000000.; // big number
                for(int j=0; j < Ncode_book[0]; j++)
                {
                    this_code = &raw_code_book[j*Nfeatures];
                    dist = 0;
                    for(int k=0; k < Nfeatures; k++)
                    {
                        diff = this_obs[k] - this_code[k];
                        dist +=  diff*diff;
                    }
                    dist = dist;
                    if (dist < raw_min_dist[i])
                    {
                        raw_code[i] = j;
                        raw_min_dist[i] = dist;
                    }
                }
                raw_min_dist[i] = sqrt(raw_min_dist[i]);
                }
                py::tuple results(2);
                results[0] = py_code;
                results[1] = py_min_dist;
                return_val = results;
            """ % locals()
    code, distortion = inline_tools.inline(
        code, ['obs', 'code_book'],
        type_converters=blitz_type_converters,
        compiler='gcc',
        verbose=1)
    return code, distortion
示例#50
0
 def test_convert_to_string(self):
     s = 'hello'
     inline_tools.inline("", ['s'], compiler=self.compiler, force=1)
示例#51
0
 def test_false(self):
     a = None
     res = inline_tools.inline('return_val = a.is_true();',['a'])
     assert_equal(res,0)
示例#52
0
 def test_convert_to_dict(self):
     d = {}
     inline_tools.inline("", ['d'], compiler=self.compiler, force=1)
示例#53
0
 def test_inline(self):
     a = numpy.complex128(1 + 1j)
     result = inline_tools.inline("return_val=1.0/a;", ['a'])
     assert_(result == .5 - .5j)
示例#54
0
 def test_set_string2(self):
     a = UserList([1,2,3])
     inline_tools.inline('a[1] = std::complex<double>(1,1);',['a'])
     assert_equal(sys.getrefcount(a[1]),2)
     assert_equal(a[1],1+1j)
示例#55
0
 def test_set_char(self):
     a = UserDict()
     inline_tools.inline('a["hello"] = 123.0;',['a'])
     assert_equal(sys.getrefcount(a["hello"]),2)
     assert_equal(a["hello"],123.0)
示例#56
0
 def test_set_from_member(self):
     a = UserDict()
     a['first'] = 1
     a['second'] = 2
     inline_tools.inline('a["first"] = a["second"];',['a'])
     assert_equal(a['first'],a['second'])
示例#57
0
 def test_set_char(self):
     a = UserList([1,2,3])
     inline_tools.inline('a[1] = "bubba";',['a'])
     assert_equal(sys.getrefcount(a[1]),2)
     assert_equal(a[1],'bubba')
示例#58
0
 def test_set_double(self):
     a = UserList([1,2,3])
     inline_tools.inline("a[1] = 123.0;",['a'])
     assert_equal(sys.getrefcount(a[1]),2)
     assert_equal(a[1],123.0)
示例#59
0
 def test_convert_to_list(self):
     l = []
     inline_tools.inline("", ['l'], compiler=self.compiler, force=1)
示例#60
0
 def test_convert_to_tuple(self):
     t = ()
     inline_tools.inline("", ['t'], compiler=self.compiler, force=1)