code
stringlengths
1
1.49M
vector
listlengths
0
7.38k
snippet
listlengths
0
7.38k
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from ctypes import * def setProcName(name): """Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases.""" # Call the process control function... libc = cdll.LoadLibrary('libc.so.6') libc.prctl(15, c_char_p(name), 0, 0, 0) # Update argv... charPP = POINTER(POINTER(c_char)) argv = charPP.in_dll(libc,'_dl_argv') size = libc.strlen(argv[0]) libc.strncpy(argv[0],c_char_p(name),size) if __name__=='__main__': # Quick test that it works... import os ps1 = 'ps' ps2 = 'ps -f' os.system(ps1) os.system(ps2) setProcName('wibble_wobble') os.system(ps1) os.system(ps2)
[ [ 1, 0, 0.3636, 0.0227, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 2, 0, 0.5682, 0.25, 0, 0.66, 0.5, 903, 0, 1, 0, 0, 0, 0, 9 ], [ 8, 1, 0.4773, 0.0227, 1, 0.68, ...
[ "from ctypes import *", "def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import multiprocessing as mp import multiprocessing.synchronize # To make sure we have all the functionality. import types import marshal import unittest def repeat(x): """A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant.""" while True: yield x def run_code(code,args): """Internal use function that does the work in each process.""" code = marshal.loads(code) func = types.FunctionType(code, globals(), '_') return func(*args) def mp_map(func, *iters, **keywords): """A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity.""" if 'pool' in keywords: pool = keywords['pool'] else: pool = mp.Pool() code = marshal.dumps(func.func_code) jobs = [] for args in zip(*iters): jobs.append(pool.apply_async(run_code,(code,args))) for i in xrange(len(jobs)): jobs[i] = jobs[i].get() return jobs class TestMpMap(unittest.TestCase): def test_simple1(self): data = ['a','b','c','d'] def noop(data): return data data_noop = mp_map(noop, data) self.assertEqual(data, data_noop) def test_simple2(self): data = [x for x in xrange(1000)] data_double = mp_map(lambda a: a*2, data) self.assertEqual(map(lambda a: a*2,data), data_double) def test_gen(self): def gen(): for i in xrange(100): yield i data_double = mp_map(lambda a: a*2, gen()) self.assertEqual(map(lambda a: a*2,gen()), data_double) def test_repeat(self): def mult(a,b): return a*b data = [x for x in xrange(50,5000,5)] data_triple = mp_map(mult, data, repeat(3)) self.assertEqual(map(lambda a: a*3,data),data_triple) def test_none(self): data = [] data_sqr = mp_map(lambda x: x*x, data) self.assertEqual([],data_sqr) if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.1456, 0.0097, 0, 0.66, 0, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 1, 0, 0.1553, 0.0097, 0, 0.66, 0.1111, 99, 0, 1, 0, 0, 99, 0, 0 ], [ 1, 0, 0.1748, 0.0097, 0, 0....
[ "import multiprocessing as mp", "import multiprocessing.synchronize # To make sure we have all the functionality.", "import types", "import marshal", "import unittest", "def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Defines helper functions for accessing numpy arrays... numpy_util_code = start_cpp() + """ #ifndef NUMPY_UTIL_CODE #define NUMPY_UTIL_CODE float & Float1D(PyArrayObject * arr, int index = 0) { return *(float*)(arr->data + index*arr->strides[0]); } float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } unsigned char & Byte1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index*arr->strides[0]); } unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } int & Int1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index*arr->strides[0]); } int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } #endif """
[ [ 1, 0, 0.1923, 0.0128, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.6282, 0.7564, 0, 0.66, 1, 799, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}" ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import cvarray import mp_map import prog_bar import numpy_help_cpp import python_obj_cpp import matrix_cpp import gamma_cpp import setProcName import start_cpp import make import doc_gen # Setup... doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.') doc.addFile('readme.txt', 'Overview') # Variables... doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.') doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.') doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++') doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++') # Functions... doc.addFunction(make.make_mod) doc.addFunction(cvarray.cv2array) doc.addFunction(cvarray.array2cv) doc.addFunction(mp_map.repeat) doc.addFunction(mp_map.mp_map) doc.addFunction(setProcName.setProcName) doc.addFunction(start_cpp.start_cpp) doc.addFunction(make.make_mod) # Classes... doc.addClass(prog_bar.ProgBar) doc.addClass(doc_gen.DocGen)
[ [ 1, 0, 0.2857, 0.0179, 0, 0.66, 0, 192, 0, 1, 0, 0, 192, 0, 0 ], [ 1, 0, 0.3036, 0.0179, 0, 0.66, 0.0385, 905, 0, 1, 0, 0, 905, 0, 0 ], [ 1, 0, 0.3214, 0.0179, 0, ...
[ "import cvarray", "import mp_map", "import prog_bar", "import numpy_help_cpp", "import python_obj_cpp", "import matrix_cpp", "import gamma_cpp", "import setProcName", "import start_cpp", "import make", "import doc_gen", "doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc...
# Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest import random import math from scipy.special import gammaln, psi, polygamma from scipy import weave from utils.start_cpp import start_cpp # Provides various gamma-related functions... gamma_code = start_cpp() + """ #ifndef GAMMA_CODE #define GAMMA_CODE #include <cmath> // Returns the natural logarithm of the Gamma function... // (Uses Lanczos's approximation.) double lnGamma(double z) { static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7}; if (z<0.5) { // Use reflection formula, as approximation doesn't work down here... return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z); } else { double x = coeff[0]; for (int i=1;i<9;i++) x += coeff[i]/(z+i-1); double t = z + 6.5; return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x); } } // Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values... double digamma(double z) { static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point. double ret = 0.0; while (z<highVal) { ret -= 1.0/z; z += 1.0; } double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz4 = iz2*iz2; double iz6 = iz4*iz2; ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0; return ret; } // Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically... double trigamma(double z) { static const double highVal = 8.0; double ret = 0.0; while (z<highVal) { ret += 1.0/(z*z); z += 1.0; } z -= 1.0; double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz3 = iz1*iz2; double iz5 = iz3*iz2; double iz7 = iz5*iz2; double iz9 = iz7*iz2; ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0; return ret; } #endif """ def lnGamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function""" code = start_cpp(gamma_code) + """ return_val = lnGamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def digamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function""" code = start_cpp(gamma_code) + """ return_val = digamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def trigamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function""" code = start_cpp(gamma_code) + """ return_val = trigamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) class TestFuncs(unittest.TestCase): """Test code for the assorted gamma-related functions.""" def test_compile(self): code = start_cpp(gamma_code) + """ """ weave.inline(code, support_code=gamma_code) def test_error_lngamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = lnGamma(z) good = gammaln(z) assert(math.fabs(own-good)<1e-12) def test_error_digamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = digamma(z) good = psi(z) assert(math.fabs(own-good)<1e-9) def test_error_trigamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = trigamma(z) good = polygamma(1,z) assert(math.fabs(own-good)<1e-9) # If this file is run do the unit tests... if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.0818, 0.0063, 0, 0.66, 0, 88, 0, 1, 0, 0, 88, 0, 0 ], [ 1, 0, 0.0881, 0.0063, 0, 0.66, 0.0909, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0943, 0.0063, 0, 0....
[ "import unittest", "import random", "import math", "from scipy.special import gammaln, psi, polygamma", "from scipy import weave", "from utils.start_cpp import start_cpp", "gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import inspect import hashlib def start_cpp(hash_str = None): """This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>""" frame = inspect.currentframe().f_back info = inspect.getframeinfo(frame) if hash_str==None: return '#line %i "%s"\n'%(info[1],info[0]) else: h = hashlib.md5() h.update(hash_str) hash_val = h.hexdigest() return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
[ [ 1, 0, 0.5, 0.0333, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.5333, 0.0333, 0, 0.66, 0.5, 154, 0, 1, 0, 0, 154, 0, 0 ], [ 2, 0, 0.8333, 0.3667, 0, 0.66, ...
[ "import inspect", "import hashlib", "def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os.path import tempfile import shutil from distutils.core import setup, Extension import distutils.ccompiler import distutils.dep_util try: __default_compiler = distutils.ccompiler.new_compiler() except: __default_compiler = None def make_mod(name, base, source, openCL = False): """Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place.""" if __default_compiler==None: raise Exception('No compiler!') # Work out the various file names - check if we actually need to do anything... if not isinstance(source, list): source = [source] source_path = map(lambda s: os.path.join(base, s), source) library_path = os.path.join(base, __default_compiler.shared_object_filename(name)) if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)): try: print 'b' # Backup the argv variable and create a temporary directory to do all work in... old_argv = sys.argv[:] temp_dir = tempfile.mkdtemp() # Prepare the extension... sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir] comp_path = filter(lambda s: not s.endswith('.h'), source_path) depends = filter(lambda s: s.endswith('.h'), source_path) if openCL: ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends) else: ext = Extension(name, comp_path, depends=depends) # Compile... setup(name=name, version='1.0.0', ext_modules=[ext]) finally: # Cleanup the argv variable and the temporary directory... sys.argv = old_argv shutil.rmtree(temp_dir, True)
[ [ 1, 0, 0.2031, 0.0156, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2188, 0.0156, 0, 0.66, 0.125, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.2344, 0.0156, 0, 0.6...
[ "import sys", "import os.path", "import tempfile", "import shutil", "from distutils.core import setup, Extension", "import distutils.ccompiler", "import distutils.dep_util", "try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None", " __default_compiler...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pydoc import inspect class DocGen: """A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.""" def __init__(self, name, title = None, summary = None): """name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title.""" if title==None: title = name if summary==None: summary = title self.doc = pydoc.HTMLDoc() self.html = open('%s.html'%name,'w') self.html.write('<html>\n') self.html.write('<head>\n') self.html.write('<title>%s</title>\n'%title) self.html.write('</head>\n') self.html.write('<body>\n') self.html_variables = '' self.html_functions = '' self.html_classes = '' self.wiki = open('%s.wiki'%name,'w') self.wiki.write('#summary %s\n\n'%summary) self.wiki.write('= %s= \n\n'%title) self.wiki_variables = '' self.wiki_functions = '' self.wiki_classes = '' def __del__(self): if self.html_variables!='': self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables)) if self.html_functions!='': self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions)) if self.html_classes!='': self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes)) self.html.write('</body>\n') self.html.write('</html>\n') self.html.close() if self.wiki_variables!='': self.wiki.write('= Variables =\n\n') self.wiki.write(self.wiki_variables) self.wiki.write('\n') if self.wiki_functions!='': self.wiki.write('= Functions =\n\n') self.wiki.write(self.wiki_functions) self.wiki.write('\n') if self.wiki_classes!='': self.wiki.write('= Classes =\n\n') self.wiki.write(self.wiki_classes) self.wiki.write('\n') self.wiki.close() def addFile(self, fn, title, fls = True): """Given a filename and section title adds the contents of said file to the output. Various flags influence how this works.""" html = [] wiki = [] for i, line in enumerate(open(fn,'r').readlines()): hl = line.replace('\n', '') if i==0 and fls: hl = '<strong>' + hl + '</strong>' for ext in ['py','txt']: if '.%s - '%ext in hl: s = hl.split('.%s - '%ext, 1) hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1] html.append(hl) wl = line.strip() if i==0 and fls: wl = '*%s*'%wl for ext in ['py','txt']: if '.%s - '%ext in wl: s = wl.split('.%s - '%ext, 1) wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n' wiki.append(wl) self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html))) self.wiki.write('== %s ==\n'%title) self.wiki.write('\n'.join(wiki)) self.wiki.write('----\n\n') def addVariable(self, var, desc): """Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc..""" self.html_variables += '<strong>%s</strong><br/>'%var self.html_variables += '%s<br/><br/>\n'%desc self.wiki_variables += '*`%s`*\n'%var self.wiki_variables += ' %s\n\n'%desc def addFunction(self, func): """Adds a function to the documentation. You provide the actual function instance.""" self.html_functions += self.doc.docroutine(func).replace('&nbsp;',' ') self.html_functions += '\n' name = func.__name__ args, varargs, keywords, defaults = inspect.getargspec(func) doc = inspect.getdoc(func) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_functions += ' %s\n\n'%doc def addClass(self, cls): """Adds a class to the documentation. You provide the actual class object.""" self.html_classes += self.doc.docclass(cls).replace('&nbsp;',' ') self.html_classes += '\n' name = cls.__name__ parents = filter(lambda a: a!=cls, inspect.getmro(cls)) doc = inspect.getdoc(cls) par_str = '' if len(parents)!=0: par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents)) self.wiki_classes += '== %s(%s) ==\n'%(name, par_str) self.wiki_classes += ' %s\n\n'%doc methods = inspect.getmembers(cls, inspect.ismethod) def method_key(pair): if pair[0]=='__init__': return '___' else: return pair[0] methods.sort(key=method_key) for name, method in methods: if not name.startswith('_%s'%cls.__name__): args, varargs, keywords, defaults = inspect.getargspec(method) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords def fetch_doc(cls, name): try: method = getattr(cls, name) if method.__doc__!=None: return inspect.getdoc(method) except: pass for parent in filter(lambda a: a!=cls, inspect.getmro(cls)): ret = fetch_doc(parent, name) if ret!=None: return ret return None doc = fetch_doc(cls, name) self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_classes += ' %s\n\n'%doc variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float)) for name, var in variables: if not name.startswith('__'): self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
[ [ 1, 0, 0.0634, 0.0049, 0, 0.66, 0, 291, 0, 1, 0, 0, 291, 0, 0 ], [ 1, 0, 0.0683, 0.0049, 0, 0.66, 0.5, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 3, 0, 0.5439, 0.9171, 0, 0.6...
[ "import pydoc", "import inspect", "class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from ctypes import * def setProcName(name): """Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases.""" # Call the process control function... libc = cdll.LoadLibrary('libc.so.6') libc.prctl(15, c_char_p(name), 0, 0, 0) # Update argv... charPP = POINTER(POINTER(c_char)) argv = charPP.in_dll(libc,'_dl_argv') size = libc.strlen(argv[0]) libc.strncpy(argv[0],c_char_p(name),size) if __name__=='__main__': # Quick test that it works... import os ps1 = 'ps' ps2 = 'ps -f' os.system(ps1) os.system(ps2) setProcName('wibble_wobble') os.system(ps1) os.system(ps2)
[ [ 1, 0, 0.3636, 0.0227, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 2, 0, 0.5682, 0.25, 0, 0.66, 0.5, 903, 0, 1, 0, 0, 0, 0, 9 ], [ 8, 1, 0.4773, 0.0227, 1, 0.68, ...
[ "from ctypes import *", "def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import multiprocessing as mp import multiprocessing.synchronize # To make sure we have all the functionality. import types import marshal import unittest def repeat(x): """A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant.""" while True: yield x def run_code(code,args): """Internal use function that does the work in each process.""" code = marshal.loads(code) func = types.FunctionType(code, globals(), '_') return func(*args) def mp_map(func, *iters, **keywords): """A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity.""" if 'pool' in keywords: pool = keywords['pool'] else: pool = mp.Pool() code = marshal.dumps(func.func_code) jobs = [] for args in zip(*iters): jobs.append(pool.apply_async(run_code,(code,args))) for i in xrange(len(jobs)): jobs[i] = jobs[i].get() return jobs class TestMpMap(unittest.TestCase): def test_simple1(self): data = ['a','b','c','d'] def noop(data): return data data_noop = mp_map(noop, data) self.assertEqual(data, data_noop) def test_simple2(self): data = [x for x in xrange(1000)] data_double = mp_map(lambda a: a*2, data) self.assertEqual(map(lambda a: a*2,data), data_double) def test_gen(self): def gen(): for i in xrange(100): yield i data_double = mp_map(lambda a: a*2, gen()) self.assertEqual(map(lambda a: a*2,gen()), data_double) def test_repeat(self): def mult(a,b): return a*b data = [x for x in xrange(50,5000,5)] data_triple = mp_map(mult, data, repeat(3)) self.assertEqual(map(lambda a: a*3,data),data_triple) def test_none(self): data = [] data_sqr = mp_map(lambda x: x*x, data) self.assertEqual([],data_sqr) if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.1456, 0.0097, 0, 0.66, 0, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 1, 0, 0.1553, 0.0097, 0, 0.66, 0.1111, 99, 0, 1, 0, 0, 99, 0, 0 ], [ 1, 0, 0.1748, 0.0097, 0, 0....
[ "import multiprocessing as mp", "import multiprocessing.synchronize # To make sure we have all the functionality.", "import types", "import marshal", "import unittest", "def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Defines helper functions for accessing numpy arrays... numpy_util_code = start_cpp() + """ #ifndef NUMPY_UTIL_CODE #define NUMPY_UTIL_CODE float & Float1D(PyArrayObject * arr, int index = 0) { return *(float*)(arr->data + index*arr->strides[0]); } float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } unsigned char & Byte1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index*arr->strides[0]); } unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } int & Int1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index*arr->strides[0]); } int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } #endif """
[ [ 1, 0, 0.1923, 0.0128, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.6282, 0.7564, 0, 0.66, 1, 799, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}" ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import cvarray import mp_map import prog_bar import numpy_help_cpp import python_obj_cpp import matrix_cpp import gamma_cpp import setProcName import start_cpp import make import doc_gen # Setup... doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.') doc.addFile('readme.txt', 'Overview') # Variables... doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.') doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.') doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++') doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++') # Functions... doc.addFunction(make.make_mod) doc.addFunction(cvarray.cv2array) doc.addFunction(cvarray.array2cv) doc.addFunction(mp_map.repeat) doc.addFunction(mp_map.mp_map) doc.addFunction(setProcName.setProcName) doc.addFunction(start_cpp.start_cpp) doc.addFunction(make.make_mod) # Classes... doc.addClass(prog_bar.ProgBar) doc.addClass(doc_gen.DocGen)
[ [ 1, 0, 0.2857, 0.0179, 0, 0.66, 0, 192, 0, 1, 0, 0, 192, 0, 0 ], [ 1, 0, 0.3036, 0.0179, 0, 0.66, 0.0385, 905, 0, 1, 0, 0, 905, 0, 0 ], [ 1, 0, 0.3214, 0.0179, 0, ...
[ "import cvarray", "import mp_map", "import prog_bar", "import numpy_help_cpp", "import python_obj_cpp", "import matrix_cpp", "import gamma_cpp", "import setProcName", "import start_cpp", "import make", "import doc_gen", "doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc...
# Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest import random import math from scipy.special import gammaln, psi, polygamma from scipy import weave from utils.start_cpp import start_cpp # Provides various gamma-related functions... gamma_code = start_cpp() + """ #ifndef GAMMA_CODE #define GAMMA_CODE #include <cmath> // Returns the natural logarithm of the Gamma function... // (Uses Lanczos's approximation.) double lnGamma(double z) { static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7}; if (z<0.5) { // Use reflection formula, as approximation doesn't work down here... return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z); } else { double x = coeff[0]; for (int i=1;i<9;i++) x += coeff[i]/(z+i-1); double t = z + 6.5; return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x); } } // Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values... double digamma(double z) { static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point. double ret = 0.0; while (z<highVal) { ret -= 1.0/z; z += 1.0; } double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz4 = iz2*iz2; double iz6 = iz4*iz2; ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0; return ret; } // Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically... double trigamma(double z) { static const double highVal = 8.0; double ret = 0.0; while (z<highVal) { ret += 1.0/(z*z); z += 1.0; } z -= 1.0; double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz3 = iz1*iz2; double iz5 = iz3*iz2; double iz7 = iz5*iz2; double iz9 = iz7*iz2; ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0; return ret; } #endif """ def lnGamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function""" code = start_cpp(gamma_code) + """ return_val = lnGamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def digamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function""" code = start_cpp(gamma_code) + """ return_val = digamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def trigamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function""" code = start_cpp(gamma_code) + """ return_val = trigamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) class TestFuncs(unittest.TestCase): """Test code for the assorted gamma-related functions.""" def test_compile(self): code = start_cpp(gamma_code) + """ """ weave.inline(code, support_code=gamma_code) def test_error_lngamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = lnGamma(z) good = gammaln(z) assert(math.fabs(own-good)<1e-12) def test_error_digamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = digamma(z) good = psi(z) assert(math.fabs(own-good)<1e-9) def test_error_trigamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = trigamma(z) good = polygamma(1,z) assert(math.fabs(own-good)<1e-9) # If this file is run do the unit tests... if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.0818, 0.0063, 0, 0.66, 0, 88, 0, 1, 0, 0, 88, 0, 0 ], [ 1, 0, 0.0881, 0.0063, 0, 0.66, 0.0909, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0943, 0.0063, 0, 0....
[ "import unittest", "import random", "import math", "from scipy.special import gammaln, psi, polygamma", "from scipy import weave", "from utils.start_cpp import start_cpp", "gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import inspect import hashlib def start_cpp(hash_str = None): """This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>""" frame = inspect.currentframe().f_back info = inspect.getframeinfo(frame) if hash_str==None: return '#line %i "%s"\n'%(info[1],info[0]) else: h = hashlib.md5() h.update(hash_str) hash_val = h.hexdigest() return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
[ [ 1, 0, 0.5, 0.0333, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.5333, 0.0333, 0, 0.66, 0.5, 154, 0, 1, 0, 0, 154, 0, 0 ], [ 2, 0, 0.8333, 0.3667, 0, 0.66, ...
[ "import inspect", "import hashlib", "def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os.path import tempfile import shutil from distutils.core import setup, Extension import distutils.ccompiler import distutils.dep_util try: __default_compiler = distutils.ccompiler.new_compiler() except: __default_compiler = None def make_mod(name, base, source, openCL = False): """Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place.""" if __default_compiler==None: raise Exception('No compiler!') # Work out the various file names - check if we actually need to do anything... if not isinstance(source, list): source = [source] source_path = map(lambda s: os.path.join(base, s), source) library_path = os.path.join(base, __default_compiler.shared_object_filename(name)) if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)): try: print 'b' # Backup the argv variable and create a temporary directory to do all work in... old_argv = sys.argv[:] temp_dir = tempfile.mkdtemp() # Prepare the extension... sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir] comp_path = filter(lambda s: not s.endswith('.h'), source_path) depends = filter(lambda s: s.endswith('.h'), source_path) if openCL: ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends) else: ext = Extension(name, comp_path, depends=depends) # Compile... setup(name=name, version='1.0.0', ext_modules=[ext]) finally: # Cleanup the argv variable and the temporary directory... sys.argv = old_argv shutil.rmtree(temp_dir, True)
[ [ 1, 0, 0.2031, 0.0156, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2188, 0.0156, 0, 0.66, 0.125, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.2344, 0.0156, 0, 0.6...
[ "import sys", "import os.path", "import tempfile", "import shutil", "from distutils.core import setup, Extension", "import distutils.ccompiler", "import distutils.dep_util", "try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None", " __default_compiler...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pydoc import inspect class DocGen: """A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.""" def __init__(self, name, title = None, summary = None): """name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title.""" if title==None: title = name if summary==None: summary = title self.doc = pydoc.HTMLDoc() self.html = open('%s.html'%name,'w') self.html.write('<html>\n') self.html.write('<head>\n') self.html.write('<title>%s</title>\n'%title) self.html.write('</head>\n') self.html.write('<body>\n') self.html_variables = '' self.html_functions = '' self.html_classes = '' self.wiki = open('%s.wiki'%name,'w') self.wiki.write('#summary %s\n\n'%summary) self.wiki.write('= %s= \n\n'%title) self.wiki_variables = '' self.wiki_functions = '' self.wiki_classes = '' def __del__(self): if self.html_variables!='': self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables)) if self.html_functions!='': self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions)) if self.html_classes!='': self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes)) self.html.write('</body>\n') self.html.write('</html>\n') self.html.close() if self.wiki_variables!='': self.wiki.write('= Variables =\n\n') self.wiki.write(self.wiki_variables) self.wiki.write('\n') if self.wiki_functions!='': self.wiki.write('= Functions =\n\n') self.wiki.write(self.wiki_functions) self.wiki.write('\n') if self.wiki_classes!='': self.wiki.write('= Classes =\n\n') self.wiki.write(self.wiki_classes) self.wiki.write('\n') self.wiki.close() def addFile(self, fn, title, fls = True): """Given a filename and section title adds the contents of said file to the output. Various flags influence how this works.""" html = [] wiki = [] for i, line in enumerate(open(fn,'r').readlines()): hl = line.replace('\n', '') if i==0 and fls: hl = '<strong>' + hl + '</strong>' for ext in ['py','txt']: if '.%s - '%ext in hl: s = hl.split('.%s - '%ext, 1) hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1] html.append(hl) wl = line.strip() if i==0 and fls: wl = '*%s*'%wl for ext in ['py','txt']: if '.%s - '%ext in wl: s = wl.split('.%s - '%ext, 1) wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n' wiki.append(wl) self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html))) self.wiki.write('== %s ==\n'%title) self.wiki.write('\n'.join(wiki)) self.wiki.write('----\n\n') def addVariable(self, var, desc): """Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc..""" self.html_variables += '<strong>%s</strong><br/>'%var self.html_variables += '%s<br/><br/>\n'%desc self.wiki_variables += '*`%s`*\n'%var self.wiki_variables += ' %s\n\n'%desc def addFunction(self, func): """Adds a function to the documentation. You provide the actual function instance.""" self.html_functions += self.doc.docroutine(func).replace('&nbsp;',' ') self.html_functions += '\n' name = func.__name__ args, varargs, keywords, defaults = inspect.getargspec(func) doc = inspect.getdoc(func) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_functions += ' %s\n\n'%doc def addClass(self, cls): """Adds a class to the documentation. You provide the actual class object.""" self.html_classes += self.doc.docclass(cls).replace('&nbsp;',' ') self.html_classes += '\n' name = cls.__name__ parents = filter(lambda a: a!=cls, inspect.getmro(cls)) doc = inspect.getdoc(cls) par_str = '' if len(parents)!=0: par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents)) self.wiki_classes += '== %s(%s) ==\n'%(name, par_str) self.wiki_classes += ' %s\n\n'%doc methods = inspect.getmembers(cls, inspect.ismethod) def method_key(pair): if pair[0]=='__init__': return '___' else: return pair[0] methods.sort(key=method_key) for name, method in methods: if not name.startswith('_%s'%cls.__name__): args, varargs, keywords, defaults = inspect.getargspec(method) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords def fetch_doc(cls, name): try: method = getattr(cls, name) if method.__doc__!=None: return inspect.getdoc(method) except: pass for parent in filter(lambda a: a!=cls, inspect.getmro(cls)): ret = fetch_doc(parent, name) if ret!=None: return ret return None doc = fetch_doc(cls, name) self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_classes += ' %s\n\n'%doc variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float)) for name, var in variables: if not name.startswith('__'): self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
[ [ 1, 0, 0.0634, 0.0049, 0, 0.66, 0, 291, 0, 1, 0, 0, 291, 0, 0 ], [ 1, 0, 0.0683, 0.0049, 0, 0.66, 0.5, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 3, 0, 0.5439, 0.9171, 0, 0.6...
[ "import pydoc", "import inspect", "class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from ctypes import * def setProcName(name): """Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases.""" # Call the process control function... libc = cdll.LoadLibrary('libc.so.6') libc.prctl(15, c_char_p(name), 0, 0, 0) # Update argv... charPP = POINTER(POINTER(c_char)) argv = charPP.in_dll(libc,'_dl_argv') size = libc.strlen(argv[0]) libc.strncpy(argv[0],c_char_p(name),size) if __name__=='__main__': # Quick test that it works... import os ps1 = 'ps' ps2 = 'ps -f' os.system(ps1) os.system(ps2) setProcName('wibble_wobble') os.system(ps1) os.system(ps2)
[ [ 1, 0, 0.3636, 0.0227, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 2, 0, 0.5682, 0.25, 0, 0.66, 0.5, 903, 0, 1, 0, 0, 0, 0, 9 ], [ 8, 1, 0.4773, 0.0227, 1, 0.09, ...
[ "from ctypes import *", "def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import multiprocessing as mp import multiprocessing.synchronize # To make sure we have all the functionality. import types import marshal import unittest def repeat(x): """A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant.""" while True: yield x def run_code(code,args): """Internal use function that does the work in each process.""" code = marshal.loads(code) func = types.FunctionType(code, globals(), '_') return func(*args) def mp_map(func, *iters, **keywords): """A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity.""" if 'pool' in keywords: pool = keywords['pool'] else: pool = mp.Pool() code = marshal.dumps(func.func_code) jobs = [] for args in zip(*iters): jobs.append(pool.apply_async(run_code,(code,args))) for i in xrange(len(jobs)): jobs[i] = jobs[i].get() return jobs class TestMpMap(unittest.TestCase): def test_simple1(self): data = ['a','b','c','d'] def noop(data): return data data_noop = mp_map(noop, data) self.assertEqual(data, data_noop) def test_simple2(self): data = [x for x in xrange(1000)] data_double = mp_map(lambda a: a*2, data) self.assertEqual(map(lambda a: a*2,data), data_double) def test_gen(self): def gen(): for i in xrange(100): yield i data_double = mp_map(lambda a: a*2, gen()) self.assertEqual(map(lambda a: a*2,gen()), data_double) def test_repeat(self): def mult(a,b): return a*b data = [x for x in xrange(50,5000,5)] data_triple = mp_map(mult, data, repeat(3)) self.assertEqual(map(lambda a: a*3,data),data_triple) def test_none(self): data = [] data_sqr = mp_map(lambda x: x*x, data) self.assertEqual([],data_sqr) if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.1456, 0.0097, 0, 0.66, 0, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 1, 0, 0.1553, 0.0097, 0, 0.66, 0.1111, 99, 0, 1, 0, 0, 99, 0, 0 ], [ 1, 0, 0.1748, 0.0097, 0, 0....
[ "import multiprocessing as mp", "import multiprocessing.synchronize # To make sure we have all the functionality.", "import types", "import marshal", "import unittest", "def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Defines helper functions for accessing numpy arrays... numpy_util_code = start_cpp() + """ #ifndef NUMPY_UTIL_CODE #define NUMPY_UTIL_CODE float & Float1D(PyArrayObject * arr, int index = 0) { return *(float*)(arr->data + index*arr->strides[0]); } float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } unsigned char & Byte1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index*arr->strides[0]); } unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } int & Int1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index*arr->strides[0]); } int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } #endif """
[ [ 1, 0, 0.1923, 0.0128, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.6282, 0.7564, 0, 0.66, 1, 799, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}" ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import cvarray import mp_map import prog_bar import numpy_help_cpp import python_obj_cpp import matrix_cpp import gamma_cpp import setProcName import start_cpp import make import doc_gen # Setup... doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.') doc.addFile('readme.txt', 'Overview') # Variables... doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.') doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.') doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++') doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++') # Functions... doc.addFunction(make.make_mod) doc.addFunction(cvarray.cv2array) doc.addFunction(cvarray.array2cv) doc.addFunction(mp_map.repeat) doc.addFunction(mp_map.mp_map) doc.addFunction(setProcName.setProcName) doc.addFunction(start_cpp.start_cpp) doc.addFunction(make.make_mod) # Classes... doc.addClass(prog_bar.ProgBar) doc.addClass(doc_gen.DocGen)
[ [ 1, 0, 0.2857, 0.0179, 0, 0.66, 0, 192, 0, 1, 0, 0, 192, 0, 0 ], [ 1, 0, 0.3036, 0.0179, 0, 0.66, 0.0385, 905, 0, 1, 0, 0, 905, 0, 0 ], [ 1, 0, 0.3214, 0.0179, 0, ...
[ "import cvarray", "import mp_map", "import prog_bar", "import numpy_help_cpp", "import python_obj_cpp", "import matrix_cpp", "import gamma_cpp", "import setProcName", "import start_cpp", "import make", "import doc_gen", "doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc...
# Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest import random import math from scipy.special import gammaln, psi, polygamma from scipy import weave from utils.start_cpp import start_cpp # Provides various gamma-related functions... gamma_code = start_cpp() + """ #ifndef GAMMA_CODE #define GAMMA_CODE #include <cmath> // Returns the natural logarithm of the Gamma function... // (Uses Lanczos's approximation.) double lnGamma(double z) { static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7}; if (z<0.5) { // Use reflection formula, as approximation doesn't work down here... return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z); } else { double x = coeff[0]; for (int i=1;i<9;i++) x += coeff[i]/(z+i-1); double t = z + 6.5; return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x); } } // Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values... double digamma(double z) { static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point. double ret = 0.0; while (z<highVal) { ret -= 1.0/z; z += 1.0; } double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz4 = iz2*iz2; double iz6 = iz4*iz2; ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0; return ret; } // Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically... double trigamma(double z) { static const double highVal = 8.0; double ret = 0.0; while (z<highVal) { ret += 1.0/(z*z); z += 1.0; } z -= 1.0; double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz3 = iz1*iz2; double iz5 = iz3*iz2; double iz7 = iz5*iz2; double iz9 = iz7*iz2; ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0; return ret; } #endif """ def lnGamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function""" code = start_cpp(gamma_code) + """ return_val = lnGamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def digamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function""" code = start_cpp(gamma_code) + """ return_val = digamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def trigamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function""" code = start_cpp(gamma_code) + """ return_val = trigamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) class TestFuncs(unittest.TestCase): """Test code for the assorted gamma-related functions.""" def test_compile(self): code = start_cpp(gamma_code) + """ """ weave.inline(code, support_code=gamma_code) def test_error_lngamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = lnGamma(z) good = gammaln(z) assert(math.fabs(own-good)<1e-12) def test_error_digamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = digamma(z) good = psi(z) assert(math.fabs(own-good)<1e-9) def test_error_trigamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = trigamma(z) good = polygamma(1,z) assert(math.fabs(own-good)<1e-9) # If this file is run do the unit tests... if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.0818, 0.0063, 0, 0.66, 0, 88, 0, 1, 0, 0, 88, 0, 0 ], [ 1, 0, 0.0881, 0.0063, 0, 0.66, 0.0909, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0943, 0.0063, 0, 0....
[ "import unittest", "import random", "import math", "from scipy.special import gammaln, psi, polygamma", "from scipy import weave", "from utils.start_cpp import start_cpp", "gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import inspect import hashlib def start_cpp(hash_str = None): """This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>""" frame = inspect.currentframe().f_back info = inspect.getframeinfo(frame) if hash_str==None: return '#line %i "%s"\n'%(info[1],info[0]) else: h = hashlib.md5() h.update(hash_str) hash_val = h.hexdigest() return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
[ [ 1, 0, 0.5, 0.0333, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.5333, 0.0333, 0, 0.66, 0.5, 154, 0, 1, 0, 0, 154, 0, 0 ], [ 2, 0, 0.8333, 0.3667, 0, 0.66, ...
[ "import inspect", "import hashlib", "def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os.path import tempfile import shutil from distutils.core import setup, Extension import distutils.ccompiler import distutils.dep_util try: __default_compiler = distutils.ccompiler.new_compiler() except: __default_compiler = None def make_mod(name, base, source, openCL = False): """Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place.""" if __default_compiler==None: raise Exception('No compiler!') # Work out the various file names - check if we actually need to do anything... if not isinstance(source, list): source = [source] source_path = map(lambda s: os.path.join(base, s), source) library_path = os.path.join(base, __default_compiler.shared_object_filename(name)) if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)): try: print 'b' # Backup the argv variable and create a temporary directory to do all work in... old_argv = sys.argv[:] temp_dir = tempfile.mkdtemp() # Prepare the extension... sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir] comp_path = filter(lambda s: not s.endswith('.h'), source_path) depends = filter(lambda s: s.endswith('.h'), source_path) if openCL: ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends) else: ext = Extension(name, comp_path, depends=depends) # Compile... setup(name=name, version='1.0.0', ext_modules=[ext]) finally: # Cleanup the argv variable and the temporary directory... sys.argv = old_argv shutil.rmtree(temp_dir, True)
[ [ 1, 0, 0.2031, 0.0156, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2188, 0.0156, 0, 0.66, 0.125, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.2344, 0.0156, 0, 0.6...
[ "import sys", "import os.path", "import tempfile", "import shutil", "from distutils.core import setup, Extension", "import distutils.ccompiler", "import distutils.dep_util", "try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None", " __default_compiler...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pydoc import inspect class DocGen: """A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.""" def __init__(self, name, title = None, summary = None): """name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title.""" if title==None: title = name if summary==None: summary = title self.doc = pydoc.HTMLDoc() self.html = open('%s.html'%name,'w') self.html.write('<html>\n') self.html.write('<head>\n') self.html.write('<title>%s</title>\n'%title) self.html.write('</head>\n') self.html.write('<body>\n') self.html_variables = '' self.html_functions = '' self.html_classes = '' self.wiki = open('%s.wiki'%name,'w') self.wiki.write('#summary %s\n\n'%summary) self.wiki.write('= %s= \n\n'%title) self.wiki_variables = '' self.wiki_functions = '' self.wiki_classes = '' def __del__(self): if self.html_variables!='': self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables)) if self.html_functions!='': self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions)) if self.html_classes!='': self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes)) self.html.write('</body>\n') self.html.write('</html>\n') self.html.close() if self.wiki_variables!='': self.wiki.write('= Variables =\n\n') self.wiki.write(self.wiki_variables) self.wiki.write('\n') if self.wiki_functions!='': self.wiki.write('= Functions =\n\n') self.wiki.write(self.wiki_functions) self.wiki.write('\n') if self.wiki_classes!='': self.wiki.write('= Classes =\n\n') self.wiki.write(self.wiki_classes) self.wiki.write('\n') self.wiki.close() def addFile(self, fn, title, fls = True): """Given a filename and section title adds the contents of said file to the output. Various flags influence how this works.""" html = [] wiki = [] for i, line in enumerate(open(fn,'r').readlines()): hl = line.replace('\n', '') if i==0 and fls: hl = '<strong>' + hl + '</strong>' for ext in ['py','txt']: if '.%s - '%ext in hl: s = hl.split('.%s - '%ext, 1) hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1] html.append(hl) wl = line.strip() if i==0 and fls: wl = '*%s*'%wl for ext in ['py','txt']: if '.%s - '%ext in wl: s = wl.split('.%s - '%ext, 1) wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n' wiki.append(wl) self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html))) self.wiki.write('== %s ==\n'%title) self.wiki.write('\n'.join(wiki)) self.wiki.write('----\n\n') def addVariable(self, var, desc): """Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc..""" self.html_variables += '<strong>%s</strong><br/>'%var self.html_variables += '%s<br/><br/>\n'%desc self.wiki_variables += '*`%s`*\n'%var self.wiki_variables += ' %s\n\n'%desc def addFunction(self, func): """Adds a function to the documentation. You provide the actual function instance.""" self.html_functions += self.doc.docroutine(func).replace('&nbsp;',' ') self.html_functions += '\n' name = func.__name__ args, varargs, keywords, defaults = inspect.getargspec(func) doc = inspect.getdoc(func) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_functions += ' %s\n\n'%doc def addClass(self, cls): """Adds a class to the documentation. You provide the actual class object.""" self.html_classes += self.doc.docclass(cls).replace('&nbsp;',' ') self.html_classes += '\n' name = cls.__name__ parents = filter(lambda a: a!=cls, inspect.getmro(cls)) doc = inspect.getdoc(cls) par_str = '' if len(parents)!=0: par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents)) self.wiki_classes += '== %s(%s) ==\n'%(name, par_str) self.wiki_classes += ' %s\n\n'%doc methods = inspect.getmembers(cls, inspect.ismethod) def method_key(pair): if pair[0]=='__init__': return '___' else: return pair[0] methods.sort(key=method_key) for name, method in methods: if not name.startswith('_%s'%cls.__name__): args, varargs, keywords, defaults = inspect.getargspec(method) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords def fetch_doc(cls, name): try: method = getattr(cls, name) if method.__doc__!=None: return inspect.getdoc(method) except: pass for parent in filter(lambda a: a!=cls, inspect.getmro(cls)): ret = fetch_doc(parent, name) if ret!=None: return ret return None doc = fetch_doc(cls, name) self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_classes += ' %s\n\n'%doc variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float)) for name, var in variables: if not name.startswith('__'): self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
[ [ 1, 0, 0.0634, 0.0049, 0, 0.66, 0, 291, 0, 1, 0, 0, 291, 0, 0 ], [ 1, 0, 0.0683, 0.0049, 0, 0.66, 0.5, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 3, 0, 0.5439, 0.9171, 0, 0.6...
[ "import pydoc", "import inspect", "class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from ctypes import * def setProcName(name): """Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases.""" # Call the process control function... libc = cdll.LoadLibrary('libc.so.6') libc.prctl(15, c_char_p(name), 0, 0, 0) # Update argv... charPP = POINTER(POINTER(c_char)) argv = charPP.in_dll(libc,'_dl_argv') size = libc.strlen(argv[0]) libc.strncpy(argv[0],c_char_p(name),size) if __name__=='__main__': # Quick test that it works... import os ps1 = 'ps' ps2 = 'ps -f' os.system(ps1) os.system(ps2) setProcName('wibble_wobble') os.system(ps1) os.system(ps2)
[ [ 1, 0, 0.3636, 0.0227, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 2, 0, 0.5682, 0.25, 0, 0.66, 0.5, 903, 0, 1, 0, 0, 0, 0, 9 ], [ 8, 1, 0.4773, 0.0227, 1, 0.24, ...
[ "from ctypes import *", "def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import multiprocessing as mp import multiprocessing.synchronize # To make sure we have all the functionality. import types import marshal import unittest def repeat(x): """A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant.""" while True: yield x def run_code(code,args): """Internal use function that does the work in each process.""" code = marshal.loads(code) func = types.FunctionType(code, globals(), '_') return func(*args) def mp_map(func, *iters, **keywords): """A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity.""" if 'pool' in keywords: pool = keywords['pool'] else: pool = mp.Pool() code = marshal.dumps(func.func_code) jobs = [] for args in zip(*iters): jobs.append(pool.apply_async(run_code,(code,args))) for i in xrange(len(jobs)): jobs[i] = jobs[i].get() return jobs class TestMpMap(unittest.TestCase): def test_simple1(self): data = ['a','b','c','d'] def noop(data): return data data_noop = mp_map(noop, data) self.assertEqual(data, data_noop) def test_simple2(self): data = [x for x in xrange(1000)] data_double = mp_map(lambda a: a*2, data) self.assertEqual(map(lambda a: a*2,data), data_double) def test_gen(self): def gen(): for i in xrange(100): yield i data_double = mp_map(lambda a: a*2, gen()) self.assertEqual(map(lambda a: a*2,gen()), data_double) def test_repeat(self): def mult(a,b): return a*b data = [x for x in xrange(50,5000,5)] data_triple = mp_map(mult, data, repeat(3)) self.assertEqual(map(lambda a: a*3,data),data_triple) def test_none(self): data = [] data_sqr = mp_map(lambda x: x*x, data) self.assertEqual([],data_sqr) if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.1456, 0.0097, 0, 0.66, 0, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 1, 0, 0.1553, 0.0097, 0, 0.66, 0.1111, 99, 0, 1, 0, 0, 99, 0, 0 ], [ 1, 0, 0.1748, 0.0097, 0, 0....
[ "import multiprocessing as mp", "import multiprocessing.synchronize # To make sure we have all the functionality.", "import types", "import marshal", "import unittest", "def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Defines helper functions for accessing numpy arrays... numpy_util_code = start_cpp() + """ #ifndef NUMPY_UTIL_CODE #define NUMPY_UTIL_CODE float & Float1D(PyArrayObject * arr, int index = 0) { return *(float*)(arr->data + index*arr->strides[0]); } float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } unsigned char & Byte1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index*arr->strides[0]); } unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } int & Int1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index*arr->strides[0]); } int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } #endif """
[ [ 1, 0, 0.1923, 0.0128, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.6282, 0.7564, 0, 0.66, 1, 799, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}" ]
# -*- coding: utf-8 -*- # Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import math import numpy import numpy.linalg import numpy.random from wishart import Wishart from gaussian import Gaussian from student_t import StudentT class GaussianPrior: """The conjugate prior for the multivariate Gaussian distribution. Maintains the 4 values and supports various operations of interest - initialisation of prior, Bayesian update, drawing a Gaussian and calculating the probability of a data point comming from a Gaussian drawn from the distribution. Not a particularly efficient implimentation, and it has no numerical protection against extremelly large data sets. Interface is not entirly orthogonal, due to the demands of real world usage.""" def __init__(self, dims): """Initialises with everything zeroed out, such that a prior must added before anything interesting is done. Supports cloning.""" if isinstance(dims, GaussianPrior): self.invShape = dims.invShape.copy() self.shape = dims.shape.copy() if dims.shape!=None else None self.mu = dims.mu.copy() self.n = dims.n self.k = dims.k else: self.invShape = numpy.zeros((dims,dims), dtype=numpy.float32) # The inverse of lambda in the equations. self.shape = None # Cached value - inverse is considered primary. self.mu = numpy.zeros(dims, dtype=numpy.float32) self.n = 0.0 self.k = 0.0 def reset(self): """Resets as though there is no data, other than the dimensions of course.""" self.invShape[:] = 0.0 self.shape = None self.mu[:] = 0.0 self.n = 0.0 self.k = 0.0 def addPrior(self, mean, covariance, weight = None): """Adds a prior to the structure, as an estimate of the mean and covariance matrix, with a weight which can be interpreted as how many samples that estimate is worth. Note the use of 'add' - you can call this after adding actual samples, or repeatedly. If weight is omitted it defaults to the number of dimensions, as the total weight in the system must match or excede this value before draws etc can be done.""" if weight==None: weight = float(self.mu.shape[0]) delta = mean - self.mu self.invShape += weight * covariance # *weight converts to a scatter matrix. self.invShape += ((self.k*weight)/(self.k+weight)) * numpy.outer(delta,delta) self.shape = None self.mu += (weight/(self.k+weight)) * delta self.n += weight self.k += weight def addSample(self, sample, weight=1.0): """Updates the prior given a single sample drawn from the Gaussian being estimated. Can have a weight provided, in which case it will be equivalent to repetition of that data point, where the repetition count can be fractional.""" sample = numpy.asarray(sample, dtype=numpy.float32) if len(sample.shape)==0: sample.shape = (1,) delta = sample - self.mu self.invShape += (weight*self.k/(self.k+weight)) * numpy.outer(delta,delta) self.shape = None self.mu += delta * (weight / (self.k+weight)) self.n += weight self.k += weight def remSample(self, sample): """Does the inverse of addSample, to in effect remove a previously added sample. Note that the issues of floating point (in-)accuracy mean its not perfect, and removing all samples is bad if there is no prior. Does not support weighting - effectvily removes a sample of weight 1.""" sample = numpy.asarray(sample, dtype=numpy.float32) if len(sample.shape)==0: sample.shape = (1,) delta = sample - self.mu self.k -= 1.0 self.n -= 1.0 self.mu -= delta / self.k self.invShape -= ((self.k+1.0)/self.k) * numpy.outer(delta,delta) self.shape = None def addSamples(self, samples, weight = None): """Updates the prior given multiple samples drawn from the Gaussian being estimated. Expects a data matrix ([sample, position in sample]), or an object that numpy.asarray will interpret as such. Note that if you have only a few samples it might be faster to repeatedly call addSample, as this is designed to be efficient for hundreds+ of samples. You can optionally weight the samples, by providing an array to the weight parameter.""" samples = numpy.asarray(samples, dtype=numpy.float32) # Calculate the mean and scatter matrices... if weight==None: # Unweighted samples... # Calculate the mean and scatter matrix... d = self.mu.shape[0] num = samples.shape[0] mean = numpy.average(samples, axis=0) scatter = numpy.tensordot(delta, delta, ([0],[0])) else: # Weighted samples... # Calculate the mean and scatter matrix... d = self.mu.shape[0] num = weight.sum() mean = numpy.average(samples, axis=0, weights=weight) delta = samples - mean.reshape((1,-1)) scatter = numpy.tensordot(weight.reshape((-1,1))*delta, delta, ([0],[0])) # Update parameters... delta = mean-self.mu self.invShape += scatter self.invShape += ((self.k*num)/(self.k+num)) * numpy.outer(delta,delta) self.shape = None self.mu += (num/(self.k+num)) * delta self.n += num self.k += num def addGP(self, gp): """Adds another Gaussian prior, combining the two.""" delta = gp.mu - self.mu self.invShape += gp.invShape self.invShape += ((gp.k*self.k)/(gp.k+self.k)) * numpy.outer(delta,delta) self.shape = None self.mu += (gp.k/(self.k+gp.k)) * delta self.n += gp.n self.k += gp.k def make_safe(self): """Checks for a singular inverse shape matrix - if singular replaces it with the identity. Also makes sure n and k are not less than the number of dimensions, clamping them if need be. obviously the result of this is quite arbitary, but its better than getting a crash from bad data.""" dims = self.mu.shape[0] det = math.fabs(numpy.linalg.det(self.invShape)) if det<1e-3: self.invShape = numpy.identity(dims, dtype=numpy.float32) if self.n<dims: self.n = dims if self.k<1e-3: self.k = 1e-3 def reweight(self, newN = None, newK = None): """A slightly cheaky method that reweights the gp such that it has the new values of n and k, effectivly adjusting the relevant weightings of the samples - can be useful for generating a prior for some GPs using the data stored in those GPs. If a new k is not provided it is set to n; if a new n is not provided it is set to the number of dimensions.""" if newN==None: newN = float(self.mu.shape[0]) if newK==None: newK = newN self.invShape *= newN / self.n self.shape = None self.n = newN self.k = newK def getN(self): """Returns n.""" return self.n def getK(self): """Returns k.""" return self.k def getMu(self): """Returns mu.""" return self.mu def getLambda(self): """Returns lambda.""" if self.shape==None: self.shape = numpy.linalg.inv(self.invShape) return self.shape def getInverseLambda(self): """Returns the inverse of lambda.""" return self.invShape def safe(self): """Returns true if it is possible to sample the prior, work out the probability of samples or work out the probability of samples being drawn from a collapsed sample - basically a test that there is enough information.""" return self.n>=self.mu.shape[0] and self.k>0.0 def prob(self, gauss): """Returns the probability of drawing the provided Gaussian from this prior.""" d = self.mu.shape[0] wishart = Wishart(d) gaussian = Gaussian(d) wishart.setDof(self.n) wishart.setScale(self.getLambda()) gaussian.setMean(self.mu) gaussian.setPrecision(self.k*gauss.getPrecision()) return wishart.prob(gauss.getPrecision()) * gaussian.prob(gauss.getMean()) def intProb(self): """Returns a multivariate student-t distribution object that gives the probability of drawing a sample from a Gaussian drawn from this prior, with the Gaussian integrated out. You may then call the prob method of this object on each sample obtained.""" d = self.mu.shape[0] st = StudentT(d) dof = self.n-d+1.0 st.setDOF(dof) st.setLoc(self.mu) mult = self.k*dof / (self.k+1.0) st.setInvScale(mult * self.getLambda()) return st def sample(self): """Returns a Gaussian, drawn from this prior.""" d = self.mu.shape[0] wishart = Wishart(d) gaussian = Gaussian(d) ret = Gaussian(d) wishart.setDof(self.n) wishart.setScale(self.getLambda()) ret.setPrecision(wishart.sample()) gaussian.setPrecision(self.k*ret.getPrecision()) gaussian.setMean(self.mu) ret.setMean(gaussian.sample()) return ret def __str__(self): return '{n:%f, k:%f, mu:%s, lambda:%s}'%(self.n, self.k, str(self.mu), str(self.getLambda()))
[ [ 1, 0, 0.0568, 0.0044, 0, 0.66, 0, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 1, 0, 0.0611, 0.0044, 0, 0.66, 0.1429, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0655, 0.0044, 0, ...
[ "import math", "import numpy", "import numpy.linalg", "import numpy.random", "from wishart import Wishart", "from gaussian import Gaussian", "from student_t import StudentT", "class GaussianPrior:\n \"\"\"The conjugate prior for the multivariate Gaussian distribution. Maintains the 4 values and suppo...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import gcp from utils import doc_gen # Setup... doc = doc_gen.DocGen('gcp', 'Gaussian Conjugate Prior', 'Library of distributions focused on the Gaussian and its conjugate prior') doc.addFile('readme.txt', 'Overview') # Classes... doc.addClass(gcp.Gaussian) doc.addClass(gcp.GaussianInc) doc.addClass(gcp.Wishart) doc.addClass(gcp.StudentT) doc.addClass(gcp.GaussianPrior)
[ [ 1, 0, 0.4667, 0.0333, 0, 0.66, 0, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 1, 0, 0.5333, 0.0333, 0, 0.66, 0.125, 970, 0, 1, 0, 0, 970, 0, 0 ], [ 14, 0, 0.7, 0.0333, 0, 0.6...
[ "import gcp", "from utils import doc_gen", "doc = doc_gen.DocGen('gcp', 'Gaussian Conjugate Prior', 'Library of distributions focused on the Gaussian and its conjugate prior')", "doc.addFile('readme.txt', 'Overview')", "doc.addClass(gcp.Gaussian)", "doc.addClass(gcp.GaussianInc)", "doc.addClass(gcp.Wish...
# -*- coding: utf-8 -*- # Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. from gaussian import Gaussian from gaussian_inc import GaussianInc from wishart import Wishart from student_t import StudentT from gaussian_prior import GaussianPrior
[ [ 1, 0, 0.7647, 0.0588, 0, 0.66, 0, 78, 0, 1, 0, 0, 78, 0, 0 ], [ 1, 0, 0.8235, 0.0588, 0, 0.66, 0.25, 680, 0, 1, 0, 0, 680, 0, 0 ], [ 1, 0, 0.8824, 0.0588, 0, 0.66...
[ "from gaussian import Gaussian", "from gaussian_inc import GaussianInc", "from wishart import Wishart", "from student_t import StudentT", "from gaussian_prior import GaussianPrior" ]
# -*- coding: utf-8 -*- # Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import math import numpy import numpy.linalg import numpy.random class Gaussian: """A basic multivariate Gaussian class. Has caching to avoid duplicate calculation.""" def __init__(self, dims): """dims is the number of dimensions. Initialises with mu at the origin and the identity matrix for the precision/covariance. dims can also be another Gaussian object, in which case it acts as a copy constructor.""" if isinstance(dims, Gaussian): self.mean = dims.mean.copy() self.precision = dims.precision.copy() if dims.precision!=None else None self.covariance = dims.covariance.copy() if dims.covariance!=None else None self.norm = dims.norm self.cholesky = dims.cholesky.copy() if dims.cholesky!=None else None else: self.mean = numpy.zeros(dims, dtype=numpy.float32) self.precision = numpy.identity(dims, dtype=numpy.float32) self.covariance = None self.norm = None self.cholesky = None def setMean(self, mean): """Sets the mean - you can use anything numpy will interprete as a 1D array of the correct length.""" nm = numpy.array(mean, dtype=numpy.float32) assert(nm.shape==self.mean.shape) self.mean = nm def setPrecision(self, precision): """Sets the precision matrix. Alternativly you can use the setCovariance method.""" np = numpy.array(precision, dtype=numpy.float32) assert(np.shape==(self.mean.shape[0],self.mean.shape[0])) self.precision = np self.covariance = None self.norm = None self.cholesky = None def setCovariance(self, covariance): """Sets the covariance matrix. Alternativly you can use the setPrecision method.""" nc = numpy.array(covariance, dtype=numpy.float32) assert(nc.shape==(self.mean.shape[0],self.mean.shape[0])) self.covariance = nc self.precision = None self.norm = None self.cholesky = None def getMean(self): """Returns the mean.""" return self.mean def getPrecision(self): """Returns the precision matrix.""" if self.precision==None: self.precision = numpy.linalg.inv(self.covariance) return self.precision def getCovariance(self): """Returns the covariance matrix.""" if self.covariance==None: self.covariance = numpy.linalg.inv(self.precision) return self.covariance def getNorm(self): """Returns the normalising constant of the distribution. Typically for internal use only.""" if self.norm==None: self.norm = math.pow(2.0*math.pi,-0.5*self.mean.shape[0]) * math.sqrt(numpy.linalg.det(self.getPrecision())) return self.norm def prob(self, x): """Given a vector x evaluates the probability density function at that point.""" x = numpy.asarray(x) offset = x - self.mean val = numpy.dot(offset,numpy.dot(self.getPrecision(),offset)) return self.getNorm() * math.exp(-0.5 * val) def sample(self): """Draws and returns a sample from the distribution.""" if self.cholesky==None: self.cholesky = numpy.linalg.cholesky(self.getCovariance()) z = numpy.random.normal(size=self.mean.shape) return self.mean + numpy.dot(self.cholesky,z) def __str__(self): return '{mean:%s, covar:%s}'%(str(self.mean), str(self.getCovariance()))
[ [ 1, 0, 0.1287, 0.0099, 0, 0.66, 0, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 1, 0, 0.1386, 0.0099, 0, 0.66, 0.25, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.1485, 0.0099, 0, 0....
[ "import math", "import numpy", "import numpy.linalg", "import numpy.random", "class Gaussian:\n \"\"\"A basic multivariate Gaussian class. Has caching to avoid duplicate calculation.\"\"\"\n def __init__(self, dims):\n \"\"\"dims is the number of dimensions. Initialises with mu at the origin and the id...
#! /usr/bin/env python # Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import p_cat from utils import doc_gen # Setup... doc = doc_gen.DocGen('p_cat', 'Probabilistic Classification', 'Standardised interface to probabilistic classifiers with features for active learning') doc.addFile('readme.txt', 'Overview') # Classes... doc.addClass(p_cat.ProbCat) doc.addClass(p_cat.ClassifyGaussian) doc.addClass(p_cat.ClassifyKDE) doc.addClass(p_cat.ClassifyDPGMM) doc.addClass(p_cat.ClassifyDF)
[ [ 1, 0, 0.4483, 0.0345, 0, 0.66, 0, 924, 0, 1, 0, 0, 924, 0, 0 ], [ 1, 0, 0.5172, 0.0345, 0, 0.66, 0.125, 970, 0, 1, 0, 0, 970, 0, 0 ], [ 14, 0, 0.6897, 0.0345, 0, ...
[ "import p_cat", "from utils import doc_gen", "doc = doc_gen.DocGen('p_cat', 'Probabilistic Classification', 'Standardised interface to probabilistic classifiers with features for active learning')", "doc.addFile('readme.txt', 'Overview')", "doc.addClass(p_cat.ProbCat)", "doc.addClass(p_cat.ClassifyGaussia...
# Copyright 2012 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import numpy import numpy.random from generators import Generator from tests import * from utils.start_cpp import start_cpp class AxisMedianGen(Generator, AxisSplit): """Provides a generator for axis-aligned split planes that split the data set in half, i.e. uses the median. Has random selection of the dimension to split the axis on.""" def __init__(self, channel, count, ignoreWeights = False): """channel is which channel to select the values from, whilst count is how many tests it will return, where each has been constructed around a randomly selected feature from the channel. Setting ignore weights to True means it will not consider the weights when calculating the median.""" AxisSplit.__init__(self, channel) self.count = count self.ignoreWeights = ignoreWeights def clone(self): return AxisMedianGen(self.channel, self.count, self.ignoreWeights) def itertests(self, es, index, weights = None): for _ in xrange(self.count): ind = numpy.random.randint(es.features(self.channel)) values = es[self.channel, index, ind] if weights==None or self.ignoreWeights: median = numpy.median(values) else: cw = numpy.cumsum(weights[index]) half = 0.5*cw[-1] pos = numpy.searchsorted(cw, half) t = (half - cw[pos-1]) / max(cw[pos] - cw[pos-1], 1e-6) median = (1.0-t)*values[pos-1] + t*values[pos] yield numpy.asarray([ind], dtype=numpy.int32).tostring() + numpy.asarray([median], dtype=numpy.float32).tostring() def genCodeC(self, name, exemplar_list): code = start_cpp() + """ struct State%(name)s { void * test; // Will be the length of a 32 bit int followed by a float. size_t length; int countRemain; float * temp; // Temporary used for calculating the median. }; int %(name)s_float_comp(const void * lhs, const void * rhs) { float l = (*(float*)lhs); float r = (*(float*)rhs); if (l<r) return -1; if (l>r) return 1; return 0; } void %(name)s_init(State%(name)s & state, PyObject * data, Exemplar * test_set) { assert(sizeof(int)==4); int count = 0; while (test_set) { count++; test_set = test_set->next; } state.length = sizeof(int) + sizeof(float); state.test = malloc(state.length); state.countRemain = %(count)i; state.temp = (float*)malloc(sizeof(float) * 2 * count); } bool %(name)s_next(State%(name)s & state, PyObject * data, Exemplar * test_set) { // Check if we are done... if (state.countRemain==0) { free(state.test); free(state.temp); return false; } state.countRemain--; // Select a random feature... %(channelType)s cd = (%(channelType)s)PyTuple_GetItem(data, %(channel)i); int feat = lrand48() %% %(channelName)s_features(cd); // Extract the values... int count = 0; while (test_set) { state.temp[count*2] = %(channelName)s_get(cd, test_set->index, feat); state.temp[count*2+1] = test_set->weight; count++; test_set = test_set->next; } // Sort them... qsort(state.temp, count, sizeof(float)*2, %(name)s_float_comp); // Pull out the median... float median; if (%(ignoreWeights)s||(count<2)) { int half = count/2; if ((count%%2)==1) median = state.temp[half*2]; else median = 0.5*(state.temp[(half-1)*2] + state.temp[half*2]); } else { // Convert to a cumulative sum... for (int i=1;i<count;i++) { state.temp[i*2+1] += state.temp[i*2-1]; } float half = 0.5*state.temp[(count-1)*2+1]; // Find the position just after the half way point... int low = 0; int high = count-1; while (low<high) { int middle = (low+high)/2; if (state.temp[middle*2+1]<half) { if (low==middle) middle++; low = middle; } else { if (high==middle) middle--; high = middle; } } // Use linear interpolation to select a value... float t = half - state.temp[low*2-1]; float div = state.temp[low*2+1] - state.temp[low*2-1]; if (div<1e-6) div = 1e-6; t /= div; median = (1.0-t) * state.temp[low*2-2] + t * state.temp[low*2]; } // Store the test and return... ((int*)state.test)[0] = feat; ((float*)state.test)[1] = median; return true; } """%{'name':name, 'channel':self.channel, 'channelName':exemplar_list[self.channel]['name'], 'channelType':exemplar_list[self.channel]['itype'], 'count':self.count, 'ignoreWeights':('true' if self.ignoreWeights else 'false')} return (code, 'State'+name) class LinearMedianGen(Generator, LinearSplit): """Provides a generator for split planes that uses the median of the features projected perpendicular to the plane direction, such that it splits the data set in half. Randomly selects which dimensions to work with and the orientation of the split plane.""" def __init__(self, channel, dims, dimCount, dirCount, ignoreWeights = False): """channel is which channel to select for and dims how many features (dimensions) to test on for any given test. dimCount is how many sets of dimensions to randomly select to generate tests for, whilst dirCount is how many random dimensions (From a uniform distribution over a hyper-sphere.) to try. It actually generates the two independantly and trys every combination, as generating uniform random directions is somewhat expensive. Setting ignore weights to True means it will not consider the weights when calculating the median.""" LinearSplit.__init__(self, channel, dims) self.dimCount = dimCount self.dirCount = dirCount self.ignoreWeights = ignoreWeights def clone(self): return LinearMedianGen(self.channel, self.dims, self.dimCount, self.dirCount, self.ignoreWeights) def itertests(self, es, index, weights = None): # Generate random points on the hyper-sphere... dirs = numpy.random.normal(size=(self.dirCount, self.dims)) dirs /= numpy.sqrt(numpy.square(dirs).sum(axis=1)).reshape((-1,1)) # Iterate and select a set of dimensions before trying each direction on them... for _ in xrange(self.dimCount): #dims = numpy.random.choice(es.features(self.channel), size=self.dims, replace=False) For when numpy 1.7.0 is common dims = numpy.zeros(self.dims, dtype=numpy.int32) feats = es.features(self.channel) for i in xrange(self.dims): dims[i] = numpy.random.randint(feats-i) dims[i] += (dims[:i]<=dims[i]).sum() for di in dirs: dists = (es[self.channel, index, dims] * di.reshape((1,-1))).sum(axis=1) if weights==None or self.ignoreWeights: median = numpy.median(dists) else: cw = numpy.cumsum(weights[index]) half = 0.5*cw[-1] pos = numpy.searchsorted(cw,half) t = (half - cw[pos-1])/max(cw[pos] - cw[pos-1], 1e-6) median = (1.0-t)*dists[pos-1] + t*dists[pos] yield numpy.asarray(dims, dtype=numpy.int32).tostring() + numpy.asarray(di, dtype=numpy.float32).tostring() + numpy.asarray([median], dtype=numpy.float32).tostring() def genCodeC(self, name, exemplar_list): code = start_cpp() + """ struct State%(name)s { void * test; size_t length; int dimRemain; int dirRemain; float * dirs; // Vectors giving points uniformly distributed on the hyper-sphere. int * feat; // The features to index at this moment. float * temp; // Temporary used for calculating the median. }; int %(name)s_float_comp(const void * lhs, const void * rhs) { float l = (*(float*)lhs); float r = (*(float*)rhs); if (l<r) return -1; if (l>r) return 1; return 0; } void %(name)s_init(State%(name)s & state, PyObject * data, Exemplar * test_set) { assert(sizeof(int)==4); // Count how many exemplars are in the input... int count = 0; while (test_set) { count++; test_set = test_set->next; } // Setup the output... state.length = sizeof(int) * %(dims)i + sizeof(float) * (%(dims)i+1); state.test = malloc(state.length); // Counters so we know when we are done... state.dimRemain = %(dimCount)i; state.dirRemain = 0; // Generate a bunch of random directions... state.dirs = (float*)malloc(sizeof(float)*%(dims)i*%(dirCount)i); for (int d=0;d<%(dirCount)i;d++) { float length = 0.0; int base = %(dims)i * d; for (int f=0; f<%(dims)i; f++) { double u = 1.0-drand48(); double v = 1.0-drand48(); float bg = sqrt(-2.0*log(u)) * cos(2.0*M_PI*v); length += bg*bg; state.dirs[base+f] = bg; } length = sqrt(length); for (int f=0; f<%(dims)i; f++) { state.dirs[base+f] /= length; } } // Which features are currently being used... state.feat = (int*)malloc(sizeof(int)*%(dims)i); // Temporary for median calculation... state.temp = (float*)malloc(sizeof(float) * 2 * count); // Safety... %(channelType)s cd = (%(channelType)s)PyTuple_GetItem(data, %(channel)i); int featCount = %(channelName)s_features(cd); if (%(dims)i>featCount) { state.dimRemain = 0; // Effectivly cancels work. } } bool %(name)s_next(State%(name)s & state, PyObject * data, Exemplar * test_set) { // Need access to the data... %(channelType)s cd = (%(channelType)s)PyTuple_GetItem(data, %(channel)i); // If we are done for this set of features select a new set... if (state.dirRemain==0) { if (state.dimRemain==0) { free(state.test); free(state.dirs); free(state.feat); free(state.temp); return false; } state.dimRemain--; // Select a new set of features... int featCount = %(channelName)s_features(cd); for (int f=0; f<%(dims)i; f++) { state.feat[f] = lrand48() %% (featCount-f); for (int j=0; j<f; j++) { if (state.feat[j]<=state.feat[f]) state.feat[f]++; } } // Reset the counter... state.dirRemain = %(dirCount)i; } state.dirRemain--; // Extract the values, projecting them using the current direction... int count = 0; while (test_set) { float val = 0.0; int base = %(dims)i * state.dirRemain; for (int f=0; f<%(dims)i; f++) { val += state.dirs[base+f] * %(channelName)s_get(cd, test_set->index, state.feat[f]); } state.temp[count*2] = val; state.temp[count*2+1] = test_set->weight; count++; test_set = test_set->next; } // Sort them... qsort(state.temp, count, sizeof(float)*2, %(name)s_float_comp); // Pull out the median... float median; if (%(ignoreWeights)s||(count<2)) { int half = count/2; if ((count%%2)==1) median = state.temp[half*2]; else median = 0.5*(state.temp[(half-1)*2] + state.temp[half*2]); } else { // Convert to a cumulative sum... for (int i=1;i<count;i++) { state.temp[i*2+1] += state.temp[i*2-1]; } float half = 0.5*state.temp[(count-1)*2+1]; // Find the position just after the half way point... int low = 0; int high = count-1; while (low<high) { int middle = (low+high)/2; if (state.temp[middle*2+1]<half) { if (low==middle) middle++; low = middle; } else { if (high==middle) middle--; high = middle; } } // Use linear interpolation to select a value... float t = half - state.temp[low*2-1]; float div = state.temp[low*2+1] - state.temp[low*2-1]; if (div<1e-6) div = 1e-6; t /= div; median = (1.0-t) * state.temp[low*2-2] + t * state.temp[low*2]; } // Store it all in the output... for (int i=0; i<%(dims)i;i++) { ((int*)state.test)[i] = state.feat[i]; } int base = %(dims)i * state.dirRemain; for (int i=0; i<%(dims)i;i++) { ((float*)state.test)[%(dims)i+i] = state.dirs[base+i]; } ((float*)state.test)[2*%(dims)i] = median; return true; } """%{'name':name, 'channel':self.channel, 'channelName':exemplar_list[self.channel]['name'], 'channelType':exemplar_list[self.channel]['itype'], 'dims':self.dims, 'dimCount':self.dimCount, 'dirCount':self.dirCount, 'ignoreWeights':('true' if self.ignoreWeights else 'false')} return (code, 'State'+name)
[ [ 1, 0, 0.0264, 0.0024, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0288, 0.0024, 0, 0.66, 0.1667, 181, 0, 1, 0, 0, 181, 0, 0 ], [ 1, 0, 0.0337, 0.0024, 0, ...
[ "import numpy", "import numpy.random", "from generators import Generator", "from tests import *", "from utils.start_cpp import start_cpp", "class AxisMedianGen(Generator, AxisSplit):\n \"\"\"Provides a generator for axis-aligned split planes that split the data set in half, i.e. uses the median. Has rand...
# Copyright 2012 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import numpy import numpy.random from utils.start_cpp import start_cpp class Generator: """A generator - provides lots of test entities designed to split an exemplar set via a (python) generator method (i.e. using yield). When a tree is constructed it is provided with a generator and each time it wants to split the generator is given the exemplar set and an index into the relevent exemplars to split on, plus an optional weighting. It then yields a set of test entities, which are applied and scored via the goal, such that the best can be selected. This is more inline with extremelly random decision forests, but there is nothing stopping the use of a goal-aware test generator that does do some kind of optimisation, potentially yielding just one test entity. The generator will contain the most important parameters of the decision forest, as it controls how the test entities are created and how many are tried - selecting the right generator and its associated parameters is essential for performance. An actual Generator is expected to also inherit from its associated Test object, such that it provides the do method. This is necesary as a test entity requires access to its associated Test object to work.""" def clone(self): """Returns a (deep) copy of this object.""" raise NotImplementedError def itertests(self, es, index, weights = None): """Generates test entities that split the provided features into two sets, yielding them one at a time such that the caller can select the best, according to the current goal. It really is allowed to do whatever it likes to create these test entities, which means it provides an insane amount of customisation potential, if possibly rather too much choice. es is the exemplar set, whilst index is the set of exemplars within the exemplar set it is creating a test for. weights optionally provides a weight for each exemplar, aligned with es.""" raise NotImplementedError yield def genCodeC(self, name, exemplar_list): """Provides C code for a generator. The return value is a 2-tuple, the first entry containing the code and the second entry `<state>`, the name of a state object to be used by the system. The state object has two public variables for use by the user - `void * test` and `size_t length`. The code itself will contain the definition of `<state>` and two functions: `void <name>_init(<state> & state, PyObject * data, Exemplar * test_set)` and `bool <name>_next(<state> & state, PyObject * data, Exemplar * test_set)`. Usage consists of creating an instance of State and calling `<name>_init` on it, then repeatedly calling `<name>_next` - each time it returns true you can use the variables in `<state>` to get at the test, but when it returns false it is time to stop (And the `<State>` will have been cleaned up.). If it is not avaliable then a NotImplementedError will be raised.""" raise NotImplementedError class MergeGen(Generator): """As most generators only handle a specific kind of data (discrete, continuous, one channel at a time.) the need arises to merge multiple generators for a given problem, in the sense that when iterating the generators tests it provides the union of all tests by all of the contained generators. Alternativly, the possibility exists to get better results by using multiple generators with different properties, as the best test from all provided will ultimatly be selected. This class merges upto 256 generators as one. The 256 limit comes from the fact the test entities provided by it have to encode which generator made them, so that the do method can send the test entity to the right test object, and it only uses a byte - in the unlikelly event that more are needed a hierarchy can be used, though your almost certainly doing it wrong if you get that far.""" def __init__(self, *args): """By default constructs the object without any generators in it, but you can provide generators to it as parameters to the constructor.""" self.gens = args assert(len(self.gens)<=256) def clone(self): ret = MergeGen() ret.gens = map(lambda g: g.clone(), self.gens) return ret def add(self, gen): """Adds a generator to the provided set. Generators can be in multiple MergeGen/RandomGen objects, just as long as a loop is not formed.""" self.gens.append(gen) assert(len(self.gens)<=256) def itertests(self, es, index, weights = None): for c, gen in enumerate(self.gens): code = chr(c) for test in gen.itertests(es, index, weights): yield code+test def do(self, test, es, index = slice(None)): code = ord(test[0]) return self.gens[code].do(test[1:], es, index) def testCodeC(self, name, exemplar_list): # Add the children... ret = '' for i, gen in enumerate(self.gens): ret += gen.testCodeC(name + '_%i'%i, exemplar_list) # Put in the final test function... ret += start_cpp() ret += 'bool %s(PyObject * data, void * test, size_t test_length, int exemplar)\n'%name ret += '{\n' ret += 'void * sub_test = ((char*)test) + 1;\n' ret += 'size_t sub_test_length = test_length - 1;\n' ret += 'int which = *(unsigned char*)test;\n' ret += 'switch(which)\n' ret += '{\n' for i in xrange(len(self.gens)): ret += 'case %i: return %s_%i(data, sub_test, sub_test_length, exemplar);\n'%(i, name, i) ret += '}\n' ret += 'return 0;\n' # To stop the compiler issuing a warning. ret += '}\n' return ret def genCodeC(self, name, exemplar_list): code = '' states = [] for i, gen in enumerate(self.gens): c, s = gen.genCodeC(name+'_%i'%i, exemplar_list) code += c states.append(s) code += start_cpp() + """ struct State%(name)s { void * test; size_t length; """%{'name':name} for i,s in enumerate(states): code += ' %s gen_%i;\n'%(s,i) code += start_cpp() + """ int upto; }; void %(name)s_init(State%(name)s & state, PyObject * data, Exemplar * test_set) { state.test = 0; state.length = 0; """%{'name':name} for i in xrange(len(self.gens)): code += '%(name)s_%(i)i_init(state.gen_%(i)i, data, test_set);\n'%{'name':name, 'i':i} code += start_cpp() + """ state.upto = 0; } bool %(name)s_next(State%(name)s & state, PyObject * data, Exemplar * test_set) { switch (state.upto) { """%{'name':name} for i in xrange(len(self.gens)): code += start_cpp() + """ case %(i)i: if (%(name)s_%(i)i_next(state.gen_%(i)i, data, test_set)) { state.length = 1 + state.gen_%(i)i.length; state.test = realloc(state.test, state.length); ((unsigned char*)state.test)[0] = %(i)i; memcpy((unsigned char*)state.test+1, state.gen_%(i)i.test, state.gen_%(i)i.length); return true; } else state.upto += 1; """%{'name':name, 'i':i} code += start_cpp() + """ } free(state.test); return false; } """ return (code, 'State'+name) class RandomGen(Generator): """This generator contains several generators, and randomly selects one to provide the tests each time itertests is called - not entirly sure what this could be used for, but it can certainly add some more randomness, for good or for bad. Supports weighting and merging multiple draws from the set of generators contained within. Has the same limit of 256 that MergeGen has, for the same reasons.""" def __init__(self, draws = 1, *args): """draws is the number of draws from the list of generators to merge to provide the final output. Note that it is drawing with replacement, and will call an underlying generator twice if it gets selected twice. After the draws parameter you can optionally provide generators, which will be put into the created object, noting that they will all have a selection weight of 1.""" self.gens = map(lambda a: (a,1.0), args) self.draws = draws assert(len(self.gens)<=256) def clone(self): ret = MergeGen(self.draws) ret.gens = map(lambda g: g.clone(), self.gens) return ret def add(self, gen, weight = 1.0): """Adds a generator to the provided set. Generators can be in multiple MergeGen/RandomGen objects, just as long as a loop is not formed. You can also provide a weight, to bias how often particular generators are selected.""" self.gens.append((gen, weight)) assert(len(self.gens)<=256) def itertests(self, es, index, weights = None): # Select which generators get to play... w = numpy.asarray(map(lambda g: g[1], self.gens)) w /= w.sum() toDo = numpy.random.multinomial(self.draws, w) # Go through and iterate the tests of each generator in turn, the number of times requested... for genInd in numpy.where(toDo!=0)[0]: code = chr(genInd) for _ in xrange(toDo[genInd]): for test in self.gens[genInd][0].itertests(es, index, weights): yield code+test def do(self, test, es, index = slice(None)): code = ord(test[0]) return self.gens[code][0].do(test[1:], es, index) def testCodeC(self, name, exemplar_list): # Add the children... ret = '' for i, (gen, _) in enumerate(self.gens): ret += gen.testCodeC(name + '_%i'%i, exemplar_list) # Put in the final test function... ret += start_cpp() ret += 'bool %s(PyObject * data, void * test, size_t test_length, int exemplar)\n'%name ret += '{\n' ret += 'void * sub_test = ((char*)test) + 1;\n' ret += 'size_t sub_test_length = test_length - 1;\n' ret += 'int which = *(unsigned char*)test;\n' ret += 'switch(which)\n' ret += '{\n' for i in xrange(len(self.gens)): ret += 'case %i: return %s_%i(data, sub_test, sub_test_length, exemplar);\n'%(i, name, i) ret += '}\n' ret += 'return 0;\n' # To stop the compiler issuing a warning. ret += '}\n' return ret def genCodeC(self, name, exemplar_list): code = '' states = [] for i, gen in enumerate(self.gens): c, s = gen[0].genCodeC(name+'_%i'%i, exemplar_list) code += c states.append(s) code += start_cpp() + """ struct State%(name)s { void * test; size_t length; """%{'name':name} for i,s in enumerate(states): code += ' %s gen_%i;\n'%(s,i) code += start_cpp() + """ int upto; int * seq; // Sequence of things to try. }; void %(name)s_init(State%(name)s & state, PyObject * data, Exemplar * test_set) { state.test = 0; state.length = 0; state.upto = -1; state.seq = (int*)malloc(sizeof(int)*%(draws)i); for (int i=0;i<%(draws)i;i++) { float weight = drand48(); """%{'name':name, 'draws':self.draws, 'count':len(self.gens)} total = sum(map(lambda g: g[1], self.gens)) ssf = 0.0 for i,gen in enumerate(self.gens): ssf += gen[1]/total code += start_cpp() + """ if (weight<%(thres)f) state.seq[i] = %(i)i; else """%{'i':i, 'thres':ssf} code += start_cpp() + """ state.seq[i] = %(count)i-1; } } bool %(name)s_next(State%(name)s & state, PyObject * data, Exemplar * test_set) { while (state.upto<%(draws)i) { if (state.upto!=-1) { switch (state.seq[state.upto]) { """%{'name':name, 'draws':self.draws, 'count':len(self.gens)} for i in xrange(len(self.gens)): code += start_cpp() + """ case %(i)i: if (%(name)s_%(i)i_next(state.gen_%(i)i, data, test_set)) { state.length = 1 + state.gen_%(i)i.length; state.test = realloc(state.test, state.length); ((unsigned char*)state.test)[0] = %(i)i; memcpy((unsigned char*)state.test+1, state.gen_%(i)i.test, state.gen_%(i)i.length); return true; } break; """%{'name':name, 'i':i} code += start_cpp() + """ } } state.upto++; if (state.upto<%(draws)i) { switch(state.seq[state.upto]) { """ %{'draws':self.draws} for i in xrange(len(self.gens)): code += start_cpp() + """ case %(i)i: %(name)s_%(i)i_init(state.gen_%(i)i, data, test_set); break; """%{'name':name, 'i':i} code += start_cpp() + """ } } } free(state.test); free(state.seq); return false; } """ return (code, 'State'+name)
[ [ 1, 0, 0.0336, 0.0031, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0367, 0.0031, 0, 0.66, 0.2, 181, 0, 1, 0, 0, 181, 0, 0 ], [ 1, 0, 0.0428, 0.0031, 0, 0.6...
[ "import numpy", "import numpy.random", "from utils.start_cpp import start_cpp", "class Generator:\n \"\"\"A generator - provides lots of test entities designed to split an exemplar set via a (python) generator method (i.e. using yield). When a tree is constructed it is provided with a generator and each time...
# Copyright 2012 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import numpy import numpy.random try: from scipy import weave except: weave = None from utils.start_cpp import start_cpp class Node: """Defines a node - these are the bread and butter of the system. Each decision tree is made out of nodes, each of which contains a binary test - if a feature vector passes the test then it travels to the true child node; if it fails it travels to the false child node (Note lowercase to avoid reserved word clash.). Eventually a leaf node is reached, where test==None, at which point the stats object is obtained, merged with the equivalent for all decision trees, and then provided as the answer to the user. Note that this python object uses the __slots__ techneque to keep it small - there will often be many thousands of these in a trained model.""" __slots__ = ['test', 'true', 'false', 'stats', 'summary'] def __init__(self, goal, gen, pruner, es, index = slice(None), weights = None, depth = 0, stats = None, entropy = None, code = None): """This recursivly grows the tree until the pruner says to stop. goal is a Goal object, so it knows what to optimise, gen a Generator object that provides tests for it to choose between and pruner is a Pruner object that decides when to stop growing. The exemplar set to train on is then provided, optionally with the indices of which members to use and weights to assign to them (weights align with the exemplar set, not with the relative exemplar indices defined by index. depth is the depth of this node - part of the recursive construction and used by the pruner as a possible reason to stop growing. stats is optionally provided to save on duplicate calculation, as it will be calculated as part of working out the split. entropy should match up with stats. The static method initC can be called to generate code that can be used by this constructor to accelerate test selection, but only if it is passed in.""" if goal==None: return # For the clone method. # Calculate the stats if not provided, and get the entropy... if stats==None: self.stats = goal.stats(es, index, weights) else: self.stats = stats self.summary = None # Use the grow method to do teh actual growth... self.give_birth(goal, gen, pruner, es, index, weights, depth, entropy, code) def give_birth(self, goal, gen, pruner, es, index = slice(None), weights = None, depth = 0, entropy = None, code = None): """This recursivly grows the tree until the pruner says to stop. goal is a Goal object, so it knows what to optimise, gen a Generator object that provides tests for it to choose between and pruner is a Pruner object that decides when to stop growing. The exemplar set to train on is then provided, optionally with the indices of which members to use and weights to assign to them (weights align with the exemplar set, not with the relative exemplar indices defined by index. depth is the depth of this node - part of the recursive construction and used by the pruner as a possible reason to stop growing. entropy should match up with self.stats. The static method initC can be called to generate code that can be used to accelerate test selection, but only if it is passed in.""" if entropy==None: entropy = goal.entropy(self.stats) # Select the best test... if isinstance(code, str) and weave!=None: # Do things in C... init = start_cpp(code) + """ if (Nindex[0]!=0) { srand48(rand); // Create the Exemplar data structure, in triplicate!.. Exemplar * items = (Exemplar*)malloc(sizeof(Exemplar)*Nindex[0]); Exemplar * splitItems = (Exemplar*)malloc(sizeof(Exemplar)*Nindex[0]); Exemplar * temp = (Exemplar*)malloc(sizeof(Exemplar)*Nindex[0]); for (int i=0; i<Nindex[0]; i++) { int ind = index[i]; float we = weights[ind]; items[i].index = ind; items[i].weight = we; items[i].next = &items[i+1]; splitItems[i].index = ind; splitItems[i].weight = we; splitItems[i].next = &splitItems[i+1]; temp[i].next = &temp[i+1]; } items[Nindex[0]-1].next = 0; splitItems[Nindex[0]-1].next = 0; temp[Nindex[0]-1].next = 0; // Do the work... selectTest(out, data, items, splitItems, temp, entropy); // Clean up... free(temp); free(splitItems); free(items); } """ data = es.tupleInputC() out = dict() rand = numpy.random.randint(-1000000000,1000000000) if weights==None: weights = numpy.ones(es.exemplars(), dtype=numpy.float32) weave.inline(init, ['out', 'data', 'index', 'weights', 'entropy', 'rand'], support_code=code) if index.shape[0]==0: return bestTest = out['bestTest'] if bestTest!=None: bestInfoGain = out['bestInfoGain'] trueStats = out['trueStats'] trueEntropy = out['trueEntropy'] trueIndex = out['trueIndex'] falseStats = out['falseStats'] falseEntropy = out['falseEntropy'] falseIndex = out['falseIndex'] trueIndex.sort() # Not needed to work - to improve cache coherance. falseIndex.sort() # " else: if index.shape[0]==0: return # Do things in python... ## Details of best test found so far... bestInfoGain = -1.0 bestTest = None trueStats = None trueEntropy = None trueIndex = None falseStats = None falseEntropy = None falseIndex = None ## Get a bunch of tests and evaluate them against the goal... for test in gen.itertests(es, index, weights): # Apply the test, work out which items pass and which fail.. res = gen.do(test, es, index) tIndex = index[res==True] fIndex = index[res==False] # Check its safe to continue... if tIndex.shape[0]==0 or fIndex.shape[0]==0: continue # Calculate the statistics... tStats = goal.stats(es, tIndex, weights) fStats = goal.stats(es, fIndex, weights) # Calculate the information gain... tEntropy = goal.entropy(tStats) fEntropy = goal.entropy(fStats) if weights==None: tWeight = float(tIndex.shape[0]) fWeight = float(fIndex.shape[0]) else: tWeight = weights[tIndex].sum() fWeight = weights[fIndex].sum() div = tWeight + fWeight tWeight /= div fWeight /= div infoGain = entropy - tWeight*tEntropy - fWeight*fEntropy # Store if the best so far... if infoGain>bestInfoGain: bestInfoGain = infoGain bestTest = test trueStats = tStats trueEntropy = tEntropy trueIndex = tIndex falseStats = fStats falseEntropy = fEntropy falseIndex = fIndex # Use the pruner to decide if we should split or not, and if so do it... self.test = bestTest if bestTest!=None and pruner.keep(depth, trueIndex.shape[0], falseIndex.shape[0], bestInfoGain, self)==True: # We are splitting - time to recurse... self.true = Node(goal, gen, pruner, es, trueIndex, weights, depth+1, trueStats, trueEntropy, code) self.false = Node(goal, gen, pruner, es, falseIndex, weights, depth+1, falseStats, falseEntropy, code) else: self.test = None self.true = None self.false = None def clone(self): """Returns a deep copy of this node. Note that it only copys the nodes - test, stats and summary are all assumed to contain invariant entities that are always replaced, never editted.""" ret = Node(None, None, None, None) ret.test = self.test ret.true = self.true.clone() if self.true!=None else None ret.false = self.false.clone() if self.false!=None else None ret.stats = self.stats ret.summary = self.summary return ret @staticmethod def initC(goal, gen, es): # Get the evaluateC code, which this code is dependent on... code = Node.evaluateC(gen, es, 'es') if code==None: return None # Add in the generator code... escl = es.listCodeC('es') try: gCode, gState = gen.genCodeC('gen', escl) except NotImplementedError: return None code += gCode # Add in the goal code... try: gDic = goal.codeC('goal', escl) except NotImplementedError: return None try: code += gDic['stats'] code += gDic['entropy'] except KeyError: return None # And finally add in the code we need to specifically handle the selection of a test for a node... code += start_cpp() + """ // out - A dictionary to output into; data - The list of entities that represent the exemplar set; items - The set of items to optimise the test for, splitItems - A copy of items, which will be screwed with; temp - Like items, same size, so we can keep a temporary copy; entropy - The entropy of the set of items. void selectTest(PyObject * out, PyObject * data, Exemplar * items, Exemplar * splitItems, Exemplar * temp, float entropy) { // Setup the generator... %(gState)s state; gen_init(state, data, items); // Loop the tests, scoring each one and keeping the best so far... void * bestTest = 0; size_t bestTestLen = 0; void * bestPassStats = 0; size_t bestPassStatsLen = 0; float bestPassEntropy = -1.0; Exemplar * bestPassItems = temp; int bestPassItemsLen = 0; void * bestFailStats = 0; size_t bestFailStatsLen = 0; float bestFailEntropy = -1.0; Exemplar * bestFailItems = 0; int bestFailItemsLen = 0; float bestGain = 0.0; Exemplar * pass = splitItems; void * passStats = 0; size_t passStatsLength = 0; Exemplar * fail = 0; void * failStats = 0; size_t failStatsLength = 0; while (gen_next(state, data, items)) { // Apply the test... Exemplar * newPass = 0; float passWeight = 0.0; Exemplar * newFail = 0; float failWeight = 0.0; while (pass) { Exemplar * next = pass->next; if (do_test(data, state.test, state.length, pass->index)) { pass->next = newPass; newPass = pass; passWeight += pass->weight; } else { pass->next = newFail; newFail = pass; failWeight += pass->weight; } pass = next; } while (fail) { Exemplar * next = fail->next; if (do_test(data, state.test, state.length, fail->index)) { fail->next = newPass; newPass = fail; passWeight += fail->weight; } else { fail->next = newFail; newFail = fail; failWeight += fail->weight; } fail = next; } pass = newPass; fail = newFail; if ((pass==0)||(fail==0)) { // All data has gone one way - this scernario can not provide an advantage so ignore it. continue; } // Generate the stats objects and entropy... goal_stats(data, pass, passStats, passStatsLength); goal_stats(data, fail, failStats, failStatsLength); float passEntropy = goal_entropy(passStats, passStatsLength); float failEntropy = goal_entropy(failStats, failStatsLength); // Calculate the information gain... float div = passWeight + failWeight; passWeight /= div; failWeight /= div; float gain = entropy - passWeight*passEntropy - failWeight*failEntropy; // If it is the largest store its output for future consumption... if (gain>bestGain) { bestTestLen = state.length; bestTest = realloc(bestTest, bestTestLen); memcpy(bestTest, state.test, bestTestLen); bestPassStatsLen = passStatsLength; bestPassStats = realloc(bestPassStats, bestPassStatsLen); memcpy(bestPassStats, passStats, bestPassStatsLen); bestFailStatsLen = failStatsLength; bestFailStats = realloc(bestFailStats, bestFailStatsLen); memcpy(bestFailStats, failStats, bestFailStatsLen); bestPassEntropy = passEntropy; bestFailEntropy = failEntropy; bestGain = gain; Exemplar * storeA = bestPassItems; Exemplar * storeB = bestFailItems; bestPassItems = 0; bestPassItemsLen = 0; bestFailItems = 0; bestFailItemsLen = 0; Exemplar * targPass = pass; while (targPass) { // Get an output node... Exemplar * out; if (storeA) { out = storeA; storeA = storeA->next; } else { out = storeB; storeB = storeB->next; } // Store it... out->next = bestPassItems; bestPassItems = out; bestPassItemsLen++; out->index = targPass->index; targPass = targPass->next; } Exemplar * targFail = fail; while (targFail) { // Get an output node... Exemplar * out; if (storeA) { out = storeA; storeA = storeA->next; } else { out = storeB; storeB = storeB->next; } // Store it... out->next = bestFailItems; bestFailItems = out; bestFailItemsLen++; out->index = targFail->index; targFail = targFail->next; } } } // Output the best into the provided dictionary - quite a lot of information... if (bestTest!=0) { PyObject * t = PyFloat_FromDouble(bestGain); PyDict_SetItemString(out, "bestInfoGain", t); Py_DECREF(t); t = PyString_FromStringAndSize((char*)bestTest, bestTestLen); PyDict_SetItemString(out, "bestTest", t); Py_DECREF(t); t = PyString_FromStringAndSize((char*)bestPassStats, bestPassStatsLen); PyDict_SetItemString(out, "trueStats", t); Py_DECREF(t); t = PyFloat_FromDouble(bestPassEntropy); PyDict_SetItemString(out, "trueEntropy", t); Py_DECREF(t); PyArrayObject * ta = (PyArrayObject*)PyArray_FromDims(1, &bestPassItemsLen, NPY_INT32); int i = 0; while (bestPassItems) { *(int*)(ta->data + ta->strides[0]*i) = bestPassItems->index; i++; bestPassItems = bestPassItems->next; } PyDict_SetItemString(out, "trueIndex", (PyObject*)ta); Py_DECREF(ta); t = PyString_FromStringAndSize((char*)bestFailStats, bestFailStatsLen); PyDict_SetItemString(out, "falseStats", t); Py_DECREF(t); t = PyFloat_FromDouble(bestFailEntropy); PyDict_SetItemString(out, "falseEntropy", t); Py_DECREF(t); ta = (PyArrayObject*)PyArray_FromDims(1, &bestFailItemsLen, NPY_INT32); i = 0; while (bestFailItems) { *(int*)(ta->data + ta->strides[0]*i) = bestFailItems->index; i++; bestFailItems = bestFailItems->next; } PyDict_SetItemString(out, "falseIndex", (PyObject*)ta); Py_DECREF(ta); } else { PyDict_SetItemString(out, "bestTest", Py_None); Py_INCREF(Py_None); } // Clean up... free(bestTest); free(bestPassStats); free(bestFailStats); free(passStats); free(failStats); } """%{'gState':gState} return code def evaluate(self, out, gen, es, index = slice(None), code=None): """Given a set of exemplars, and possibly an index, this outputs the infered stats entities. Requires the generator so it can apply the tests. The output goes into out, a list indexed by exemplar position. If code is set to a string generated by evaluateC it uses that, for speed.""" if isinstance(index, slice): index = numpy.arange(*index.indices(es.exemplars())) if isinstance(code, str) and weave!=None: init = start_cpp(code) + """ if (Nindex[0]!=0) { // Create the Exemplar data structure... Exemplar * test_set = (Exemplar*)malloc(sizeof(Exemplar)*Nindex[0]); for (int i=0; i<Nindex[0]; i++) { test_set[i].index = index[i]; test_set[i].next = &test_set[i+1]; } test_set[Nindex[0]-1].next = 0; // Do the work... evaluate(self, data, test_set, out); // Clean up... free(test_set); } """ data = es.tupleInputC() weave.inline(init, ['self', 'data', 'index', 'out'], support_code=code) return if self.test==None: # At a leaf - store this nodes stats object for the relevent nodes... for val in index: out[val] = self.stats else: # Need to split the index and send it down the two branches, as needed... res = gen.do(self.test, es, index) tIndex = index[res==True] fIndex = index[res==False] if tIndex.shape[0]!=0: self.true.evaluate(out, gen, es, tIndex) if fIndex.shape[0]!=0: self.false.evaluate(out, gen, es, fIndex) @staticmethod def evaluateC(gen, es, esclName = 'es'): """For a given generator and exemplar set this returns the C code (Actually the support code.) that evaluate can use to accelerate its run time, or None if the various components involved do not support C code generation.""" # First do accessors for the data set... try: escl = es.listCodeC(esclName) except NotImplementedError: return None code = '' for channel in escl: code += channel['get'] + '\n' code += channel['exemplars'] + '\n' code += channel['features'] + '\n' # Now throw in the test code... try: code += gen.testCodeC('do_test', escl) + '\n' except NotImplementedError: return None # Finally add in the code that recurses through and evaluates the nodes on the provided data... code += start_cpp() + """ // So we can use an inplace modified linkied list to avoid malloc's during the real work (Weight is included because this code is reused by the generator system, which needs it.)... struct Exemplar { int index; float weight; Exemplar * next; }; // Recursivly does the work... // node - node of the tree; for an external user this will always be the root. // data - python tuple containing the inputs needed at each stage. // test_set - Linked list of entities to analyse. // out - python list in which the output is to be stored. void evaluate(PyObject * node, PyObject * data, Exemplar * test_set, PyObject * out) { PyObject * test = PyObject_GetAttrString(node, "test"); if (test==Py_None) { // Leaf node - assign the relevent stats to the members of the test-set... PyObject * stats = PyObject_GetAttrString(node, "stats"); while (test_set) { Py_INCREF(stats); PyList_SetItem(out, test_set->index, stats); test_set = test_set->next; } Py_DECREF(stats); } else { // Branch node - use the test to split the test_set and recurse... // Tests... Exemplar * pass = 0; Exemplar * fail = 0; void * test_ptr = PyString_AsString(test); size_t test_len = PyString_Size(test); while (test_set) { Exemplar * next = test_set->next; if (do_test(data, test_ptr, test_len, test_set->index)) { test_set->next = pass; pass = test_set; } else { test_set->next = fail; fail = test_set; } test_set = next; } // Recurse... if (pass) { PyObject * child = PyObject_GetAttrString(node, "true"); evaluate(child, data, pass, out); Py_DECREF(child); } if (fail) { PyObject * child = PyObject_GetAttrString(node, "false"); evaluate(child, data, fail, out); Py_DECREF(child); } } Py_DECREF(test); } """ return code def size(self): """Returns how many nodes this (sub-)tree consists of.""" if self.test==None: return 1 else: return 1 + self.true.size() + self.false.size() def error(self, goal, gen, es, index = slice(None), weights = None, inc = False, store = None, code = None): """Once a tree is trained this method allows you to determine how good it is, using a test set, which would typically be its out-of-bag (oob) test set. Given a test set, possibly weighted, it will return its error rate, as defined by the goal. goal is the Goal object used for trainning, gen the Generator. Also supports incrimental testing, where the information gleened from the test set is stored such that new test exemplars can be added. This is the inc variable - True to store this (potentially large) quantity of information, and update it if it already exists, False to not store it and therefore disallow incrimental learning whilst saving memory. Note that the error rate will change by adding more training data as well as more testing data - you can call it with es==None to get an error score without adding more testing exemplars, assuming it has previously been called with inc==True. store is for internal use only. code can be provided by the relevent parameter, as generated by the errorC method, allowing a dramatic speedup.""" if code!=None and weave!=None: init = start_cpp(code) + """ float err = 0.0; float weight = 0.0; if (dummy==0) // To allow for a dummy run. { if (Nindex[0]!=0) { Exemplar * test_set = (Exemplar*)malloc(sizeof(Exemplar)*Nindex[0]); for (int i=0; i<Nindex[0]; i++) { int ind = index[i]; test_set[i].index = ind; test_set[i].weight = weights[ind]; test_set[i].next = &test_set[i+1]; } test_set[Nindex[0]-1].next = 0; error(self, data, test_set, err, weight, incNum==1); free(test_set); } else { error(self, data, 0, err, weight, incNum==1); } } return_val = err; """ data = es.tupleInputC() dummy = 1 if self==None else 0 incNum = 1 if inc else 0 if weights==None: weights = numpy.ones(es.exemplars(), dtype=numpy.float32) return weave.inline(init, ['self', 'data', 'index', 'weights', 'incNum', 'dummy'], support_code=code) else: # Book-keeping - work out if we need to return a score; make sure there is a store list... ret = store==None if ret: store = [] if isinstance(index, slice): index = numpy.arange(*index.indices(es.exemplars())) # Update the summary at this node if needed... summary = None if es!=None and index.shape[0]!=0: if self.summary==None: summary = goal.summary(es, index, weights) else: summary = goal.updateSummary(self.summary, es, index, weights) if inc: self.summary = summary # Either recurse to the leafs or include this leaf... if self.test==None: # A leaf... if summary!=None: store.append(goal.error(self.stats, summary)) else: # Not a leaf... if es!=None: res = gen.do(self.test, es, index) tIndex = index[res==True] fIndex = index[res==False] if tIndex.shape[0]!=0: self.true.error(goal, gen, es, tIndex, weights, inc, store) elif inc==True: self.true.error(goal, gen, None, tIndex, weights, inc, store) if fIndex.shape[0]!=0: self.false.error(goal, gen, es, fIndex, weights, inc, store) elif inc==True: self.false.error(goal, gen, None, fIndex, weights, inc, store) else: self.true.error(goal, gen, es, index, weights, inc, store) self.false.error(goal, gen, es, index, weights, inc, store) # Calculate the weighted average of all the leafs all at once, to avoid an inefficient incrimental calculation, or just sum them up if a weight of None has been provided at any point... if ret and len(store)!=0: if None in map(lambda t: t[1], store): return sum(map(lambda t: t[0], store)) else: store = numpy.asarray(store, dtype=numpy.float32) return numpy.average(store[:,0], weights=store[:,1]) @staticmethod def errorC(goal, gen, es, esclName = 'es'): """Provides C code that can be used by the error method to go much faster. Makes use of a goal, a generator, and an exampler set, and the code will be unique for each keying combination of these. Will return None if C code generation is not supported for the particular combination.""" # First do accessors for the data set... try: escl = es.listCodeC(esclName) except NotImplementedError: return None code = '' for channel in escl: code += channel['get'] + '\n' code += channel['exemplars'] + '\n' code += channel['features'] + '\n' # Throw in the test code... try: code += gen.testCodeC('do_test', escl) + '\n' except NotImplementedError: return None # Definition of Exemplar... code += start_cpp() + """ // So we can use an inplace modified linkied list to avoid malloc's during the real work... struct Exemplar { int index; float weight; Exemplar * next; }; """ # Add the needed goal code... try: gDic = goal.codeC('goal', escl) except NotImplementedError: return None try: code += gDic['summary'] code += gDic['updateSummary'] code += gDic['error'] except KeyError: return None # The actual code... code += start_cpp() + """ // Recursivly calculates the error whilst updating the summaries... // node - node of the tree; for an external user this will always be the root. // data - python tuple containing the inputs needed at each stage. // test_set - Linked list of entities to use to generate/update the error. // err - Variable into which the error will be output. Must be 0.0 on call. // weight - Weight that can be used in the error calculation - basically temporary storage. Must be 0.0 on call. void error(PyObject * node, PyObject * data, Exemplar * test_set, float & err, float & weight, bool inc) { // Calculate/update the summary at this node, but only store it if inc is true... void * sum = 0; size_t sumLen = 0; PyObject * summary = PyObject_GetAttrString(node, "summary"); if (summary==Py_None) { goal_summary(data, test_set, sum, sumLen); } else { sumLen = PyString_Size(summary); sum = realloc(sum, sumLen); memcpy(sum, PyString_AsString(summary), sumLen); goal_updateSummary(data, test_set, sum, sumLen); } Py_DECREF(summary); if (inc) { PyObject * t = PyString_FromStringAndSize((char*)sum, sumLen); PyObject_SetAttrString(node, "summary", t); Py_DECREF(t); } // If there is a test then recurse, otherwise calculate and include the error... PyObject * test = PyObject_GetAttrString(node, "test"); if (test==Py_None) { // Leaf node - calculate and store the error... PyObject * stats = PyObject_GetAttrString(node, "stats"); void * s = PyString_AsString(stats); size_t sLen = PyString_Size(stats); goal_error(s, sLen, sum, sumLen, err, weight); Py_DECREF(stats); } else { // Branch node - use the test to split the test_set and recurse... // Tests... Exemplar * pass = 0; Exemplar * fail = 0; void * test_ptr = PyString_AsString(test); size_t test_len = PyString_Size(test); while (test_set) { Exemplar * next = test_set->next; if (do_test(data, test_ptr, test_len, test_set->index)) { test_set->next = pass; pass = test_set; } else { test_set->next = fail; fail = test_set; } test_set = next; } // Recurse... if ((pass!=0)||inc) { PyObject * child = PyObject_GetAttrString(node, "true"); error(child, data, pass, err, weight, inc); Py_DECREF(child); } if ((fail!=0)||inc) { PyObject * child = PyObject_GetAttrString(node, "false"); error(child, data, fail, err, weight, inc); Py_DECREF(child); } } // Clean up... Py_DECREF(test); free(sum); } """ return code def removeIncError(self): """Culls the information for incrimental testing from the data structure, either to reset ready for new information or just to shrink the data structure after learning is finished.""" self.summary = None if self.test!=None: self.false.removeIncError() self.true.removeIncError() def addTrain(self, goal, gen, es, index = slice(None), weights = None, code = None): """This allows you to update the nodes with more data, as though it was used for trainning. The actual tests are not affected, only the statistics at each node - part of incrimental learning. You can optionally proivde code generated by the addTrainC method to give it go faster stripes.""" if isinstance(index, slice): index = numpy.arange(*index.indices(es.exemplars())) if code!=None: init = start_cpp(code) + """ if (dummy==0) // To allow for a dummy run. { Exemplar * test_set = (Exemplar*)malloc(sizeof(Exemplar)*Nindex[0]); for (int i=0; i<Nindex[0]; i++) { int ind = index[i]; test_set[i].index = ind; test_set[i].weight = weights[ind]; test_set[i].next = &test_set[i+1]; } test_set[Nindex[0]-1].next = 0; addTrain(self, data, test_set); free(test_set); } """ data = es.tupleInputC() dummy = 1 if self==None else 0 if weights==None: weights = numpy.ones(es.exemplars(), dtype=numpy.float32) return weave.inline(init, ['self', 'data', 'index', 'weights', 'dummy'], support_code=code) else: # Update this nodes stats... self.stats = goal.updateStats(self.stats, es, index, weights) # Check if it has children that need updating... if self.test!=None: # Need to split the index and send it down the two branches, as needed... res = gen.do(self.test, es, index) tIndex = index[res==True] fIndex = index[res==False] if tIndex.shape[0]!=0: self.true.addTrain(goal, gen, es, tIndex, weights) if fIndex.shape[0]!=0: self.false.addTrain(goal, gen, es, fIndex, weights) @staticmethod def addTrainC(goal, gen, es, esclName = 'es'): """Provides C code that the addTrain method can use to accelerate itself - standard rules about code being unique for each combination of input types applies.""" # First do accessors for the data set... try: escl = es.listCodeC(esclName) except NotImplementedError: return None code = '' for channel in escl: code += channel['get'] + '\n' code += channel['exemplars'] + '\n' code += channel['features'] + '\n' # Throw in the test code... try: code += gen.testCodeC('do_test', escl) + '\n' except NotImplementedError: return None # Definition of Exemplar... code += start_cpp() + """ // So we can use an inplace modified linkied list to avoid malloc's during the real work... struct Exemplar { int index; float weight; Exemplar * next; }; """ # Add the needed goal code... try: gDic = goal.codeC('goal', escl) except NotImplementedError: return None try: code += gDic['updateStats'] except KeyError: return None code += start_cpp() + """ void addTrain(PyObject * node, PyObject * data, Exemplar * test_set) { // Update the stats at this node... PyObject * stats = PyObject_GetAttrString(node, "stats"); size_t stLen = PyString_Size(stats); void * st = malloc(stLen); memcpy(st, PyString_AsString(stats), stLen); goal_updateStats(data, test_set, st, stLen); PyObject * t = PyString_FromStringAndSize((char*)st, stLen); PyObject_SetAttrString(node, "stats", t); Py_DECREF(t); free(st); Py_DECREF(stats); // If its not a leaf recurse down and do its children also... PyObject * test = PyObject_GetAttrString(node, "test"); if (test!=Py_None) { // Tests... Exemplar * pass = 0; Exemplar * fail = 0; void * test_ptr = PyString_AsString(test); size_t test_len = PyString_Size(test); while (test_set) { Exemplar * next = test_set->next; if (do_test(data, test_ptr, test_len, test_set->index)) { test_set->next = pass; pass = test_set; } else { test_set->next = fail; fail = test_set; } test_set = next; } // Recurse... if (pass!=0) { PyObject * child = PyObject_GetAttrString(node, "true"); addTrain(child, data, pass); Py_DECREF(child); } if (fail!=0) { PyObject * child = PyObject_GetAttrString(node, "false"); addTrain(child, data, fail); Py_DECREF(child); } } Py_DECREF(test); } """ return code def grow(self, goal, gen, pruner, es, index = slice(None), weights = None, depth = 0, code = None): """This is called on a tree that has already grown - it recurses to the children and continues as though growth never stopped. This can be to grow the tree further using a less stritc pruner or to grow the tree after further information has been added. code can be passed in as generated by the initC static method, and will be used to optimise test generation.""" if self.test==None: self.give_birth(goal, gen, pruner, es, index, weights, depth, code = code) else: res = gen.do(self.test, es, index) tIndex = index[res==True] fIndex = index[res==False] self.true.grow(goal, gen, pruner, es, tIndex, weights, depth+1, code) self.false.grow(goal, gen, pruner, es, fIndex, weights, depth+1, code)
[ [ 1, 0, 0.0109, 0.001, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0119, 0.001, 0, 0.66, 0.25, 181, 0, 1, 0, 0, 181, 0, 0 ], [ 7, 0, 0.0143, 0.002, 0, 0.66,...
[ "import numpy", "import numpy.random", "try: from scipy import weave\nexcept: weave = None", "try: from scipy import weave", "except: weave = None", "from utils.start_cpp import start_cpp", "class Node:\n \"\"\"Defines a node - these are the bread and butter of the system. Each decision tree is made ou...
# Copyright 2012 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import numpy from utils.start_cpp import start_cpp class Test: """Interface for a test definition. This provides the concept of a test that an exemplar either passes or fails. The test is actually defined by some arbitary entity made by a matching generator, but this object is required to actually do the test - contains the relevant code and any shared parameters to keep memory consumption low, as there could be an aweful lot of tests. The seperation of test from generator is required as there are typically many methods to generate a specific test - generators inherit from the relevant test object.""" def do(self, test, es, index = slice(-1)): """Does the test. Given the entity that defines the actual test and an ExemplarSet to run the test on. An optional index for the features can be provided (Passed directly through to the exemplar sets [] operator, so its indexing rules apply.), but if omitted it runs for all. Return value is a boolean numpy array indexed by the relative exemplar indices, that gives True if it passsed the test, False if it failed.""" raise NotImplementedError def testCodeC(self, name, exemplar_list): """Provides C code to perform the test - provides a C function that is given the test object as a pointer to the first byte and the index of the exemplar to test; it then returns true or false dependeing on if it passes the test or not. Returned string contains a function with the calling convention `bool <name>(PyObject * data, void * test, size_t test_length, int exemplar)`. data is a python tuple indexed by channel containning the object to be fed to the exemplar access function. To construct this function it needs the return value of listCodeC for an ExemplarSet, so it can get the calling convention to access the channel. When compiled the various functions must be avaliable.""" raise NotImplementedError class AxisSplit(Test): """Possibly the simplest test you can apply to continuous data - an axis-aligned split plane. Can also be applied to discrete data if that happens to make sense. This stores which channel to apply the tests to, whilst each test entity is a 8 byte string, encoding an int32 then a float32 - the first indexes the feature to use from the channel, the second the offset, such that an input has this value subtracted and then fails the test if the result is less than zero or passes if it is greater than or equal to.""" def __init__(self, channel): """Needs to know which channel this test is applied to.""" self.channel = channel def do(self, test, es, index = slice(None)): value_index = numpy.fromstring(test[0:4], dtype=numpy.int32, count=1) offset = numpy.fromstring(test[4:8], dtype=numpy.float32, count=1) values = es[self.channel, index, value_index[0]] return (values-offset[0])>=0.0 def testCodeC(self, name, exemplar_list): ret = start_cpp() + """ bool %(name)s(PyObject * data, void * test, size_t test_length, int exemplar) { int feature = *(int*)test; float offset = *((float*)test + 1); %(channelType)s channel = (%(channelType)s)PyTuple_GetItem(data, %(channel)i); float value = (float)%(channelName)s_get(channel, exemplar, feature); return (value-offset)>=0.0; } """%{'name':name, 'channel':self.channel, 'channelName':exemplar_list[self.channel]['name'], 'channelType':exemplar_list[self.channel]['itype']} return ret class LinearSplit(Test): """Does a linear split of data based on some small set of values. Can be applied to discrete data, though that would typically be a bit strange. This object stores both the channel to which the test is applied and how many dimensions are used, whilst the test entity is a string encoding three things in sequence. First are the int32 indices of the features from the exemplars channel to use, second are the float32 values forming the vector that is dot producted with the extracted values to project to the line perpendicular to the plane, and finally the float32 offset, subtracted from the line position to make it a negative to fail, zero or positive to pass decision.""" def __init__(self, channel, dims): """Needs to know which channel it is applied to and how many dimensions are to be considered.""" self.channel = channel self.dims = dims def do(self, test, es, index = slice(None)): ss1 = 4*self.dims ss2 = 2*ss1 ss3 = ss2+4 value_indices = numpy.fromstring(test[0:ss1], dtype=numpy.int32, count=self.dims) plane_axis = numpy.fromstring(test[ss1:ss2], dtype=numpy.float32, count=self.dims) offset = numpy.fromstring(test[ss2:ss3], dtype=numpy.float32, count=1) values = es[self.channel, index, value_indices] return ((values*plane_axis.reshape((1,-1))).sum(axis=1) - offset)>=0.0 def testCodeC(self, name, exemplar_list): ret = start_cpp() + """ bool %(name)s(PyObject * data, void * test, size_t test_length, int exemplar) { int * feature = (int*)test; float * plane_axis = (float*)test + %(dims)i; float offset = *((float*)test + %(dims)i*2); %(channelType)s channel = (%(channelType)s)PyTuple_GetItem(data, %(channel)i); float value = 0.0; for (int i=0;i<%(dims)i;i++) { float v = (float)%(channelName)s_get(channel, exemplar, feature[i]); value += v*plane_axis[i]; } return (value-offset)>=0.0; } """%{'name':name, 'channel':self.channel, 'channelName':exemplar_list[self.channel]['name'], 'channelType':exemplar_list[self.channel]['itype'], 'dims':self.dims} return ret class DiscreteBucket(Test): """For discrete values. The test is applied to a single value, and consists of a list of values such that if it is equal to one of them it passes, but if it is not equal to any of them it fails. Basically a binary split of categorical data. The test entity is a string encoding first a int32 of the index of which feature to use, followed by the remainder of the string forming a list of int32's that constitute the values that result in success.""" def __init__(self, channel): """Needs to know which channel this test is applied to.""" self.channel = channel def do(self, test, es, index = slice(None)): t = numpy.fromstring(test, dtype=numpy.int32) values = es[self.channel, index, t[0]] return numpy.in1d(values, t[1:]) def testCodeC(self, name, exemplar_list): ret = start_cpp() + """ bool %(name)s(PyObject * data, void * test, size_t test_length, int exemplar) { size_t steps = test_length>>2; int * accept = (int*)test; %(channelType)s channel = (%(channelType)s)PyTuple_GetItem(data, %(channel)i); int value = (int)%(channelName)s_get(channel, exemplar, accept[0]); for (size_t i=1; i<steps; i++) { if (accept[i]==value) return true; } return false; } """%{'name':name, 'channel':self.channel, 'channelName':exemplar_list[self.channel]['name'], 'channelType':exemplar_list[self.channel]['itype']} return ret
[ [ 1, 0, 0.0809, 0.0074, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0956, 0.0074, 0, 0.66, 0.2, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 3, 0, 0.1618, 0.0809, 0, 0.6...
[ "import numpy", "from utils.start_cpp import start_cpp", "class Test:\n \"\"\"Interface for a test definition. This provides the concept of a test that an exemplar either passes or fails. The test is actually defined by some arbitary entity made by a matching generator, but this object is required to actually ...
# Copyright 2012 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import numpy import numpy.random try: from multiprocessing import Pool, Manager, cpu_count except: Pool = None from exemplars import * from goals import * from pruners import * from nodes import * from tests import * from generators import * from gen_median import * from gen_random import * from gen_classify import * class DF: """Master object for the decision forest system - provides the entire interface. Typical use consists of setting up the system - its goal, pruner and generator(s), providing data to train a model and then using the model to analyse new exemplars. Incrimental learning is also supported however, albeit a not very sophisticated implimentation. Note that this class is compatable with pythons serialisation routines, for if you need to save/load a trained model.""" def __init__(self, other = None): """Initialises as a blank model, ready to be setup and run. Can also act as a copy constructor if you provide an instance of DF as a single parameter.""" if isinstance(other, DF): self.goal = other.goal.clone() if other.goal!=None else None self.pruner = other.pruner.clone() if other.pruner!=None else None self.gen = other.gen.clone() if other.gen!=None else None self.trees = map(lambda t: (t[0].clone(), t[1], t[2].copy() if t[2]!=None else None), other.trees) self.inc = other.inc self.grow = other.grow self.trainCount = other.trainCount self.evaluateCodeC = dict(other.evaluateCodeC) self.addCodeC = dict(other.addCodeC) self.errorCodeC = dict(other.errorCodeC) self.addTrainCodeC = dict(other.addTrainCodeC) self.useC = other.useC else: self.goal = None self.pruner = PruneCap() self.gen = None self.trees = [] # A list of tuples: (root node, oob score, draw) Last entry is None if self.grow is False, otherwise a numpy array of repeat counts for trainning for the exemplars. self.inc = False # True to support incrimental learning, False to not. self.grow = False # If true then during incrimental learning it checks pre-existing trees to see if they can grow some more each time. self.trainCount = 0 # Count of how many trainning examples were used to train with - this is so it knows how to split up the data when doing incrimental learning (between new and old exmeplars.). Also used to detect if trainning has occured. # Assorted code caches... self.evaluateCodeC = dict() self.addCodeC = dict() self.errorCodeC = dict() self.addTrainCodeC = dict() self.useC = True def setGoal(self, goal): """Allows you to set a goal object, of type Goal - must be called before doing anything, and must not be changed after anything is done.""" assert(self.trainCount==0) self.addCodeC = dict() self.errorCodeC = dict() self.addTrainCodeC = dict() self.goal = goal def getGoal(self): """Returns the curent Goal object.""" return self.goal def setPruner(self, pruner): """Sets the pruner, which controls when to stop growing each tree. By default this is set to the PruneCap object with default parameters, though you might want to use getPruner to get it so you can adjust its parameters to match the problem at hand, as the pruner is important for avoiding overfitting.""" assert(self.trainCount==0) self.pruner = pruner def getPruner(self): """Returns the current Pruner object.""" return self.pruner def setGen(self, gen): """Allows you to set the Generator object from which node tests are obtained - must be set before anything happens. You must not change this once trainning starts.""" assert(self.trainCount==0) self.evaluateCodeC = dict() self.addCodeC = dict() self.errorCodeC = dict() self.addTrainCodeC = dict() self.gen = gen def getGen(self): """Returns the Generator object for the system.""" return self.gen def setInc(self, inc, grow = False): """Set this to True to support incrimental learning, False to not. Having incrimental learning on costs extra memory, but has little if any computational affect. If incrimental learning is on you can also switch grow on, in which case as more data arrives it tries to split the leaf nodes of trees that have already been grown. Requires a bit more memory be used, as it needs to keep the indices of the training set for future growth. Note that the default pruner is entirly inappropriate for this mode - the pruner has to be set such that as more data arrives it will allow future growth.""" assert(self.trainCount==0) self.inc = inc self.grow = grow def getInc(self): """Returns the status of incrimental learning - True if its enabled, False if it is not.""" return self.inc def getGrow(self): """Returns True if the trees will be subject to further growth during incrimental learning, when they have gained enough data to subdivide further.""" return self.grow def allowC(self, allow): """By default the system will attempt to compile and use C code instead of running the (much slower) python code - this allows you to force it to not use C code, or switch C back on if you had previously switched it off. Typically only used for speed comparisons and debugging, but also useful if the use of C code doesn't work on your system. Just be aware that the speed difference is galactic.""" self.useC = allow def addTree(self, es, weightChannel = None, ret = False, dummy = False): """Adds an entirely new tree to the system given all of the new data. Uses all exemplars in the ExemplarSet, which can optionally include a channel with a single feature in it to weight the vectors; indicated via weightChannel. Typically this is used indirectly via the learn method, rather than by the user of an instance of this class.""" # Arrange for code... if self.useC: key = es.key() if key not in self.addCodeC: self.addCodeC[key] = Node.initC(self.goal, self.gen, es) code = self.addCodeC[key] if key not in self.errorCodeC: self.errorCodeC[key] = Node.errorC(self.goal, self.gen, es) errCode = self.errorCodeC[key] else: code = None errCode = None # Special case code for a dummy run... if dummy: i = numpy.zeros(0, dtype=numpy.int32) w = numpy.ones(0, dtype=numpy.float32) if code!=None: Node(self.goal, self.gen, self.pruner, es, i, w, code=code) if errCode!=None: Node.error.im_func(None, self.goal, self.gen, es, i, w, self.inc, code = errCode) return # First select which samples are to be used for trainning, and which for testing, calculating the relevant weights... draw = numpy.random.poisson(size=es.exemplars()) # Equivalent to a bootstrap sample, assuming an infinite number of exemplars are avaliable. Correct thing to do given that incrimental learning is an option. train = numpy.asarray(numpy.where(draw!=0)[0], dtype=numpy.int32) test = numpy.asarray(numpy.where(draw==0)[0], dtype=numpy.int32) if weightChannel==None: trainWeight = numpy.asarray(draw, dtype=numpy.float32) testWeight = None else: weights = es[weightChannel,:,0] trainWeight = numpy.asarray(draw * weights, dtype=numpy.float32) testWeight = numpy.asarray(weights, dtype=numpy.float32) if train.shape[0]==0: return # Safety for if it selects to use none of the items - do nothing... # Grow a tree... tree = Node(self.goal, self.gen, self.pruner, es, train, trainWeight, code=code) # Apply the goal-specific post processor to the tree... self.goal.postTreeGrow(tree, self.gen) # Calculate the oob error for the tree... if test.shape[0]!=0: error = tree.error(self.goal, self.gen, es, test, testWeight, self.inc, code=errCode) else: error = 1e100 # Can't calculate an error - record a high value so we lose the tree at the first avaliable opportunity, which is sensible behaviour given that we don't know how good it is. # Store it... if self.grow==False: draw = None if ret: return (tree, error, draw) else: self.trees.append((tree, error, draw)) def lumberjack(self, count): """Once a bunch of trees have been learnt this culls them, reducing them such that there are no more than count. It terminates those with the highest error rate first, and does nothing if there are not enough trees to excede count. Typically this is used by the learn method, rather than by the object user.""" if len(self.trees)>count: self.trees.sort(key = lambda t: t[1]) self.trees = self.trees[:count] def learn(self, trees, es, weightChannel = None, clamp = None, mp = True, callback = None): """This learns a model given data, and, when it is switched on, will also do incrimental learning. trees is how many new trees to create - for normal learning this is just how many to make, for incrimental learning it is how many to add to those that have already been made - more is always better, within reason, but it is these that cost you computation and memory. es is the ExemplarSet containing the data to train on. For incrimental learning you always provide the previous data, at the same indices, with the new exemplars appended to the end. weightChannel allows you to give a channel containing a single feature if you want to weight the importance of the exemplars. clamp is only relevent to incrimental learning - it is effectivly a maximum number of trees to allow, where it throws away the weakest trees first. This is how incrimental learning works, and so must be set for that - by constantly adding new trees as new data arrives and updating the error metrics of the older trees (The error will typically increase with new data.) the less-well trainned (and typically older) trees will be culled. mp indicates if multiprocessing should be used or not - True to do so, False to not. Will automatically switch itself off if not supported.""" # Prepare for multiprocessing... if Pool==None: mp = False elif cpu_count()<2: mp = False if mp: pool = Pool() manager = Manager() treesDone = manager.Value('i',0) result = None totalTrees = len(self.trees) + trees # If this is an incrimental pass then first update all the pre-existing trees... if self.trainCount!=0: assert(self.inc) newCount = es.exemplars() - self.trainCount key = es.key() code = self.addCodeC[key] if key in self.addCodeC else None errCode = self.errorCodeC[key] if key in self.errorCodeC else None if key not in self.addTrainCodeC: c = Node.addTrainC(self.goal, self.gen, es) self.addTrainCodeC[key] = c if c!=None: # Do a dummy run, to avoid multiproccess race conditions... i = numpy.zeros(0, dtype=numpy.int32) w = numpy.ones(0, dtype=numpy.float32) Node.addTrain.im_func(None, self.goal, self.gen, es, i, w, c) addCode = self.addTrainCodeC[key] if mp: result = pool.map_async(updateTree, map(lambda tree_tup: (self.goal, self.gen, self.pruner if self.grow else None, tree_tup, self.trainCount, newCount, es, weightChannel, (code, errCode, addCode), treesDone, numpy.random.randint(1000000000)), self.trees)) else: newTrees = [] for ti, tree_tup in enumerate(self.trees): if callback: callback(ti, totalTrees) data = (self.goal, self.gen, self.pruner if self.grow else None, tree_tup, self.trainCount, newCount, es, weightChannel, (code, errCode, addCode)) newTrees.append(updateTree(data)) self.trees = newTrees # Record how many exemplars were trained with most recently - needed for incrimental learning... self.trainCount = es.exemplars() # Create new trees... if trees!=0: if mp and trees>1: # There is a risk of a race condition caused by compilation - do a dummy run to make sure we compile in advance... self.addTree(es, weightChannel, dummy=True) # Set the runs going... newTreesResult = pool.map_async(mpGrowTree, map(lambda _: (self, es, weightChannel, treesDone, numpy.random.randint(1000000000)), xrange(trees))) # Wait for the runs to complete... while (not newTreesResult.ready()) and ((result==None) or (not result.ready())): newTreesResult.wait(0.1) if result: result.wait(0.1) if callback: callback(treesDone.value, totalTrees) # Put the result into the dta structure... if result: self.trees = result.get() self.trees += filter(lambda tree: tree!=None, newTreesResult.get()) else: for ti in xrange(trees): if callback: callback(len(self.trees)+ti, totalTrees) self.addTree(es, weightChannel) # Prune trees down to the right number of trees if needed... if clamp!=None: self.lumberjack(clamp) # Clean up if we have been multiprocessing... if mp: pool.close() pool.join() def answer_types(self): """Returns a dictionary giving all the answer types that can be requested using the which parameter of the evaluate method. The keys give the string to be provided to which, whilst the values give human readable descriptions of what will be returned. 'best' is always provided, as a point estimate of the best answer; most models also provide 'prob', which is a probability distribution over 'best', such that 'best' is the argmax of 'prob'.""" return self.goal.answer_types() def evaluate(self, es, index = slice(None), which = 'best', mp = False, callback = None): """Given some exemplars returns a list containing the output of the model for each exemplar. The returned list will align with the index, which defaults to everything and hence if not provided is aligned with es, the ExemplarSet. The meaning of the entrys in the list will depend on the Goal of the model and which: which can either be a single answer type from the goal object or a list of answer types, to get a tuple of answers for each list entry - the result is what the Goal-s answer method returns. The answer_types method passes through to provide relevent information. Can be run in multiprocessing mode if you set the mp variable to True - only worth it if you have a lot of data (Also note that it splits by tree, so each process does all data items but for just one of the trees.). Should not be called if size()==0.""" if isinstance(index, slice): index = numpy.arange(*index.indices(es.exemplars())) # Handle the generation of C code, with caching... if self.useC: es_type = es.key() if es_type not in self.evaluateCodeC: self.evaluateCodeC[es_type] = Node.evaluateC(self.gen, es) code = self.evaluateCodeC[es_type] else: code = None # If multiprocessing has been requested set it up... if Pool==None: mp = False elif cpu_count()<2: mp = False if mp: pool = Pool() pool_size = cpu_count() manager = Manager() treesDone = manager.Value('i',0) # Collate the relevent stats objects... store = [] if mp: # Dummy run, to avoid a race condition during compilation... if code!=None: ei = numpy.zeros(0, dtype=index.dtype) self.trees[0][0].evaluate([], self.gen, es, ei, code) # Do the actual work... result = pool.map_async(treeEval, map(lambda tree_error: (tree_error[0], self.gen, es, index, treesDone, code), self.trees)) while not result.ready(): result.wait(0.1) if callback: callback(treesDone.value, len(self.trees)) store += result.get() else: for ti, (tree, _, _) in enumerate(self.trees): if callback: callback(ti, len(self.trees)) res = [None] * es.exemplars() tree.evaluate(res, self.gen, es, index, code) store.append(res) # Merge and obtain answers for the output... if mp and index.shape[0]>1: step = index.shape[0]//pool_size excess = index.shape[0] - step*pool_size starts = map(lambda i: i*(step+1), xrange(excess)) starts += map(lambda i: ranges[-1] + i*step, xrange(pool_size-excess)) starts += [index.shape[0]] ranges = map(lambda a, b: slice(a, b), starts[:-1], starts[1:]) ret = pool.map(getAnswer, map(lambda ran: (self.goal, map(lambda i: map(lambda s: s[i], store), index[ran]), which, es, index[ran], map(lambda t: t[0], self.trees)), ranges)) ret = reduce(lambda a,b: a+b, ret) else: ret = self.goal.answer_batch(map(lambda i: map(lambda s: s[i], store), index), which, es, index, map(lambda t: t[0], self.trees)) # Clean up if we have been multiprocessing... if mp: pool.close() pool.join() # Return the answer... return ret def size(self): """Returns the number of trees within the forest.""" return len(self.trees) def nodes(self): """Returns the total number of nodes in all the trees.""" return sum(map(lambda t: t[0].size(), self.trees)) def error(self): """Returns the average error of all the trees - meaning depends on the Goal at hand, but should provide an idea of how well the model is working.""" return numpy.mean(map(lambda t: t[1], self.trees)) def mpGrowTree(data): """Part of the multiprocessing system - grows and returns a tree.""" self, es, weightChannel, treesDone, seed = data numpy.random.seed(seed) ret = self.addTree(es, weightChannel, True) treesDone.value += 1 return ret def updateTree(data): """Updates a tree - kept external like this for the purpose of multiprocessing.""" goal, gen, pruner, (tree, error, old_draw), prevCount, newCount, es, weightChannel, (code, errCode, addCode) = data[:9] if len(data)>10: numpy.random.seed(data[10]) # Choose which of the new samples are train and which are test, prepare the relevent inputs... draw = numpy.random.poisson(size=newCount) train = numpy.where(draw!=0)[0] + prevCount test = numpy.where(draw==0)[0] + prevCount if weightChannel==None: trainWeight = numpy.asarray(draw, dtype=numpy.float32) testWeight = None else: weights = es[weightChannel,:,prevCount:] trainWeight = numpy.asarray(draw * weights, dtype=numpy.float32) testWeight = numpy.asarray(weights, dtype=numpy.float32) pad = numpy.zeros(prevCount, dtype=numpy.float32) trainWeight = numpy.append(pad, trainWeight) if testWeight!=None: testWeight = numpy.append(pad, testWeight) # Update both test and train for the tree... if train.shape[0]!=0: tree.addTrain(goal, gen, es, train, trainWeight, addCode) error = tree.error(goal, gen, es, test, testWeight, True, code=errCode) # If we are growing its time to grow the tree... draw = None if old_draw==None else numpy.append(old_draw, draw) if pruner!=None: index = numpy.where(draw!=0)[0] if weightChannel==None: weights = numpy.asarray(draw, dtype=numpy.float32) else: weights = es[weightChannel,:,prevCount:] * numpy.asarray(draw, dtype=numpy.float32) tree.grow(goal, gen, pruner, es, index, weights, 0, code) # If provided update the trees updated count... if len(data)>9: data[9].value += 1 # Return the modified tree in a tuple with the updated error updated draw array... return (tree, error, draw) def treeEval(data): """Used by the evaluate method when doing multiprocessing.""" tree, gen, es, index, treesDone, code = data ret = [None] * es.exemplars() tree.evaluate(ret, gen, es, index, code) treesDone.value += 1 return ret def getAnswer(data): """Used for multiprocessing the calls to the answer method.""" goal, stores, which, es, indices, trees = data return goal.answer_batch(stores, which, es, indices, trees)
[ [ 1, 0, 0.0258, 0.0023, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0281, 0.0023, 0, 0.66, 0.0625, 181, 0, 1, 0, 0, 181, 0, 0 ], [ 7, 0, 0.0363, 0.0094, 0, ...
[ "import numpy", "import numpy.random", "try:\n from multiprocessing import Pool, Manager, cpu_count\nexcept:\n Pool = None", " from multiprocessing import Pool, Manager, cpu_count", " Pool = None", "from exemplars import *", "from goals import *", "from pruners import *", "from nodes import *", ...
# Copyright 2012 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import random import numpy import numpy.random from generators import Generator from tests import * from utils.start_cpp import start_cpp class AxisClassifyGen(Generator, AxisSplit): """Provides a generator that creates axis-aligned split planes that have their position selected to maximise the information gain with respect to the task of classification.""" def __init__(self, channel, catChannel, count): """channel is which channel to select the values from; catChannel contains the true classes of the features so the split can be optimised; and count is how many tests it will return, where each has been constructed around a randomly selected feature from the channel.""" AxisSplit.__init__(self, channel) self.catChannel = catChannel self.count = count def clone(self): return AxisClassifyGen(self.channel, self.catChannel, self.count) def itertests(self, es, index, weights = None): def entropy(histo): histo = histo[histo>1e-6] return -(histo*(numpy.log(histo) - numpy.log(histo.sum()))).sum() for _ in xrange(self.count): ind = numpy.random.randint(es.features(self.channel)) values = es[self.channel, index, ind] cats = es[self.catChannel, index, 0] if cats.shape[0]<2: split = 0.0 else: indices = numpy.argsort(values) values = values[indices] cats = cats[indices] high = numpy.bincount(cats, weights=weights[index] if weights!=None else None) low = numpy.zeros(high.shape[0], dtype=numpy.float32) improvement = -1e100 for i in xrange(values.shape[0]-1): # Move the selected item from high to low... w = weights[index[indices[i]]] if weights!=None else 1 high[cats[i]] -= w low[cats[i]] += w # Calculate the improvement (Within a scalar factor constant for the entire field - only care about the relative value.)... imp = -(entropy(low) + entropy(high)) # Keep if best... if imp>improvement: split = 0.5*(values[i] + values[i+1]) improvement = imp yield numpy.asarray([ind], dtype=numpy.int32).tostring() + numpy.asarray([split], dtype=numpy.float32).tostring() def genCodeC(self, name, exemplar_list): code = start_cpp() + """ struct Store%(name)s { int cat; float value; float weight; }; struct State%(name)s { void * test; // Will be the length of a 32 bit int followed by a float. size_t length; int countRemain; Store%(name)s * temp; // Temporary used for storing the sorted values. int catCount; float * low; float * high; }; int %(name)s_store_comp(const void * lhs, const void * rhs) { const Store%(name)s & l = (*(Store%(name)s*)lhs); const Store%(name)s & r = (*(Store%(name)s*)rhs); if (l.value<r.value) return -1; if (l.value>r.value) return 1; return 0; } void %(name)s_init(State%(name)s & state, PyObject * data, Exemplar * test_set) { assert(sizeof(int)==4); int count = 0; state.catCount = 0; %(catChannelType)s ccd = (%(catChannelType)s)PyTuple_GetItem(data, %(catChannel)i); while (test_set) { count++; int cat = %(catChannelName)s_get(ccd, test_set->index, 0); if (cat>=state.catCount) state.catCount = cat+1; test_set = test_set->next; } state.length = sizeof(int) + sizeof(float); state.test = malloc(state.length); state.countRemain = %(count)i; state.temp = (Store%(name)s*)malloc(sizeof(Store%(name)s) * count); state.low = (float*)malloc(state.catCount*sizeof(float)); state.high = (float*)malloc(state.catCount*sizeof(float)); } bool %(name)s_next(State%(name)s & state, PyObject * data, Exemplar * test_set) { // Check if we are done... if (state.countRemain==0) { free(state.test); free(state.temp); free(state.low); free(state.high); return false; } state.countRemain--; // Select a random feature... %(channelType)s cd = (%(channelType)s)PyTuple_GetItem(data, %(channel)i); int feat = lrand48() %% %(channelName)s_features(cd); %(catChannelType)s ccd = (%(catChannelType)s)PyTuple_GetItem(data, %(catChannel)i); // Extract the values... int count = 0; while (test_set) { state.temp[count].cat = %(catChannelName)s_get(ccd, test_set->index, 0); state.temp[count].value = %(channelName)s_get(cd, test_set->index, feat); state.temp[count].weight = test_set->weight; count++; test_set = test_set->next; } // Sort them... qsort(state.temp, count, sizeof(Store%(name)s), %(name)s_store_comp); // Find the optimal split point... float bestSplit = 0.0; float bestImp = -1e100; for (int c=0; c<state.catCount; c++) { state.low[c] = 0.0; state.high[c] = 0.0; } for (int i=0; i<count; i++) { state.high[state.temp[i].cat] += state.temp[i].weight; } for (int i=0; i<(count-1); i++) { // Move the indexed element across... int c = state.temp[i].cat; float w = state.temp[i].weight; state.low[c] += w; state.high[c] -= w; // Calculate the improvement... float lowSum = 0.0; float highSum = 0.0; for (int c=0; c<state.catCount; c++) { lowSum += state.low[c]; highSum += state.high[c]; } float logLowSum = log(lowSum); float logHighSum = log(highSum); float imp = 0.0; for (int c=0; c<state.catCount; c++) { if (state.low[c]>1e-6) imp += state.low[c] * (log(state.low[c]) - logLowSum); if (state.high[c]>1e-6) imp += state.high[c] * (log(state.high[c]) - logHighSum); } // If its the best calculate and store the split point... if (imp>bestImp) { bestSplit = 0.5 * (state.temp[i].value + state.temp[i+1].value); bestImp = imp; } } // Store the test and return... ((int*)state.test)[0] = feat; ((float*)state.test)[1] = bestSplit; return true; } """%{'name':name, 'channel':self.channel, 'channelName':exemplar_list[self.channel]['name'], 'channelType':exemplar_list[self.channel]['itype'], 'catChannel':self.catChannel, 'catChannelName':exemplar_list[self.catChannel]['name'], 'catChannelType':exemplar_list[self.catChannel]['itype'], 'count':self.count} return (code, 'State'+name) class LinearClassifyGen(Generator, LinearSplit): """Provides a generator for split planes that projected the features perpendicular to a random plane direction but then optimises where to put the split plane to maximise classification performance. Randomly selects which dimensions to work with and the orientation of the split plane.""" def __init__(self, channel, catChannel, dims, dimCount, dirCount): """channel is which channel to select for and catChannel the channel to get the classification answers from. dims is how many features (dimensions) to test on for any given test. dimCount is how many sets of dimensions to randomly select to generate tests for, whilst dirCount is how many random dimensions (From a uniform distribution over a hyper-sphere.) to try. It actually generates the two independantly and trys every combination, as generating uniform random directions is somewhat expensive.""" LinearSplit.__init__(self, channel, dims) self.catChannel = catChannel self.dimCount = dimCount self.dirCount = dirCount def clone(self): return LinearClassifyGen(self.channel, self.catChannel, self.dims, self.dimCount, self.dirCount) def itertests(self, es, index, weights = None): def entropy(histo): histo = histo[histo>1e-6] return -(histo*(numpy.log(histo) - numpy.log(histo.sum()))).sum() # Generate random points on the hyper-sphere... dirs = numpy.random.normal(size=(self.dirCount, self.dims)) dirs /= numpy.sqrt(numpy.square(dirs).sum(axis=1)).reshape((-1,1)) # Iterate and select a set of dimensions before trying each direction on them... for _ in xrange(self.dimCount): #dims = numpy.random.choice(es.features(self.channel), size=self.dims, replace=False) For when numpy 1.7.0 is common dims = numpy.zeros(self.dims, dtype=numpy.int32) feats = es.features(self.channel) for i in xrange(self.dims): dims[i] = numpy.random.randint(feats-i) dims[i] += (dims[:i]<=dims[i]).sum() for di in dirs: dists = (es[self.channel, index, dims] * di.reshape((1,-1))).sum(axis=1) cats = es[self.catChannel, index, 0] split = 0.0 if cats.shape[0]>1: indices = numpy.argsort(dists) dists = dists[indices] cats = cats[indices] high = numpy.bincount(cats, weights=weights[index[indices]] if weights!=None else None) low = numpy.zeros(high.shape[0], dtype=numpy.float32) improvement = -1e100 for i in xrange(dists.shape[0]-1): # Move the selected item from high to low... w = weights[index[indices[i]]] if weights!=None else 1 high[cats[i]] -= w low[cats[i]] += w # Calculate the improvement (Within a scalar factor constant for the entire field - only care about the relative value.)... imp = -(entropy(low) + entropy(high)) # Keep if best... if imp>improvement: ratio = numpy.random.random() split = ratio*dists[i] + (1.0-ratio)*dists[i+1] improvement = imp yield numpy.asarray(dims, dtype=numpy.int32).tostring() + numpy.asarray(di, dtype=numpy.float32).tostring() + numpy.asarray([split], dtype=numpy.float32).tostring() def genCodeC(self, name, exemplar_list): code = start_cpp() + """ struct Store%(name)s { int cat; float value; float weight; }; struct State%(name)s { void * test; // Will be the length of a 32 bit int followed by a float. size_t length; float * dirs; // Vectors giving points uniformly distributed on the hyper-sphere. int * feat; // The features to index at this moment. int dimRemain; int dirRemain; Store%(name)s * temp; // Temporary used for storing the sorted values. int catCount; float * low; float * high; }; int %(name)s_store_comp(const void * lhs, const void * rhs) { const Store%(name)s & l = (*(Store%(name)s*)lhs); const Store%(name)s & r = (*(Store%(name)s*)rhs); if (l.value<r.value) return -1; if (l.value>r.value) return 1; return 0; } void %(name)s_init(State%(name)s & state, PyObject * data, Exemplar * test_set) { assert(sizeof(int)==4); // Count how many exemplars are in the input, and how many classes are represented... int count = 0; state.catCount = 0; %(catChannelType)s ccd = (%(catChannelType)s)PyTuple_GetItem(data, %(catChannel)i); while (test_set) { count++; int cat = %(catChannelName)s_get(ccd, test_set->index, 0); if (cat>=state.catCount) state.catCount = cat+1; test_set = test_set->next; } // Setup the output... state.length = sizeof(int) * %(dims)i + sizeof(float) * (%(dims)i+1); state.test = malloc(state.length); // Counters so we know when we are done... state.dimRemain = %(dimCount)i; state.dirRemain = 0; // Generate a bunch of random directions... state.dirs = (float*)malloc(sizeof(float)*%(dims)i*%(dirCount)i); for (int d=0;d<%(dirCount)i;d++) { float length = 0.0; int base = %(dims)i * d; for (int f=0; f<%(dims)i; f++) { double u = 1.0-drand48(); double v = 1.0-drand48(); float bg = sqrt(-2.0*log(u)) * cos(2.0*M_PI*v); length += bg*bg; state.dirs[base+f] = bg; } length = sqrt(length); for (int f=0; f<%(dims)i; f++) { state.dirs[base+f] /= length; } } // Which features are currently being used... state.feat = (int*)malloc(sizeof(int)*%(dims)i); // Temporary for sorting the exemplars by value... state.temp = (Store%(name)s*)malloc(sizeof(Store%(name)s) * count); // Class count arrays for optimal split selection... state.low = (float*)malloc(state.catCount*sizeof(float)); state.high = (float*)malloc(state.catCount*sizeof(float)); // Safety... %(channelType)s cd = (%(channelType)s)PyTuple_GetItem(data, %(channel)i); int featCount = %(channelName)s_features(cd); if (%(dims)i>featCount) { state.dimRemain = 0; // Effectivly cancels work. } } bool %(name)s_next(State%(name)s & state, PyObject * data, Exemplar * test_set) { // Need access to the data... %(channelType)s cd = (%(channelType)s)PyTuple_GetItem(data, %(channel)i); %(catChannelType)s ccd = (%(catChannelType)s)PyTuple_GetItem(data, %(catChannel)i); // If we are done for this set of features select a new set... if (state.dirRemain==0) { if (state.dimRemain==0) { free(state.test); free(state.dirs); free(state.feat); free(state.temp); return false; } state.dimRemain--; // Select a new set of features... int featCount = %(channelName)s_features(cd); for (int f=0; f<%(dims)i; f++) { state.feat[f] = lrand48() %% (featCount-f); for (int j=0; j<f; j++) { if (state.feat[j]<=state.feat[f]) state.feat[f]++; } } // Reset the counter... state.dirRemain = %(dirCount)i; } state.dirRemain--; // Extract the values, projecting them using the current direction... int count = 0; while (test_set) { float val = 0.0; int base = %(dims)i * state.dirRemain; for (int f=0; f<%(dims)i; f++) { val += state.dirs[base+f] * %(channelName)s_get(cd, test_set->index, state.feat[f]); } state.temp[count].cat = %(catChannelName)s_get(ccd, test_set->index, 0); state.temp[count].value = val; state.temp[count].weight = test_set->weight; count++; test_set = test_set->next; } // Sort them... qsort(state.temp, count, sizeof(Store%(name)s), %(name)s_store_comp); // Find the optimal split point... float bestSplit = 0.0; float bestImp = -1e100; for (int c=0; c<state.catCount; c++) { state.low[c] = 0.0; state.high[c] = 0.0; } for (int i=0; i<count; i++) { state.high[state.temp[i].cat] += state.temp[i].weight; } for (int i=0; i<(count-1); i++) { // Move the indexed element across... int c = state.temp[i].cat; float w = state.temp[i].weight; state.low[c] += w; state.high[c] -= w; // Calculate the improvement... float lowSum = 0.0; float highSum = 0.0; for (int c=0; c<state.catCount; c++) { lowSum += state.low[c]; highSum += state.high[c]; } float logLowSum = log(lowSum); float logHighSum = log(highSum); float imp = 0.0; for (int c=0; c<state.catCount; c++) { if (state.low[c]>1e-6) imp += state.low[c] * (log(state.low[c]) - logLowSum); if (state.high[c]>1e-6) imp += state.high[c] * (log(state.high[c]) - logHighSum); } // If its the best calculate and store the split point... if (imp>bestImp) { bestSplit = 0.5 * (state.temp[i].value + state.temp[i+1].value); bestImp = imp; } } // Store it all in the output... for (int i=0; i<%(dims)i;i++) { ((int*)state.test)[i] = state.feat[i]; } int base = %(dims)i * state.dirRemain; for (int i=0; i<%(dims)i;i++) { ((float*)state.test)[%(dims)i+i] = state.dirs[base+i]; } ((float*)state.test)[2*%(dims)i] = bestSplit; return true; } """%{'name':name, 'channel':self.channel, 'channelName':exemplar_list[self.channel]['name'], 'channelType':exemplar_list[self.channel]['itype'], 'catChannel':self.catChannel, 'catChannelName':exemplar_list[self.catChannel]['name'], 'catChannelType':exemplar_list[self.catChannel]['itype'], 'dims':self.dims, 'dimCount':self.dimCount, 'dirCount':self.dirCount} return (code, 'State'+name) class DiscreteClassifyGen(Generator, DiscreteBucket): """Defines a generator for discrete data. It basically takes a single discrete feature and then greedily optimises to get the best classification performance, As it won't necesarilly converge to the global optimum multiple restarts are provided. The discrete values must form a contiguous set, starting at 0 and going upwards. When splitting it only uses values it can see - unseen values will fail the test, though it always arranges for the most informative half to be the one that passes the test.""" def __init__(self, channel, catChannel, featCount, initCount): """channel is the channel to build discrete tests for; featCount is how many random features to randomly select and initCount how many random initialisations to try for each feature.""" DiscreteBucket.__init__(self, channel) self.catChannel = catChannel self.featCount = featCount self.initCount = initCount def clone(self): return DiscreteClassifyGen(self.channel, self.catChannel, self.featCount, self.initCount) def itertests(self, es, index, weights = None): # Helper function used below... def entropy(histo): histo = histo[histo>1e-6] return -(histo*(numpy.log(histo) - numpy.log(histo.sum()))).sum() # Iterate and yield the right number of tests... for _ in xrange(self.featCount): # Randomly select a feature, get the values and categories... feat = numpy.random.randint(es.features(self.channel)) values = es[self.channel, index, feat] cats = es[self.catChannel, index, 0] # Create histograms of category counts for each value... histos = dict() maxHistoSize = 0 for value in numpy.unique(values): use = values==value histos[value] = numpy.bincount(cats[use], weights = weights[index[use]] if weights!=None else None) maxHistoSize = max(maxHistoSize, histos[value].shape[0]) if len(histos)<2: # Can't optimise - give up. yield numpy.asarray(feat, dtype=numpy.int32).tostring() continue # Optimise from multiple starting points... for _ in xrange(self.initCount): # Generate a random greedy order... order = numpy.random.permutation(histos.keys()) # Initialise by putting the first two entrys in different halfs... low = numpy.zeros(maxHistoSize, dtype=numpy.float32) high = numpy.zeros(maxHistoSize, dtype=numpy.float32) low[:histos[order[0]].shape[0]] += histos[order[0]] lowEnt = entropy(low) keepLow = [order[0]] high[:histos[order[1]].shape[0]] += histos[order[1]] highEnt = entropy(high) keepHigh = [order[1]] # Loop the rest and put each of them in the best half... for i in xrange(2, order.shape[0]): # Get the histogram... histo = histos[order[i]] # Calculate the options... lowOp = low.copy() lowOp[:histo.shape[0]] += histo lowOpEnt = entropy(lowOp) highOp = high.copy() highOp[:histo.shape[0]] += histo highOpEnt = entropy(highOp) # Choose the best... if (lowEnt+highOpEnt)<(lowOpEnt+highEnt): high = highOp highEnt = highOpEnt keepHigh.append(order[i]) else: low = lowOp lowEnt = lowOpEnt keepLow.append(order[i]) # Swap the halfs so the half that passes has the lowest entropy - this is because unseen values will fail, so might as well send them to the least certain side... if lowEnt<highEnt: keepHigh = keepLow # Yield a discrete decision object... yield numpy.asarray(feat, dtype=numpy.int32).tostring() + numpy.asarray(keepHigh, dtype=numpy.int32).tostring() try: from svm import svm class SVMClassifyGen(Generator, Test): """Allows you to use the SVM library as a classifier for a node. Note that it detects if the SVM library is avaliable - if not then this class will not exist. Be warned that its quite memory intensive, as it just wraps the SVM objects without any clever packing. Works by randomly selecting a class to seperate and training a one vs all classifier, with random parameters on random features. Parameters are quite complicated, due to all the svm options and randomness control being extensive.""" def __init__(self, params, paramDraw, catChannel, catDraw, featChannel, featCount, featDraw): """There are three parts - the svm parameters to use, the class to seperate and the features to train on, all of which allow for the introduction of randomness. The svm parameters are controlled by params - it must be either a single svm.Params or a list of them, which includes things like parameter sets provided by the svm library. For each test generation paramDraw parameter options are selected randomly from params and tried combinatorically with the other two parts. The class of each feature must be provided, as an integer in channel catChannel. For each test generation it selects one class randomly from the classes exhibited by the features, which it does catDraw times, combinatorically with the other two parts. The features to train on are found in channel featChannel, and it randomly selects featCount of them to be used for each trainning run, which it does featDraw times combinatorically with the other two parameters. Each time classifiers are generated it will produce the product of the three *Draw parameters generators, where it draws each set once and then tries all combinations between the three.""" # svm parameters... if isinstance(params, svm.Params): self.params = [params] else: self.params = [x for x in params] self.paramDraw = paramDraw # class parameters... self.catChannel = catChannel self.catDraw = catDraw # feature parameters... self.featChannel = featChannel self.featCount = featCount self.featDraw = featDraw def clone(self): return SVMClassifyGen(self.params, self.paramDraw, self.catChannel, self.catDraw, self.featChannel, self.featCount, self.featDraw) def do(self, test, es, index = slice(None)): # Test is (feat index, svm.Model) - feat index grabs the features to run the model on, which tells you which side they belong on... dataMatrix = numpy.asarray(es[self.featChannel, index, test[0]], dtype=numpy.float_) if len(dataMatrix.shape)!=2: dataMatrix = dataMatrix.reshape((1,-1)) values = test[1].multiClassify(dataMatrix) return values>0 def itertests(self, es, index, weights = None): # Generate the set of svm parameters to use... param_set = random.sample(self.params, self.paramDraw) # Generate the set of classes to train for... cats = es[self.catChannel, index, 0] if numpy.unique(cats).shape[0]<2: return cat_set = random.sample(cats, min(self.catDraw, cats.shape[0])) y = numpy.empty(cats.shape[0], dtype=numpy.float_) # Iterate and yield each decision boundary by learning a model - base iteration is over the features to use for trainning... smo = svm.smo.SMO() for _ in xrange(self.featDraw): # Draw the feature set to use... feat_index = random.sample(xrange(es.features(self.featChannel)), self.featCount) feat_index = numpy.array(feat_index, dtype=numpy.int32) dataMatrix = numpy.asarray(es[self.featChannel, index, feat_index], dtype=numpy.float_) # Try it combinatorically with the other two... for cat in cat_set: y[:] = -1.0 y[cats==cat] = 1.0 smo.setData(dataMatrix, y) for param in param_set: smo.setParams(param) smo.solve() yield (feat_index, smo.getModel()) except ImportError: pass # Allow it to still work when the svm module is not avaliable.
[ [ 1, 0, 0.0162, 0.0015, 0, 0.66, 0, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0177, 0.0015, 0, 0.66, 0.1111, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0191, 0.0015, 0, ...
[ "import random", "import numpy", "import numpy.random", "from generators import Generator", "from tests import *", "from utils.start_cpp import start_cpp", "class AxisClassifyGen(Generator, AxisSplit):\n \"\"\"Provides a generator that creates axis-aligned split planes that have their position selected...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...