code stringlengths 1 1.49M | vector listlengths 0 7.38k | snippet listlengths 0 7.38k |
|---|---|---|
# 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(' ',' ')
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(' ',' ')
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.26,
... | [
"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(' ',' ')
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(' ',' ')
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.46,
... | [
"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(' ',' ')
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(' ',' ')
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.04,
... | [
"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(' ',' ')
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(' ',' ')
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.46,
... | [
"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(' ',' ')
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(' ',' ')
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.4,
... | [
"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(' ',' ')
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(' ',' ')
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.01,
... | [
"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 2010 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 params import Kernel
from params import Params
from copy import copy
class ParamsRange:
"""A parameters object where each variable takes a list rather than a single value - it then pretends to be a list of Params objects, which consists of every combination implied by the ranges."""
def __init__(self):
"""Initialises to contain just the default."""
self.c = [10.0]
self.rebalance = [True]
# Which kernel to use and two parameters whose meanings depend on the kernel...
self.kernel = [Kernel.linear]
self.p1 = [1.0]
self.p2 = [1.0]
def getCList(self):
"""Returns the list of c parameters."""
return self.c
def setCList(self,c):
"""Sets the list of c values."""
self.c = c
def getRebalanceList(self):
"""Returns the list of rebalance options - can only ever be two"""
return self.rebalance
def setRebalanceList(self,rebalance):
"""Sets if c is rebalanced or not."""
self.rebalance = rebalance
def setKernelList(self,kernel):
"""Sets the list of kernels."""
self.kernel = kernel
def setP1List(self,p1):
"""Sets the list of P1 values."""
self.p1 = p1
def setP2List(self,p2):
"""Sets the list of P2 values."""
self.p2 = p2
def getKernelList(self):
"""Returns the list of kernels."""
return self.kernel
def getP1List(self):
"""returns the list of kernel parameters 1, not always used."""
return self.p1
def getP2List(self):
"""returns the list of kernel parameters 2, not always used."""
return self.p2
def permutations(self):
p = Params()
for c in self.c:
p.setC(c)
for rebalance in self.rebalance:
p.setRebalance(c)
for kernel in self.kernel:
p.setKernel(kernel)
for p1 in self.p1:
p.setP1(p1)
for p2 in self.p2:
p.setP2(p2)
yield copy(p)
def __iter__(self):
return self.permutations()
class ParamsSet:
"""Pretends to be a list of parameters, when instead it is a list of parameter ranges, where each set of ranges defines a search grid - used for model selection, typically by being passed as the params input to the MultiModel class."""
def __init__(self, incDefault = False, incExtra = False):
"""Initialises the parameter set - with the default constructor this is empty. However, initalising it with paramsSet(True) gets you a good default set to model select with (That is the addLinear and addPoly methods are called with default parameters.), whilst paramsSet(True,True) gets you an insanely large default set for if your feeling particularly patient (It being all the add methods with default parameters.)."""
self.ranges = []
if incDefault:
self.addLinear()
self.addPoly()
if incExtra:
self.addHomoPoly()
self.addBasisFuncs()
self.addSigmoid()
def addRange(self, ran):
"""Adds a new ParamsRange to the set."""
self.ranges.append(ran)
def addLinear(self, cExpLow = -3, cExpHigh = 3, cExp = 10.0, rebalance = True):
"""Adds a standard linear model to the set, with a range of c values. These values will range from cExp^cExpLow to cExp^cExpHigh, and by default are the set {0.001,0.01,0.1,1,10,100,1000}, which is typically good enough."""
ran = ParamsRange()
ran.setCList(map(lambda x:cExp**x,xrange(cExpLow,cExpHigh+1)))
ran.setRebalanceList([rebalance])
self.addRange(ran)
def addHomoPoly(self, maxDegree = 6, cExpLow = -3, cExpHigh = 3, cExp = 10.0, rebalance = True):
"""Adds the homogenous polynomial to the set, from an exponent of 2 to the given value inclusive, which defaults to 8. Same c controls as for addLinear."""
ran = ParamsRange()
ran.setCList(map(lambda x:cExp**x,xrange(cExpLow,cExpHigh+1)))
ran.setRebalanceList([rebalance])
ran.setKernelList([Kernel.homo_polynomial])
ran.setP1List(range(2,maxDegree+1))
self.addRange(ran)
def addPoly(self, maxDegree = 6, cExpLow = -3, cExpHigh = 3, cExp = 10.0, rebalance = True):
"""Adds the polynomial to the set, from an exponent of 2 to the given value inclusive, which defaults to 8. Same c controls as for addLinear."""
ran = ParamsRange()
ran.setCList(map(lambda x:cExp**x,xrange(cExpLow,cExpHigh+1)))
ran.setRebalanceList([rebalance])
ran.setKernelList([Kernel.polynomial])
ran.setP1List(range(2,maxDegree+1))
self.addRange(ran)
def addBasisFuncs(self, rExpHigh = 6, rExp = 2.0, sdExpHigh = 6, sdExp = 2.0, cExpLow = -3, cExpHigh = 3, cExp = 10.0, rebalance = True):
"""Adds the basis functions to the set, both Radial and Gaussian. The parameter for the radial basis functions go from rExp^0 to rExp^rExpHigh, whilst the parameter for the Gaussian does the same thing, but with the sd parameters. Same c controls as for addLinear."""
ran = ParamsRange()
ran.setCList(map(lambda x:cExp**x,xrange(cExpLow,cExpHigh+1)))
ran.setRebalanceList([rebalance])
ran.setKernelList([Kernel.rbf])
ran.setP1List(map(lambda x:rExp**x,xrange(rExpHigh+1)))
self.addRange(ran)
ran = ParamsRange()
ran.setCList(map(lambda x:cExp**x,xrange(cExpLow,cExpHigh+1)))
ran.setRebalanceList([rebalance])
ran.setKernelList([Kernel.gbf])
ran.setP1List(map(lambda x:sdExp**x,xrange(sdExpHigh+1)))
self.addRange(ran)
def addSigmoid(self, sExpLow = -3, sExpHigh = 3, sExp = 10.0, oExpLow = -3, oExpHigh = 3, oExp = 10.0, cExpLow = -3, cExpHigh = 3, cExp = 10.0, rebalance = True):
"""Add sigmoids to the set - the parameters use s for the scale component and o for the offset component; these parameters use the same exponential scheme as for c and others. Same c controls as for addLinear."""
ran = ParamsRange()
ran.setCList(map(lambda x:cExp**x,xrange(cExpLow,cExpHigh+1)))
ran.setRebalanceList([rebalance])
ran.setKernelList([Kernel.sigmoid])
ran.setP1List(map(lambda x:oExp**x,xrange(oExpLow,oExpHigh+1)))
ran.setP2List(map(lambda x:sExp**x,xrange(sExpLow,sExpHigh+1)))
self.addRange(ran)
def permutations(self):
for ran in self.ranges:
for p in ran:
yield p
def __iter__(self):
return self.permutations()
| [
[
1,
0,
0.071,
0.0055,
0,
0.66,
0,
206,
0,
1,
0,
0,
206,
0,
0
],
[
1,
0,
0.0765,
0.0055,
0,
0.66,
0.25,
206,
0,
1,
0,
0,
206,
0,
0
],
[
1,
0,
0.0874,
0.0055,
0,
0.6... | [
"from params import Kernel",
"from params import Params",
"from copy import copy",
"class ParamsRange:\n \"\"\"A parameters object where each variable takes a list rather than a single value - it then pretends to be a list of Params objects, which consists of every combination implied by the ranges.\"\"\"\n ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2010 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 svm
from utils import doc_gen
# Setup...
doc = doc_gen.DocGen('svm', 'Support Vector Machine', 'Support vector machines, classification only')
doc.addFile('readme.txt', 'Overview')
# Functions...
doc.addFunction(svm.solvePair)
doc.addFunction(svm.looPair)
doc.addFunction(svm.looPairSelect)
# Classes...
doc.addClass(svm.Kernel)
doc.addClass(svm.Params)
doc.addClass(svm.ParamsRange)
doc.addClass(svm.ParamsSet)
doc.addClass(svm.Dataset)
doc.addClass(svm.Model)
doc.addClass(svm.MultiModel)
| [
[
1,
0,
0.3684,
0.0263,
0,
0.66,
0,
75,
0,
1,
0,
0,
75,
0,
0
],
[
1,
0,
0.4211,
0.0263,
0,
0.66,
0.0769,
970,
0,
1,
0,
0,
970,
0,
0
],
[
14,
0,
0.5526,
0.0263,
0,
0... | [
"import svm",
"from utils import doc_gen",
"doc = doc_gen.DocGen('svm', 'Support Vector Machine', 'Support vector machines, classification only')",
"doc.addFile('readme.txt', 'Overview')",
"doc.addFunction(svm.solvePair)",
"doc.addFunction(svm.looPair)",
"doc.addFunction(svm.looPairSelect)",
"doc.addC... |
# -*- coding: utf-8 -*-
# Copyright 2010 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 smo import SMO
import copy
import numpy
def looPair(params,data):
"""Given a parameters object and a pair of data matrix and y (As returned by dataset.getTrainData.) this returns a (good) approximation of the leave one out negative log likellihood, and a model trained on *all* the data as a pair. Makes the assumption that losing a non-supporting vector does not require retraining, which is correct the vast majority of the time, and as a bonus avoids retrainning for most of the data, making this relativly fast."""
dataMatrix,y = data
# First train on all the data...
smo = SMO()
smo.setParams(params)
smo.setData(dataMatrix,y)
smo.solve()
onAll = copy.deepcopy(smo.getModel())
indices = smo.getIndices()
# Collate statistics for all the non-supporting vectors...
scores = onAll.multiClassify(dataMatrix)*y
correct = (scores>0).sum() - (scores[indices]>0).sum()
# Now iterate and retrain without each of the supporting vectors, collating the statistics...
for i in xrange(indices.shape[0]):
index = indices[i]
noIndex = numpy.array(range(index)+range(index+1,y.shape[0]))
smo.setData(dataMatrix[noIndex],y[noIndex])
smo.solve()
res = smo.getModel().classify(dataMatrix[index]) * y[index]
if res>0: correct += 1
# Return the loo and initial trainning on all the data...
return (float(correct)/float(y.shape[0]),onAll)
def looPairRange(params, data, dist = 1.1):
"""Identical to looPair, except you specifiy a distance from the boundary and it retrains for all points in that range, but not for once outside that range. For a value of one, ignoring rounding error, it should be identical to looPair, though in practise you should never do this - dist should always be >1.0. This also has a better than optimisation - if it knows its result is going to be worse than betterThan it gives up and saves computation."""
dataMatrix,y = data
# First train on all the data...
smo = SMO()
smo.setParams(params)
smo.setData(dataMatrix,y)
smo.solve()
onAll = copy.deepcopy(smo.getModel())
# Get set of indices to retrain with, collate statistics for all the non-supporting vectors...
scores = onAll.multiClassify(dataMatrix)*y
indices = numpy.nonzero(scores<dist)[0]
correct = (scores>0).sum() - (scores[indices]>0).sum()
# Now iterate and retrain without each of the supporting vectors, collating the statistics...
for i in xrange(indices.shape[0]):
index = indices[i]
noIndex = numpy.array(range(index)+range(index+1,y.shape[0]))
smo.setData(dataMatrix[noIndex],y[noIndex])
smo.solve()
res = smo.getModel().classify(dataMatrix[index]) * y[index]
if res>0: correct += 1
# Return the loo and initial trainning on all the data...
return (float(correct)/float(y.shape[0]),onAll)
def looPairBrute(params,data):
"""Same as looPair but does it brute force style - no approximation here."""
dataMatrix,y = data
# First train on all the data...
smo = SMO()
smo.setParams(params)
smo.setData(dataMatrix,y)
smo.solve()
onAll = copy.deepcopy(smo.getModel())
# Now iterate and retrain without each of the vectors, collating the statistics...
correct = 0
for i in xrange(y.shape[0]):
noIndex = numpy.array(range(i)+range(i+1,y.shape[0]))
smo.setData(dataMatrix[noIndex],y[noIndex])
smo.solve()
res = smo.getModel().classify(dataMatrix[i]) * y[i]
if res>0: correct += 1
# Return the loo and initial trainning on all the data...
return (float(correct)/float(y.shape[0]),onAll)
def looPairSelect(paramsList,data):
"""Given an iterator of parameters this returns a pair of the loo score and model of the best set of parameters - just loops over looPair."""
best = None
for params in paramsList:
res = looPair(params,data)
if best==None or res[0]>best[0]:
best = res
return best
| [
[
1,
0,
0.1161,
0.0089,
0,
0.66,
0,
105,
0,
1,
0,
0,
105,
0,
0
],
[
1,
0,
0.1339,
0.0089,
0,
0.66,
0.1667,
739,
0,
1,
0,
0,
739,
0,
0
],
[
1,
0,
0.1429,
0.0089,
0,
... | [
"from smo import SMO",
"import copy",
"import numpy",
"def looPair(params,data):\n \"\"\"Given a parameters object and a pair of data matrix and y (As returned by dataset.getTrainData.) this returns a (good) approximation of the leave one out negative log likellihood, and a model trained on *all* the data as... |
# -*- coding: utf-8 -*-
# Copyright 2010 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.
# Some code used by the smo module...
cacheCode = """
// Right now only provides the most basic of caching, by pre-caclulating the diagonal, which is admitedly used very heavilly...
npy_intp * dmSize;
double * dm;
double * diagBuff;
void cacheBegin(npy_intp * dmSizeIn, double * dmIn)
{
dmSize = dmSizeIn;
dm = dmIn;
diagBuff = (double*)malloc(dmSize[0] * sizeof(double));
for (int i=0;i<dmSize[0];i++)
{
double * vec = dm + i*dmSize[1];
diagBuff[i] = kernel(dmSize[1], vec, vec);
}
}
double cacheK(int a,int b) // Indices of two vectors from the data matrix.
{
if (a!=b)
{
return kernel(dmSize[1], dm + a*dmSize[1], dm + b*dmSize[1]);
}
else
{
return diagBuff[a];
}
}
void cacheEnd()
{
free(diagBuff);
}
"""
smoCoreCode = """
// Constant...
const double eps = 1e-3;
// Initialise the cache...
cacheBegin(Ndm,dm);
// Iterate until convergance...
int pv1 = -1;
int pv2 = -1;
//long long int maxIter = ((long long int)Ny[0])*((long long int)Ny[0])*2; // Cap iters, to avoid any chance of it getting stuck in an infinite loop if a cyclic set of edits were to appear. Note that this number is really high - typically it going to need a few more than Ny[0] iterations.
//for (long long int iter=0;iter<maxIter;iter++)
while (true)
{
// Determine which pair we are going to optimise, break if all are optimised...
double maxG = -1e100;
double minG = 1e100;
double minObj = 1e100;
// Select the first member of the pair, v1...
int v1 = -1;
for (int i=0;i<Ny[0];i++)
{
double c = (y[i]<0)?cn:cp;
if (((y[i]>0)&&(alpha[i]<c))||((y[i]<0)&&(alpha[i]>0.0)))
{
double g = -y[i] * gradient[i];
if (g >= maxG)
{
v1 = i;
maxG = g;
}
}
}
// Select the second member of the pair, v2...
int v2 = -1;
double a;
for (int i=0;i<Ny[0];i++)
{
double c = (y[i]<0)?cn:cp;
if (((y[i]>0)&&(alpha[i]>0.0))||((y[i]<0)&&(alpha[i]<c)))
{
double g = -y[i] * gradient[i];
if (g <= minG) minG = g;
double b = maxG - g;
if (b>0)
{
double na = cacheK(v1,v1) + cacheK(i,i) - 2.0*cacheK(v1,i);
if (na<=0.0) na = 1e12;
double obj = -(b*b)/a;
if (obj <= minObj)
{
if ((i!=pv2)&&(v1!=pv1)) // Prevents it selecting the same pair twice in a row - this can cause an infinite loop.
{
v2 = i;
a = na;
minObj = obj;
}
}
}
}
}
// Check for convergance/algorithm has done its best...
if (v2==-1) break;
if ((maxG-minG)<eps) break;
pv1 = v1;
pv2 = v2;
// Calculate new alpha values, to reduce the objective function...
double b = -y[v1]*gradient[v1] + y[v2]*gradient[v2];
double oldA1 = alpha[v1];
double oldA2 = alpha[v2];
alpha[v1] += y[v1]*b/a;
alpha[v2] -= y[v2]*b/a;
// Correct for alpha being out of range...
double sum = y[v1]*oldA1 + y[v2]*oldA2;
double c = (y[v1]<0)?cn:cp;
if (alpha[v1]<0.0) alpha[v1] = 0.0;
else { if (alpha[v1]>c) alpha[v1] = c; }
alpha[v2] = y[v2] * (sum - y[v1]*alpha[v1]);
c = (y[v2]<0)?cn:cp;
if (alpha[v2]<0.0) alpha[v2] = 0.0;
else { if (alpha[v2]>c) alpha[v2] = c; }
alpha[v1] = y[v1] * (sum - y[v2]*alpha[v2]);
// Update the gradient...
double dA1 = alpha[v1] - oldA1;
double dA2 = alpha[v2] - oldA2;
for (int i=0;i<Ny[0];i++)
{
gradient[i] += y[i] * y[v1] * cacheK(i,v1) * dA1;
gradient[i] += y[i] * y[v2] * cacheK(i,v2) * dA2;
}
}
// Deinitialise the cache...
cacheEnd();
""" | [
[
14,
0,
0.2006,
0.2222,
0,
0.66,
0,
364,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.6667,
0.6728,
0,
0.66,
1,
902,
1,
0,
0,
0,
0,
3,
0
]
] | [
"cacheCode = \"\"\"\n// Right now only provides the most basic of caching, by pre-caclulating the diagonal, which is admitedly used very heavilly...\nnpy_intp * dmSize;\ndouble * dm;\ndouble * diagBuff;\n\nvoid cacheBegin(npy_intp * dmSizeIn, double * dmIn)\n{",
"smoCoreCode = \"\"\"\n// Constant...\n const doubl... |
# -*- coding: utf-8 -*-
# Copyright 2010 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 params import Kernel
from params import Params
from params_sets import ParamsRange
from params_sets import ParamsSet
from dataset import Dataset
from model import Model
from loo import looPair
from loo import looPairRange
from loo import looPairBrute
from loo import looPairSelect
from multiclass import MultiModel
import smo
def solvePair(params,dataset,negLabel,posLabel):
"""Solves for a pair of labels - you provide a parameters object, a data set and the labels to assign to -1 and +1 respectivly. It then returns a Model object."""
s = smo.SMO()
s.setParams(params)
s.setData(dataset.getTrainData(negLabel,posLabel))
s.solve()
return s.getModel()
| [
[
1,
0,
0.3514,
0.027,
0,
0.66,
0,
206,
0,
1,
0,
0,
206,
0,
0
],
[
1,
0,
0.3784,
0.027,
0,
0.66,
0.0833,
206,
0,
1,
0,
0,
206,
0,
0
],
[
1,
0,
0.4054,
0.027,
0,
0.6... | [
"from params import Kernel",
"from params import Params",
"from params_sets import ParamsRange",
"from params_sets import ParamsSet",
"from dataset import Dataset",
"from model import Model",
"from loo import looPair",
"from loo import looPairRange",
"from loo import looPairBrute",
"from loo impor... |
# -*- coding: utf-8 -*-
| [] | [] |
# -*- coding: utf-8 -*-
# Copyright 2010 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 params import *
from smo_aux import *
from model import *
import numpy
from scipy.weave import inline
class SMO:
"""Implimentation of the 'Sequential Minimal Optimization' SVM solving method of Platt, using the WSS 3 pair selection method of Fan, Chen and Lin. This just solves for the alpha values - it is upto the wrapping code to do something useful with them. Makes extensive use of scipy.weave, so you need that working."""
def __init__(self):
"""Initalises the parameters to a suitable default, but does not fill in a dataset - at the very least you will have to provide that."""
self.params = Params()
self.dataMatrix = None
self.y = None
self.model = None
self.alpha = None
def setParams(self, params):
"""Sets the parameters, i.e. which model to fit."""
self.params = params
def getParams(self):
"""Returns the parameters object - by default this is a linear model with a C of 10.0"""
return self.params
def setData(self, dataMatrix, y=None):
"""Sets the data matrix and corresponding y vector of +/- 1 values. If given only one value this function assumes its a tuple of (dataMatrix,y), as returned by the Dataset getTrainData method."""
if y==None:
self.dataMatrix = dataMatrix[0]
self.y = dataMatrix[1]
else:
self.dataMatrix = dataMatrix
self.y = y
assert self.y.shape[0]==self.dataMatrix.shape[0] , 'dataMatrix and feature vector lengths do not match.'
def getDataMatrix(self):
"""Returns the current data matrix, where each row is a feature vector."""
return self.dataMatrix
def getY(self):
"""Returns the y vector, that is the labels for the feature vector."""
return self.y
def solve(self, alpha = None):
"""Solves for the current information and replaces the current model, if any. You can optionally provide an alpha vector of alpha values for each vector - this can speed up convergance if initialised better than the typical zeroed vector."""
# Check for having no samples of one type - handle elegantly...
dm = self.dataMatrix
y = self.y
pCount = numpy.nonzero(y>0)[0].shape[0]
nCount = y.shape[0] - pCount
if pCount==0 or nCount==0:
self.alpha = numpy.zeros(0,dtype=numpy.float_)
if pCount>0: b = 1.0
else: b = -1.0
self.model = Model(self.params, numpy.zeros((0,self.dataMatrix.shape[1]),dtype=numpy.float_), numpy.zeros(0,dtype=numpy.float_), b)
return
# First do the heavy weight task - calculate the alpha weights for the vectors...
support = self.params.getCode()
support += cacheCode
kernelKey = '// Kernel = '+self.params.kernelKey()+'\n'
if alpha==None: alpha = numpy.zeros(self.y.shape[0], dtype=numpy.double)
else: alpha = alpha.copy()
gradient = numpy.ones(self.y.shape[0],dtype=numpy.double)
gradient *= -1.0
if self.params.getRebalance():
r = self.params.getC() * y.shape[0]/(2.0*pCount*nCount)
cp = r * nCount
cn = r * pCount
else:
cp = self.params.getC()
cn = self.params.getC()
inline(kernelKey+smoCoreCode, ['dm','y','alpha','gradient','cp','cn'], support_code = support)
# Now build the model so far, but set b to zero...
self.alpha = alpha
indices = numpy.nonzero(alpha>=1e-3)[0]
self.model = Model(self.params, self.dataMatrix[indices], numpy.asfarray(self.y[indices]) * alpha[indices], 0.0)
# Finally, calculate the b offset value and stuff it into the model - its easier this way as we can use the model to calculate the offsets...
# (Note the below code 'handles' the scenario where all vectors are at 0 or c - this shouldn't happen, but better safe than screwed by numerical error.)
minB = -1e100
maxB = 1e100
actualB = 0.0
numActualB = 0
dec = self.model.multiDecision(self.dataMatrix)
for i in xrange(y.shape[0]):
if self.y[i]<0: cap = cn
else: cap = cp
if alpha[i]<1e-3:
if y[i]<0:
maxB = min((maxB,self.y[i] - dec[i]))
else:
minB = max((minB,self.y[i] - dec[i]))
elif alpha[i]>(cap-1e-3):
if y[i]<0:
minB = max((minB,self.y[i] - dec[i]))
else:
maxB = min((maxB,self.y[i] - dec[i]))
else:
numActualB += 1
actualB += (self.y[i] - dec[i] - actualB) / float(numActualB)
if numActualB>0:
self.model.b = actualB
else:
self.model.b = 0.5*(minB + maxB)
def getModel(self):
"""Returns the model from the last call to solve, or None if solve has never been called."""
return self.model
def getAlpha(self):
"""Returns the alpha vector that the algorithm converged to - can be useful for initialising a new but similar model."""
return self.alpha
def getIndices(self):
"""Returns an array of the indices of the vectors from the input dataset that form the support vectors of the current model, or None if solve has never been called."""
return numpy.nonzero(self.alpha>=1e-3)[0]
| [
[
1,
0,
0.0909,
0.007,
0,
0.66,
0,
206,
0,
1,
0,
0,
206,
0,
0
],
[
1,
0,
0.0979,
0.007,
0,
0.66,
0.2,
699,
0,
1,
0,
0,
699,
0,
0
],
[
1,
0,
0.1049,
0.007,
0,
0.66,
... | [
"from params import *",
"from smo_aux import *",
"from model import *",
"import numpy",
"from scipy.weave import inline",
"class SMO:\n \"\"\"Implimentation of the 'Sequential Minimal Optimization' SVM solving method of Platt, using the WSS 3 pair selection method of Fan, Chen and Lin. This just solves f... |
# 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
class ExemplarSet:
"""An interface for a set of feature vectors, referred to as exemplars - whilst a data matrix will typically be used this allows the possibility of exemplars for which that is impractical, i.e. calculating them on the fly if there is an unreasonable number of features within each exemplar. Also supports the concept of channels, which ties in with the test generation so you can have different generators for each channel. For trainning the 'answer' is stored in its own channel (Note that, because that channel will not exist for novel features it should always be the last channel, so that indexing is consistant, unless it is replaced with a dummy channel.), the type of which will depend on the problem being solved. Also allows the mixing of both continuous and discrete values."""
def exemplars(self):
"""Returns how many exemplars are provided."""
raise NotImplementedError
def channels(self):
"""Returns how many channels of features are provided. They are indexed {0, ..., return-1}."""
raise NotImplementedError
def name(self, channel):
"""Returns a string as a name for a channel - this is optional and provided more for human usage. Will return None if the channel in question has no name."""
return None
def dtype(self, channel):
"""Returns the numpy dtype used for the given channel. numpy.float32 and numpy.int32 are considered to be the standard choices."""
raise NotImplementedError
def features(self, channel):
"""Returns how many features exist for each exemplar for the given channel - they can then be indexed {0, .., return-1} for the given channel."""
raise NotImplementedError
def __getitem__(self, index):
"""Actual data access is via the [] operator, with 3 entities - [channel, exemplar(s), feature(s)]. channel must index the channel, and indicates which channel to get the data from - must always be an integer. exemplars(s) indicates which examples to return and features(s) which features to return for each of the exemplars. For both of these 3 indexing types must be supported - a single integer, a slice, or a numpy array of indexing integers. For indexing integers the system is designed to work such that repetitions are never used, though that is in fact supported most of the time by actual implimentations. The return value must always have the type indicated by the dtype method for the channel in question. If both are indexed with an integer then it will return a single number (But still of the numpy dtype.); if only 1 is an integer a 1D numpy array; and if neither are integers a 2D numpy array, indexed [relative exemplar, relative feature]. Note that this last requirement is not the numpy default, which would actually continue to give a 1D array rather than the 2D subset defined by two sets of indicies."""
raise NotImplementedError
def codeC(self, channel, name):
"""Returns a dictionary containning all the entities needed to access the given channel of the exemplar from within C, using name to provide a unique string to avoid namespace clashes. Will raise a NotImplementedError if not avaliable. `['type'] = The C type of the channel, often 'float'. ['input'] = The input object to be passed into the C code, must be protected from any messing around that scipy.weave might do. ['itype'] = The input type in C, as a string, usually 'PyObject *' or 'PyArrayObject *'. ['get'] = Returns code for a function to get values from the channel of the exemplar; has calling convention <type> <name>_get(<itype> input, int exemplar, int feature). ['exemplars'] = Code for a function to get the number of exemplars; has calling convention int <name>_exemplars(<itype> input). Will obviously return the same value for all channels, so can be a bit redundant. ['features'] = Code for a function that returns how many features the channel has; calling convention is int <name>_features(<itype> input). ['name'] is also provided, which contains the base name handed to this method, for conveniance.`"""
raise NotImplementedError
def listCodeC(self, name):
"""Helper method - returns a tuple indexed by channel that gives the dictionary returned by codeC for each channel in this exemplar. It generates the names using the provided name by adding the number indexing the channel to the end. Happens to by the required input elsewhere."""
return tuple(map(lambda c: self.codeC(c, name+str(c)), xrange(self.channels())))
def tupleInputC(self):
"""Helper method, that can be overriden - returns a tuple containing the inputs needed for the exemplar."""
return tuple(map(lambda c: self.codeC(c, name+str(c))['input'], xrange(self.channels())))
def key(self):
"""Provides a unique string that can be used to hash the results of codeC, to avoid repeated generation. Must be implimented if codeC is implimented."""
raise NotImplementedError
class MatrixES(ExemplarSet):
"""The most common exemplar set - basically what you use when all the feature vectors can be computed and then stored in memory without issue. Contains a data matrix for each channel, where these are provided by the user."""
def __init__(self, *args):
"""Optionally allows you to provide a list of numpy data matrices to by the channels data matrices. Alternativly you can use the add method to add them, one after another, post construction, or some combination of both. All data matrices must be 2D numpy arrays, with the first dimension, indexing the exemplar, being the same size in all cases. (If there is only 1 exemplar then it will accept 1D arrays.)"""
self.dm = list(map(lambda a: a.reshape((1,-1)) if len(a.shape)==1 else a, args))
for dm in self.dm:
assert(len(dm.shape)==2)
assert(dm.shape[0]==self.dm[0].shape[0])
def add(self, dm):
"""Adds a new data matrix of information as another channel. Returns its channel index. If given a 1D matrix assumes that there is only one exemplar and adjusts it accordingly."""
if len(dm.shape)==1: dm = dm.reshape((1,-1))
assert(len(dm.shape)==2)
self.dm.append(dm)
assert(dm.shape[0]==self.dm[0].shape[0])
return len(self.dm)-1
def append(self, *args):
"""Allows you to add exemplars to the structure, by providing a set of data matrices that align with those contained, which contain the new exemplars. Note that this is slow and generally ill advised. If adding a single new feature the arrays can be 1D."""
assert(len(args)==len(self.dm))
for i, (prev, extra) in enumerate(zip(self.dm, args)):
if len(extra.shape)==1: extra = extra.reshape((1,-1))
self.dm[i] = numpy.append(prev, extra, 0)
def exemplars(self):
return self.dm[0].shape[0]
def channels(self):
return len(self.dm)
def dtype(self, channel):
return self.dm[channel].dtype
def features(self, channel):
return self.dm[channel].shape[1]
def __getitem__(self, index):
a = numpy.asarray(index[1]).reshape(-1)
b = numpy.asarray(index[2]).reshape(-1)
if a.shape[0]==1 or b.shape[0]==1: return self.dm[index[0]][index[1],index[2]]
else: return self.dm[index[0]][numpy.ix_(a,b)]
def codeC(self, channel, name):
ret = dict()
inp = self.dm[channel]
if inp.dtype==numpy.float32: dtype = 'float'
elif inp.dtype==numpy.float64: dtype = 'double'
elif inp.dtype==numpy.int32: dtype = 'long'
elif inp.dtype==numpy.int64: dtype = 'long long'
elif inp.dtype==numpy.uint32: dtype = 'unsigned long'
elif inp.dtype==numpy.uint64: dtype = 'unsigned long long'
elif inp.dtype==numpy.int16: dtype = 'short'
elif inp.dtype==numpy.uint16: dtype = 'unsigned short'
elif inp.dtype==numpy.int8: dtype = 'char'
elif inp.dtype==numpy.uint8: dtype = 'unsigned char'
else: raise NotImplementedError
ret['name'] = name
ret['type'] = dtype
ret['input'] = inp
ret['itype'] = 'PyArrayObject *'
ret['get'] = 'inline %s %s_get(PyArrayObject * input, int exemplar, int feature) {return *(%s *)(input->data + exemplar*input->strides[0] + feature*input->strides[1]);}' % (ret['type'], name, ret['type'])
ret['exemplars'] = 'inline int %s_exemplars(PyArrayObject * input) {return input->dimensions[0];}'%name
ret['features'] = 'inline int %s_features(PyArrayObject * input) {return input->dimensions[1];}'%name
return ret
def tupleInputC(self):
return tuple(self.dm)
def key(self):
return 'MatrixES|' + reduce(lambda a,b: a+':'+b, map(lambda d: str(d.dtype), self.dm))
MatrixFS = MatrixES # For backward compatability.
class MatrixGrow(ExemplarSet):
"""A slightly more advanced version of the basic exemplar set that has better support for incrimental learning, as it allows appends to be more efficient. It still assumes that all of the data can be fitted in memory, and makes use of numpy arrays for internal storage."""
def __init__(self, *args):
"""Optionally allows you to provide a list of numpy data matrices to by the channels data matrices. Alternativly you can use the add method to add them, one after another, post construction, or use append to start things going. All data matrices must be 2D numpy arrays, with the first dimension, indexing the exemplar, being the same size in all cases. (If there is only 1 exemplar then it will accept 1D arrays.)"""
# Internal storage is as a list, where each entry in the list is a set of exemplars. The exmplars are represented as a further list, indexed by channel, of 2D data matrices.
if len(args)!=0:
self.dmcList = [list(map(lambda a: a.reshape((1,-1)) if len(a.shape)==1 else a, args))]
for dm in self.dmcList[0]:
assert(len(dm.shape)==2)
assert(dm.shape[0]==self.dm[0].shape[0])
else:
self.dmcList = []
def add(self, dm):
"""Adds a new data matrix of information as another channel. Returns its channel index. If given a 1D matrix assumes that there is only one exemplar and adjusts it accordingly."""
self.make_compact()
if len(dm.shape)==1: dm = dm.reshape((1,-1))
assert(len(dm.shape)==2)
if len(dmcList)==0: dmcList.append([])
self.dmcList[0].append(dm)
assert(dm.shape[0]==self.dmcList[0][0].shape[0])
return len(self.dmcList[0])-1
def append(self, *args):
"""Allows you to add exemplars to the structure, by providing a set of data matrices that align with those contained, which contain the new exemplars. If adding a single new exemplar the arrays can be 1D."""
args = map(lambda dm: dm if len(dm.shape)!=1 else dm.reshape((1,-1)), args)
for dm in args:
assert(len(dm.shape)==2)
assert(dm.shape[0]==args[0].shape[0])
if len(self.dmcList)!=0:
assert(len(args)==len(self.dmcList[0]))
for i, dm in enumerate(args):
assert(dm.dtype==self.dmcList[0][i].dtype)
assert(dm.shape[1]==self.dmcList[0][i].shape[1])
self.dmcList.append(args)
def exemplars(self):
return sum(map(lambda dmc: dmc[0].shape[0], self.dmcList))
def channels(self):
return len(self.dmcList[0]) if len(self.dmcList)!=0 else 0
def dtype(self, channel):
return self.dmcList[0][channel].dtype
def features(self, channel):
return self.dmcList[0][channel].shape[1]
def make_compact(self):
"""Internal method really - converts the data structure so that len(dmcList)==1, by concatenating arrays as needed."""
if len(self.dmcList)>1:
rep = []
for i in xrange(len(self.dmcList[0])):
dml = map(lambda dmc: dmc[i], self.dmcList)
dm = numpy.concatenate(dml, axis=0)
rep.append(dm)
self.dmcList = [rep]
def __getitem__(self, index):
self.make_compact()
a = numpy.asarray(index[1]).reshape(-1)
b = numpy.asarray(index[2]).reshape(-1)
if not isinstance(index[1],numpy.ndarray) or not isinstance(index[2],numpy.ndarray): return self.dmcList[0][index[0]][index[1],index[2]]
else: return self.dmcList[0][index[0]][numpy.ix_(a,b)]
def codeC(self, channel, name):
self.make_compact()
ret = dict()
inp = self.dmcList[0][channel]
if inp.dtype==numpy.float32: dtype = 'float'
elif inp.dtype==numpy.float64: dtype = 'double'
elif inp.dtype==numpy.int32: dtype = 'long'
elif inp.dtype==numpy.int64: dtype = 'long long'
elif inp.dtype==numpy.uint32: dtype = 'unsigned long'
elif inp.dtype==numpy.uint64: dtype = 'unsigned long long'
elif inp.dtype==numpy.int16: dtype = 'short'
elif inp.dtype==numpy.uint16: dtype = 'unsigned short'
elif inp.dtype==numpy.int8: dtype = 'char'
elif inp.dtype==numpy.uint8: dtype = 'unsigned char'
else: raise NotImplementedError
ret['name'] = name
ret['type'] = dtype
ret['input'] = inp
ret['itype'] = 'PyArrayObject *'
ret['get'] = 'inline %s %s_get(PyArrayObject * input, int exemplar, int feature) {return *(%s *)(input->data + exemplar*input->strides[0] + feature*input->strides[1]);}' % (ret['type'], name, ret['type'])
ret['exemplars'] = 'inline int %s_exemplars(PyArrayObject * input) {return input->dimensions[0];}'%name
ret['features'] = 'inline int %s_features(PyArrayObject * input) {return input->dimensions[1];}'%name
return ret
def tupleInputC(self):
self.make_compact()
return tuple(self.dmcList[0])
def key(self):
self.make_compact()
return 'MatrixGrow|' + reduce(lambda a,b: a+':'+b, map(lambda d: str(d.dtype), self.dmcList[0])) | [
[
1,
0,
0.043,
0.0039,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
3,
0,
0.1406,
0.168,
0,
0.66,
0.25,
448,
0,
10,
0,
0,
0,
0,
12
],
[
8,
1,
0.0625,
0.0039,
1,
0.25... | [
"import numpy",
"class ExemplarSet:\n \"\"\"An interface for a set of feature vectors, referred to as exemplars - whilst a data matrix will typically be used this allows the possibility of exemplars for which that is impractical, i.e. calculating them on the fly if there is an unreasonable number of features wit... |
# 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
class ProbCat:
"""A standard interface for a probabilistic classifier. Provides an interface for a system where you add a bunch of 'samples' and their categories, and can then request the probability that new samples belong to each category. Designed so it can be used in an incrimental manor - if a classifier does not support that it is responsible for prentending that it does, by retrainning each time it is used after new data has been provided. Being probabilistic the interface forces the existance of a prior - it can be a fake-prior that is never used or updated, but it must exist. Obviously it being handled correctly is ideal. The 'sample' object often passed in is category specific, though in a lot of cases will be something that can be interpreted as a 1D numpy array, i.e. a feature vector. The 'cat' object often passed in represents a category - whilst it can be model specific it is generally considered to be a python object that is hashable and can be tested for equality. Being hashable is important to allow it to key a dictionary."""
def priorAdd(self, sample):
"""Adds a sample to the prior; being that it is the prior no category is provided with. This can do nothing, but is typically used to build a prior over samples when the category is unknown."""
raise NotImplementedError('priorAdd has not been implimented.')
def add(self, sample, cat):
"""Given a sample and its category this updates the model, hopefully incrimentally during this method call, but otherwise when the model is next needed. Stuff added to a specific category should *not* be added to the prior by this method - a user can decide to do that by additionally calling priorAdd if they so choose."""
raise NotImplementedError('add has not been implimented.')
def getSampleTotal(self):
"""Returns the total number of samples that have been provided to train the classifier (Does not include the samples provided to build the prior.)."""
raise NotImplementedError('add has not been implimented.')
def getCatTotal(self):
"""Returns the total number of categories that have been provided to the classifier."""
raise NotImplementedError('getCatTotal has not been implimented.')
def getCatList(self):
"""Returns a list of all the categories that the classifier has examples of."""
raise NotImplementedError('getCatList has not been implimented.')
def getCatCounts(self):
"""Returns a dictionary indexable by each of the categories that goes to how many samples of that category have been provided. The returned dictionary must not be edited by the user."""
raise NotImplementedError('getCatCounts has not been implimented.')
def listMode(self):
"""Returns true if list mode is supported, False otherwise. List mode basically provides some of the same methods, with the 'List' postfix, where the return is a list of answers which the usual method would provide just one of. Used when there are multiple estimates, e.g. multiple draws from a posterior on the model."""
return False
def getDataProb(self, sample, state = None):
"""Returns a dictionary indexed by the various categories, with the probabilities of the sample being drawn from the respective categories. Must also include an entry indexed by 'None' that represents the probability of the sample comming from the prior. Note that this is P(data|category,model) - you probably want it reversed, which requires Bayes rule be applied. state is an optional dictionary - if you are calling this repeatedly on the same sample, e.g. during incrimental learning, then state allows an algorithm to store data to accelerate future calls. There should be a dictionary for each sample, and it should be empty on the first call. The implimentation will presume that the sample is identical for each call but that the model will not be, though as it would typically be used for incrimental learning the speed up can be done under the assumption that the model has only changed a little bit."""
ret = dict()
for key, value in self.getDataNLL(sample, state).iteritems():
ret[key] = math.exp(-value)
return ret
def getDataNLL(self, sample, state = None):
"""Identical to getDataProb, except it returns negative log liklihood instead of probabilities. Default implimentation converts the return value of getDataProb, so either that or this needs to be overriden."""
ret = dict()
for key, value in self.getDataProb(sample, state).iteritems():
ret[key] = -math.log(max(value,1e-64))
return ret
def getDataProbList(self, sample, state = None):
"""Is only implimented if listMode returns True. Does the same things as getDataProb, but returns a list of answers."""
def convert(dic):
ret = dict()
for key, value in dic.iteritems():
ret[key] = math.exp(-value)
return ret
return map(convert, self.getDataNLLList(sample, state))
def getDataNLLList(self, sample, state = None):
"""The negative log liklihood version of getDataProbList."""
def convert(dic):
ret = dict()
for key, value in dic.iteritems():
ret[key] = -math.log(max(value,1e-64))
return ret
return map(convert, self.getDataProbList(sample, state))
def getProb(self, sample, weight = False, conc = None, state = None):
"""This calls through to getDataProb and then applies Bayes rule to return a dictionary of values representing P(data,category|model) = P(data|category,model)P(category). Note that whilst the two terms going into the return value will be normalised the actual return value will not - you will typically normalise to get P(category|data,model). The weight parameter indicates the source of P(class) - False (The default) indicates to use a uniform prior, True to weight by the number of instances of each category that have been provided to the classifier. Alternativly a dictionary indexed by the categories can be provided of weights, which will be normalised and used. By default the prior probability is ignored, but if a concentration (conc) value is provided it assumes a Dirichlet process, and you will have an entry in the return value, indexed by None, indicating the probability that it belongs to a previously unhandled category. For normalisation purposes conc is always assumed to be in relation to the number of samples that have been provided to the classifier, regardless of weight. state is passed through to the getDataProb call."""
# Get the data probabilities...
dprob = self.getDataProb(sample, state)
# Calculate the class probabilities, including normalisation and the inclusion of conc if need be...
if weight==False: cprob = dict(map(lambda c: (c,1.0), self.getCatList()))
elif weight==True: cprob = dict(self.getCatCounts())
else: cprob = dict(weight)
norm = float(sum(cprob.itervalues()))
if conc!=None: # Adjust norm so it all sums to 1.
conc = float(conc) / (self.getSampleTotal() + conc)
norm /= 1.0 - conc
for cat in cprob.iterkeys(): cprob[cat] /= norm
if conc!=None: cprob[None] = conc
# Multiply it all out and return...
ret = dict(cprob)
for cat in ret.iterkeys():
ret[cat] *= dprob[cat]
return ret
def getNLL(self, sample, weight = False, conc = None, state = None):
"""Negative log liklihood equivalent of getProb."""
# Get the data nll...
dprob = self.getDataNLL(sample, state)
# Calculate the class probabilities, including normalisation and the inclusion of conc if need be...
if weight==False: cprob = dict(map(lambda c: (c,1.0), self.getCatList()))
elif weight==True: cprob = dict(self.getCatCounts())
else: cprob = dict(weight)
norm = float(sum(cprob.itervalues()))
if conc!=None: # Adjust norm so it all sums to 1.
conc = float(conc) / (self.getSampleTotal() + conc)
norm /= 1.0 - conc
norm = math.log(max(norm,1e-64))
for cat in cprob.iterkeys(): cprob[cat] = norm - math.log(cprob[cat])
if conc!=None: cprob[None] = -math.log(max(conc,1e-64))
# Multiply it all out and return...
ret = dict(cprob)
for cat in ret.iterkeys():
ret[cat] += dprob[cat]
return ret
def getProbList(self, sample, weight = False, conc = None, state = None):
"""List version of getProb, will only work if listMode returns True. Same as getProb but it returns a list of answers, as samples of a possible answer."""
def work(dprob):
if weight==False: cprob = dict(map(lambda c: (c,1.0), self.getCatList()))
elif weight==True: cprob = dict(self.getCatCounts())
else: cprob = dict(weight)
norm = float(sum(cprob.itervalues()))
if conc!=None: # Adjust norm so it all sums to 1.
conc = float(conc) / (self.getSampleTotal() + conc)
norm /= 1.0 - conc
for cat in cprob.iterkeys(): cprob[cat] /= norm
if conc!=None: cprob[None] = conc
# Multiply it all out and return...
ret = dict(cprob)
for cat in ret.iterkeys():
ret[cat] *= dprob[cat]
return ret
return map(work, self.getDataProbList(sample, state))
def getNLLList(self, sample, weight = False, conc = None, state = None):
"""Negative log liklihood version of getProbList"""
def work(dprob):
if weight==False: cprob = dict(map(lambda c: (c,1.0), self.getCatList()))
elif weight==True: cprob = dict(self.getCatCounts())
else: cprob = dict(weight)
norm = float(sum(cprob.itervalues()))
if conc!=None: # Adjust norm so it all sums to 1.
conc = float(conc) / (self.getSampleTotal() + conc)
norm /= 1.0 - conc
norm = math.log(max(norm,1e-64))
for cat in cprob.iterkeys(): cprob[cat] = norm - math.log(cprob[cat])
if conc!=None: cprob[None] = -math.log(max(conc,1e-64))
# Multiply it all out and return...
ret = dict(cprob)
for cat in ret.iterkeys():
ret[cat] += dprob[cat]
return ret
return map(work, self.getDataNLLList(sample, state))
def getCat(self, sample, weight = False, conc = None, state = None):
"""Simply calls through to getNLL and returns the category with the highest probability. If conc is provided it can be None, to indicate a new category is more likelly than any of the existing ones. A simple conveniance method. state is passed through to the getDataProb call."""
nll = self.getNLL(sample, weight, conc, state)
best = None
ret = None
for cat, p in nll.iteritems():
if best==None or p<best:
best = p
ret = cat
return ret
def getCatList(self, sample, weight = False, conc = None, state = None):
"""List version of getCat, will only work if listMode returns True. Same as getCat but it returns a list of answers, as samples of a possible answer."""
def work(nll):
best = None
ret = None
for cat, p in prob.iteritems():
if best==None or p<best:
best = p
ret = cat
return ret
return map(work, self.getNLLList(sample, weight, conc, state))
| [
[
1,
0,
0.0429,
0.0048,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
3,
0,
0.531,
0.9429,
0,
0.66,
1,
432,
0,
22,
0,
0,
0,
0,
99
],
[
8,
1,
0.0667,
0.0048,
1,
0.88,
... | [
"import math",
"class ProbCat:\n \"\"\"A standard interface for a probabilistic classifier. Provides an interface for a system where you add a bunch of 'samples' and their categories, and can then request the probability that new samples belong to each category. Designed so it can be used in an incrimental manor... |
# 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 numpy
from kde_inc.kde_inc import KDE_INC
from prob_cat import ProbCat
class ClassifyKDE(ProbCat):
"""A classifier that uses the incrimental kernel density estimate model for each category. It keeps a 'psuedo-prior', a KDE_INC with an (optionally) larger variance that contains all the samples. Uses entities that can index a dictionary for categories."""
def __init__(self, prec, cap = 32, mult = 1.0):
"""You provide the precision that is to be used (As a 2D numpy array, so it implicitly provides the number of dimensions.), the cap on the number of components in the KDE_INC objects and the multiplier for the standard deviation of the components in the 'psuedo-prior'."""
self.prec = numpy.array(prec, dtype=numpy.float32)
self.cap = cap
self.mult = mult
self.prior = KDE_INC(self.prec / (self.mult*self.mult), self.cap)
self.cats = dict() # Dictionary indexed by category going to the associated KDE_INC object.
self.counts = None
def setPrec(self, prec):
"""Changes the precision matrix - must be called before any samples are added, and must have the same dimensions as the current one."""
self.prec = numpy.array(prec, dtype=numpy.float32)
self.prior.setPrec(self.prec / (self.mult*self.mult))
def priorAdd(self, sample):
self.prior.add(sample)
def add(self, sample, cat):
if cat not in self.cats: self.cats[cat] = KDE_INC(self.prec, self.cap)
self.cats[cat].add(sample)
self.counts = None
def getSampleTotal(self):
return sum(map(lambda mm: mm.samples(), self.cats.itervalues()))
def getCatTotal(self):
return len(self.cats)
def getCatList(self):
return self.cats.keys()
def getCatCounts(self):
if self.counts==None:
self.counts = dict()
for cat, mm in self.cats.iteritems():
self.counts[cat] = mm.samples()
return self.counts
def getDataProb(self, sample, state = None):
ret = dict()
ret[None] = self.prior.prob(sample)
for cat, mm in self.cats.iteritems(): ret[cat] = mm.prob(sample)
return ret
def getDataNLL(self, sample, state = None):
ret = dict()
ret[None] = self.prior.nll(sample)
for cat, mm in self.cats.iteritems(): ret[cat] = mm.nll(sample)
return ret
| [
[
1,
0,
0.1467,
0.0133,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.16,
0.0133,
0,
0.66,
0.3333,
917,
0,
1,
0,
0,
917,
0,
0
],
[
1,
0,
0.1867,
0.0133,
0,
0.... | [
"import numpy",
"from kde_inc.kde_inc import KDE_INC",
"from prob_cat import ProbCat",
"class ClassifyKDE(ProbCat):\n \"\"\"A classifier that uses the incrimental kernel density estimate model for each category. It keeps a 'psuedo-prior', a KDE_INC with an (optionally) larger variance that contains all the s... |
# 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 random
import numpy
import numpy.random
import scipy.special
from gcp import gcp
class DPGMM:
"""A Dirichlet process Gaussian mixture model, implimented using the mean-field variational method, with the stick tying rather than capping method such that incrimental usage works. For those unfamiliar with Dirichlet processes the key thing to realise is that each stick corresponds to a mixture component for density estimation or a cluster for clustering, so the stick cap is the maximum number of these entities (Though it can choose to use less sticks than supplied.). As each stick has a computational cost standard practise is to start with a low number of sticks and then increase the count, updating the model each time, until no improvement to the model is obtained with further sticks. Note that because the model is fully Bayesian the output is in fact a probability distribution over the probability distribution from which the data is drawn, i.e. instead of the point estimate of a Gaussian mixture model you get back a probability distribution from which you can draw a Gaussian mixture model, though shortcut methods are provided to get the probability/component membership probability of features. Regarding the model it actually has an infinite number of sticks, but as computers don't have an infinite amount of memory or computation the sticks count is capped. The infinite number of sticks past the cap are still modeled in a limited manor, such that you can get the probability in clustering of a sample/feature belonging to an unknown cluster (i.e. one of the infinite number past the stick cap.). It also means that there is no explicit cluster count, as it is modelling a probability distribution over the number of clusters - if you need a cluster count the best choice is to threshold on the component weights, as returned by sampleMixture(...) or intMixture(...), i.e. keep only thise that are higher than a percentage of the highest weight."""
def __init__(self, dims, stickCap = 1):
"""You initialise with the number of dimensions and the cap on the number of sticks to have. Note that the stick cap should be high enough for it to represent enough components, but not so high that you run out of memory. The better option is to set the stick cap to 1 (The default) and use the solve grow methods, which in effect find the right number of sticks. Alternativly if only given one parameter of the same type it acts as a copy constructor."""
if isinstance(dims, DPGMM):
self.dims = dims.dims
self.stickCap = dims.stickCap
self.data = map(lambda x: x.copy(), dims.data)
self.prior = gcp.GaussianPrior(dims.prior)
self.priorT = gcp.StudentT(dims.priorT) if dims.priorT!=None else None
self.n = map(lambda x: gcp.GaussianPrior(x), dims.n)
self.beta = dims.beta.copy()
self.alpha = dims.alpha.copy()
self.v = dims.v.copy()
self.z = None if dims.z==None else dims.z.copy()
self.skip = dims.skip
self.epsilon = dims.epsilon
self.nT = map(lambda x: None if x==None else gcp.StudentT(x), dims.nT)
self.vExpLog = dims.vExpLog.copy()
self.vExpNegLog = dims.vExpNegLog.copy()
else:
self.dims = dims
self.stickCap = stickCap
self.data = [] # A list containing data matrices - used to collate all the samples ready for processing. Before processing they are all appended into a single data matrix, such that this list is of length 1.
self.prior = gcp.GaussianPrior(self.dims) # The prior over the mixture components.
self.priorT = None
self.n = map(lambda _: gcp.GaussianPrior(self.dims), xrange(self.stickCap)) # The mixture components, one for each stick.
self.beta = numpy.ones(2, dtype=numpy.float32) # The two parameters (Typically named alpha & beta) for the Gamma distribution prior over alpha.
self.alpha = numpy.ones(2, dtype=numpy.float32) # The parameters for the Gamma distribution that represents the current distribution over alpha - basically beta updated with the current stick configuration.
self.v = numpy.ones((self.stickCap,2), dtype=numpy.float32) # Each [i,:] of this array represents the two parameters of the beta distribution over the strick breaking weight for the relevant mixture component.
self.z = None # The matrix of multinomials over stick-assignment for each sample, aligned with the data matrix. In the case of incrimental use will not necessarily be complete.
self.skip = 0 # Number of samples at the start of the data matrix to not bother updating - useful to speed things up with incrimental learning.
self.epsilon = 1e-4 # Amount of change below which it stops iterating.
# The cache of stuff kept around for speed...
self.nT = [None]*self.stickCap # The student T distribution associated with each Gaussian.
self.vExpLog = numpy.empty(self.stickCap, dtype=numpy.float32) # The expected value of the logorithm of each v.
self.vExpNegLog = numpy.empty(self.stickCap, dtype=numpy.float32) # The expected value of the logarithm of 1 minus each v.
self.vExpLog[:] = -1.0 # Need these to always be correct - this matches initialisation of v.
self.vExpNegLog[:] = -1.0 # As above.
def incStickCap(self, inc = 1):
"""Increases the stick cap by the given number of entrys. Can be used in collaboration with nllData to increase the number of sticks until insufficient improvement, indicating the right number has been found."""
self.stickCap += inc
self.n += map(lambda _: gcp.GaussianPrior(self.dims), xrange(inc))
self.v = numpy.append(self.v,numpy.ones((inc,2), dtype=numpy.float32),0)
if self.z!=None:
self.z = numpy.append(self.z, numpy.random.mtrand.dirichlet(32.0*numpy.ones(inc), size=self.z.shape[0]), 1)
weight = numpy.random.mtrand.dirichlet(numpy.ones(2), size=self.z.shape[0])
self.z[:,:self.stickCap-inc] *= weight[:,0].reshape((self.z.shape[0],1))
self.z[:,self.stickCap-inc:] *= weight[:,1].reshape((self.z.shape[0],1))
self.nT += [None] * inc
self.vExpLog = numpy.append(self.vExpLog,-1.0*numpy.ones(inc, dtype=numpy.float32))
self.vExpNegLog = numpy.append(self.vExpNegLog,-1.0*numpy.ones(inc, dtype=numpy.float32))
def getStickCap(self):
"""Returns the current stick cap."""
return self.stickCap
def setPrior(self, mean = None, covar = None, weight = None, scale = 1.0):
"""Sets a prior for the mixture components - basically a pass through for the addPrior method of the GaussianPrior class. If None (The default) is provided for the mean or the covar then it calculates these values for the currently contained sample set and uses them. Note that the prior defaults to nothing - this must be called before fitting the model, and if mean/covar are not provided then there must be enough data points to avoid problems. weight defaults to the number of dimensions if not specified. If covar is not given then scale is a multiplier for the covariance matrix - setting it high will soften the prior up and make it consider softer solutions when given less data. Returns True on success, False on failure - failure can happen if there is not enough data contained for automatic calculation (Think singular covariance matrix). This must be called before any solve methods are called."""
# Handle mean/covar being None...
if mean==None or covar==None:
inc = gcp.GaussianInc(self.dims)
dm = self.getDM()
for i in xrange(dm.shape[0]): inc.add(dm[i,:])
ggd = inc.fetch()
if mean==None: mean = ggd.getMean()
if covar==None: covar = ggd.getCovariance() * scale
if numpy.linalg.det(covar)<1e-12: return False
# Update the prior...
self.prior.reset()
self.prior.addPrior(mean, covar, weight)
self.priorT = self.prior.intProb()
return True
def setConcGamma(self, alpha, beta):
"""Sets the parameters for the Gamma prior over the concentration. Note that whilst alpha and beta are used for the parameter names, in accordance with standard terminology for Gamma distributions, they are not related to the model variable names. Default values are (1,1). The concentration parameter controls how much information the model requires to justify using a stick, such that lower numbers result in fewer sticks, higher numbers in larger numbers of sticks. The concentration parameter is learnt from the data, under the Gamma distribution prior set with this method, but this prior can still have a strong effect. If your data is not producing as many clusters as you expect then adjust this parameter accordingly, (e.g. increase alpha or decrease beta, or both.), but don't go too high or it will start hallucinating patterns where none exist!"""
self.beta[0] = alpha
self.beta[1] = beta
def setThreshold(self, epsilon):
"""Sets the threshold for parameter change below which it considers it to have converged, and stops iterating."""
self.epsilon = epsilon
def add(self, sample):
"""Adds either a single sample or several samples - either give a single sample as a 1D array or a 2D array as a data matrix, where each sample is [i,:]. (Sample = feature. I refer to them as samples as that more effectivly matches the concept of this modeling the probability distribution from which the features are drawn.)"""
sample = numpy.asarray(sample, dtype=numpy.float32)
if len(sample.shape)==1:
self.data.append(numpy.reshape(sample, (1,self.dims)))
else:
assert(len(sample.shape)==2)
assert(sampler.shape[1]==self.dims)
self.data.append(sample)
def getDM(self):
"""Returns a data matrix containing all the samples that have been added."""
if len(self.data)==1: return self.data[0]
if len(self.data)==0: return None
self.data = [numpy.vstack(self.data)]
return self.data[0]
def size(self):
"""Returns the number of samples that have been added."""
dm = self.getDM()
if dm!=None: return dm.shape[0]
else: return 0
def lock(self, num=0):
"""Prevents the algorithm updating the component weighting for the first num samples in the database - potentially useful for incrimental learning if in a rush. If set to 0, the default, everything is updated."""
self.skip = num
def solve(self, iterCap=None):
"""Iterates updating the parameters until the model has converged. Note that the system is designed such that you can converge, add more samples, and converge again, i.e. incrimental learning. Alternativly you can converge, add more sticks, and then convegre again without issue, which makes finding the correct number of sticks computationally reasonable.. Returns the number of iterations required to acheive convergance. You can optionally provide a cap on the number of iterations it will perform."""
# Deal with the z array being incomplete - enlarge/create as needed. Random initialisation is used...
dm = self.getDM()
if self.z==None or self.z.shape[0]<dm.shape[0]:
newZ = numpy.empty((dm.shape[0],self.stickCap), dtype=numpy.float32)
if self.z==None: offset = 0
else:
offset = self.z.shape[0]
newZ[:offset,:] = self.z
self.z = newZ
self.z[offset:,:] = numpy.random.mtrand.dirichlet(32.0*numpy.ones(self.stickCap), size=self.z.shape[0]-offset) # 32 is to avoid extreme values, which can lock it in place, without the distribution being too flat as to cause problems converging.
# Iterate until convergance...
prev = self.z.copy()
iters = 0
while True:
iters += 1
# Update the concentration parameter...
self.alpha[0] = self.beta[0] + self.stickCap
self.alpha[1] = self.beta[1] - self.vExpNegLog.sum()
# Record the expected values of a stick given the prior alone - needed to normalise the z values...
expLogStick = -scipy.special.psi(1.0 + self.alpha[0]/self.alpha[1])
expNegLogStick = expLogStick
expLogStick += scipy.special.psi(1.0)
expNegLogStick += scipy.special.psi(self.alpha[0]/self.alpha[1])
# Update the stick breaking weights...
self.v[:,0] = 1.0
self.v[:,1] = self.alpha[0]/self.alpha[1]
sums = self.z.sum(axis=0)
self.v[:,0] += sums
self.v[:,1] += self.z.shape[0]
self.v[:,1] -= numpy.cumsum(sums)
# Calculate the log expectations on the stick breaking weights...
self.vExpLog[:] = -scipy.special.psi(self.v.sum(axis=1))
self.vExpNegLog[:] = self.vExpLog
self.vExpLog[:] += scipy.special.psi(self.v[:,0])
self.vExpNegLog[:] += scipy.special.psi(self.v[:,1])
# Update the Gaussian conjugate priors, extracting the student-t distributions as well...
for k in xrange(self.stickCap):
self.n[k].reset()
self.n[k].addGP(self.prior)
self.n[k].addSamples(dm, self.z[:,k])
self.nT[k] = self.n[k].intProb()
# Update the z values...
prev[self.skip:,:] = self.z[self.skip:,:]
vExpNegLogCum = self.vExpNegLog.cumsum()
base = self.vExpLog.copy()
base[1:] += vExpNegLogCum[:-1]
self.z[self.skip:,:] = numpy.exp(base).reshape((1,self.stickCap))
for k in xrange(self.stickCap):
self.z[self.skip:,k] *= self.nT[k].batchProb(dm[self.skip:,:])
norm = self.priorT.batchProb(dm[self.skip:,:])
norm *= math.exp(expLogStick + vExpNegLogCum[-1]) / (1.0 - math.exp(expNegLogStick))
self.z[self.skip:,:] /= (self.z[self.skip:,:].sum(axis=1) + norm).reshape((self.z.shape[0]-self.skip,1))
# Check for convergance...
change = numpy.abs(prev[self.skip:,:]-self.z[self.skip:,:]).sum(axis=1).max()
if change<self.epsilon: break
if iters==iterCap: break
# Return the number of iterations that were required to acheive convergance...
return iters
def solveGrow(self, iterCap=None):
"""This method works by solving for the current stick cap, and then it keeps increasing the stick cap until there is no longer an improvement in the model quality. If using this method you should probably initialise with a stick cap of 1. By using this method the stick cap parameter is lost, and you no longer have to guess what a good value is."""
it = 0
prev = None
while True:
it += self.solve(iterCap)
value = self.nllData()
if prev==None or value<prev:
prev = value
self.incStickCap()
else: return it
def sampleMixture(self):
"""Once solve has been called and a distribution over models determined this allows you to draw a specific model. Returns a 2-tuple, where the first entry is an array of weights and the second entry a list of Gaussian distributions - they line up, to give a specific Gaussian mixture model. For density estimation the probability of a specific point is then the sum of each weight multiplied by the probability of it comming from the associated Gaussian. For clustering the probability of a specific point belonging to a cluster is the weight multiplied by the probability of it comming from a specific Gaussian, normalised for all clusters. Note that this includes an additional term to cover the infinite number of terms that follow, which is really an approximation, but tends to be such a small amount as to not matter. Be warned that if doing clustering a point could be assigned to this 'null cluster', indicating that the model thinks the point belongs to an unknown cluster (i.e. one that it doesn't have enough information, or possibly sticks, to instanciate.)."""
weight = numpy.empty(self.stickCap+1, dtype=numpy.float32)
stick = 1.0
for i in xrange(self.stickCap):
val = random.betavariate(self.v[i,0], self.v[i,1])
weight[i] = stick * val
stick *= 1.0 - val
weight[-1] = stick
gauss = map(lambda x: x.sample(), self.n)
gauss.append(self.prior.sample())
return (weight,gauss)
def intMixture(self):
"""Returns the details needed to calculate the probability of a point given the model (density estimation), or its probability of belonging to each stick (clustering), but with the actual draw of a mixture model from the model integrated out. It is an apprximation, though not a bad one. Basically you get a 2-tuple - the first entry is an array of weights, the second a list of student-t distributions. The weights and distributions align, such that for density estimation the probability for a point is the sum over all entrys of the weight multiplied by the probability of the sample comming from the student-t distribution. The prob method of this class calculates the use of this for a sample directly. For clustering the probability of belonging to each cluster is calculated as the weight multiplied by the probability of comming from the associated student-t, noting that you will need to normalise. stickProb allows you to get this assesment directly. Do not edit the returned value; also, it will not persist if solve is called again. This must only be called after solve is called at least once. Note that an extra element is included to cover the remainder of the infinite number of elements - be warned that a sample could have the highest probability of belonging to this dummy element, indicating that it probably belongs to something for which there is not enough data to infer a reasonable model."""
weights = numpy.empty(self.stickCap+1, dtype=numpy.float32)
stick = 1.0
for i in xrange(self.stickCap):
ev = self.v[i,0] / self.v[i,:].sum()
weights[i] = stick * ev
stick *= 1.0 - ev
weights[-1] = stick
return (weights, self.nT + [self.priorT])
def prob(self, x):
"""Given a sample this returns its probability, with the actual draw from the model integrated out. Must not be called until after solve has been called. This is the density estimate if using this model for density estimation. Will also accept a data matrix, in which case it will return a 1D array of probabilities aligning with the input data matrix."""
x = numpy.asarray(x)
if len(x.shape)==1:
ret = 0.0
stick = 1.0
for i in xrange(self.stickCap):
bp = self.nT[i].prob(x)
ev = self.v[i,0] / self.v[i,:].sum()
ret += bp * stick * ev
stick *= 1.0 - ev
bp = self.priorT.prob(x)
ret += bp * stick
return ret
else:
ret = numpy.zeros(x.shape[0])
stick = 1.0
for i in xrange(self.stickCap):
bp = self.nT[i].batchProb(x)
ev = self.v[i,0] / self.v[i,:].sum()
ret += bp * stick * ev
stick *= 1.0 - ev
bp = self.priorT.batchProb(x)
ret += bp * stick
return ret
def stickProb(self, x):
"""Given a sample this returns its probability of belonging to each of the components, as a 1D array, including a dummy element at the end to cover the infinite number of sticks not being explicitly modeled. This is the probability of belonging to each cluster if using the model for clustering. Must not be called until after solve has been called. Will also accept a data matrix, in which case it will return a matrix with a row for each vector in the input data matrix."""
x = numpy.asarray(x)
if len(x.shape)==1:
ret = numpy.empty(self.stickCap+1, dtype=numpy.float32)
stick = 1.0
for i in xrange(self.stickCap):
bp = self.nT[i].prob(x)
ev = self.v[i,0] / self.v[i,:].sum()
ret[i] = bp * stick * ev
stick *= 1.0 - ev
bp = self.priorT.prob(x)
ret[self.stickCap] = bp * stick
ret /= ret.sum()
return ret
else:
ret = numpy.empty((x.shape[0],self.stickCap+1), dtype=numpy.float32)
stick = 1.0
for i in xrange(self.stickCap):
bp = self.nT[i].batchProb(x)
ev = self.v[i,0] / self.v[i,:].sum()
ret[:,i] = bp * stick * ev
stick *= 1.0 - ev
bp = self.priorT.batchProb(x)
ret[:,self.stickCap] = bp * stick
ret /= ret.sum(axis=1).reshape((-1,1))
return ret
def reset(self, alphaParam = True, vParam = True, zParam = True):
"""Allows you to reset the parameters associated with each variable - good for doing a restart if your doing multiple restarts, or if you suspect it has got stuck in a local minima whilst doing incrimental stuff."""
if alphaParam:
self.alpha[:] = 1.0
if vParam:
self.v[:,:] = 1.0
self.vExpLog[:] = -1.0
self.vExpNegLog[:] = -1.0
if zParam:
self.z = None
def nllData(self):
"""Returns the negative log likelihood of the data given the current distribution over models, with the model integrated out - good for comparing multiple restarts/different numbers of sticks to find which is the best."""
dm = self.getDM()
model = self.intMixture()
probs = numpy.empty((dm.shape[0],model[0].shape[0]), dtype=numpy.float32)
for i, st in enumerate(model[1]):
probs[:,i] = st.batchLogProb(dm) + math.log(model[0][i])
offsets = probs.max(axis=1)
probs -= offsets.reshape((-1,1))
ret = offsets.sum()
ret += numpy.log(numpy.exp(probs).sum(axis=1)).sum()
return -ret
def multiSolve(self, runs, testIter=256):
"""Clones this object a number of times, given by the runs parameter, and then runs each for the testIters parameter number of iterations, to give them time to converge a bit. It then selects the one with the best nllData() score and runs that to convergance, before returning that specific clone. This is basically a simple way of avoiding getting stuck in a really bad local minima, though chances are you will end up in another one, just not a terrible one. Obviously testIter limits the effectivness of this, but as it tends to converge faster if your closer to the correct answer hopefully not by much. (To be honest I have not found this method to be of much use - in testing when this techneque converges to the wrong answer it does so consistantly, indicating that there is insufficient data regardless of initialisation.)"""
best = None
bestNLL = None
for _ in xrange(runs):
clone = DPGMM(self)
clone.solve(testIter)
score = clone.nllData()
if bestNLL==None or score<bestNLL:
best = clone
bestNLL = score
best.solve()
return best
def multiGrowSolve(self, runs):
"""This effectivly does multiple calls of growSolve, as indicated by runs, and returns a clone of this object that has converged to the best solution found. This is without a doubt the best solving techneque provided by this method, just remember to use the default stickCap of 1 when setting up the object. Also be warned - this can take an aweful long time to produce its awesomness. Can return self, if the starting number of sticks is the best (Note that self will always be converged after this method returns.)."""
self.solve()
best = self
bestNLL = self.nllData()
for _ in xrange(runs):
current = self
lastScore = None
while True:
current = DPGMM(current)
current.incStickCap()
current.solve()
score = current.nllData()
if score<bestNLL:
best = current
bestNLL = score
if lastScore!=None and score>lastScore: break
lastScore = score
return best
| [
[
1,
0,
0.0282,
0.0026,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
1,
0,
0.0308,
0.0026,
0,
0.66,
0.1667,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0333,
0.0026,
0,
... | [
"import math",
"import random",
"import numpy",
"import numpy.random",
"import scipy.special",
"from gcp import gcp",
"class DPGMM:\n \"\"\"A Dirichlet process Gaussian mixture model, implimented using the mean-field variational method, with the stick tying rather than capping method such that incrimen... |
# -*- 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.