code
stringlengths
1
1.49M
vector
listlengths
0
7.38k
snippet
listlengths
0
7.38k
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import inspect import hashlib def start_cpp(hash_str = None): """This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>""" frame = inspect.currentframe().f_back info = inspect.getframeinfo(frame) if hash_str==None: return '#line %i "%s"\n'%(info[1],info[0]) else: h = hashlib.md5() h.update(hash_str) hash_val = h.hexdigest() return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
[ [ 1, 0, 0.5, 0.0333, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.5333, 0.0333, 0, 0.66, 0.5, 154, 0, 1, 0, 0, 154, 0, 0 ], [ 2, 0, 0.8333, 0.3667, 0, 0.66, ...
[ "import inspect", "import hashlib", "def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os.path import tempfile import shutil from distutils.core import setup, Extension import distutils.ccompiler import distutils.dep_util try: __default_compiler = distutils.ccompiler.new_compiler() except: __default_compiler = None def make_mod(name, base, source, openCL = False): """Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place.""" if __default_compiler==None: raise Exception('No compiler!') # Work out the various file names - check if we actually need to do anything... if not isinstance(source, list): source = [source] source_path = map(lambda s: os.path.join(base, s), source) library_path = os.path.join(base, __default_compiler.shared_object_filename(name)) if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)): try: print 'b' # Backup the argv variable and create a temporary directory to do all work in... old_argv = sys.argv[:] temp_dir = tempfile.mkdtemp() # Prepare the extension... sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir] comp_path = filter(lambda s: not s.endswith('.h'), source_path) depends = filter(lambda s: s.endswith('.h'), source_path) if openCL: ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends) else: ext = Extension(name, comp_path, depends=depends) # Compile... setup(name=name, version='1.0.0', ext_modules=[ext]) finally: # Cleanup the argv variable and the temporary directory... sys.argv = old_argv shutil.rmtree(temp_dir, True)
[ [ 1, 0, 0.2031, 0.0156, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2188, 0.0156, 0, 0.66, 0.125, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.2344, 0.0156, 0, 0.6...
[ "import sys", "import os.path", "import tempfile", "import shutil", "from distutils.core import setup, Extension", "import distutils.ccompiler", "import distutils.dep_util", "try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None", " __default_compiler...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pydoc import inspect class DocGen: """A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.""" def __init__(self, name, title = None, summary = None): """name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title.""" if title==None: title = name if summary==None: summary = title self.doc = pydoc.HTMLDoc() self.html = open('%s.html'%name,'w') self.html.write('<html>\n') self.html.write('<head>\n') self.html.write('<title>%s</title>\n'%title) self.html.write('</head>\n') self.html.write('<body>\n') self.html_variables = '' self.html_functions = '' self.html_classes = '' self.wiki = open('%s.wiki'%name,'w') self.wiki.write('#summary %s\n\n'%summary) self.wiki.write('= %s= \n\n'%title) self.wiki_variables = '' self.wiki_functions = '' self.wiki_classes = '' def __del__(self): if self.html_variables!='': self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables)) if self.html_functions!='': self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions)) if self.html_classes!='': self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes)) self.html.write('</body>\n') self.html.write('</html>\n') self.html.close() if self.wiki_variables!='': self.wiki.write('= Variables =\n\n') self.wiki.write(self.wiki_variables) self.wiki.write('\n') if self.wiki_functions!='': self.wiki.write('= Functions =\n\n') self.wiki.write(self.wiki_functions) self.wiki.write('\n') if self.wiki_classes!='': self.wiki.write('= Classes =\n\n') self.wiki.write(self.wiki_classes) self.wiki.write('\n') self.wiki.close() def addFile(self, fn, title, fls = True): """Given a filename and section title adds the contents of said file to the output. Various flags influence how this works.""" html = [] wiki = [] for i, line in enumerate(open(fn,'r').readlines()): hl = line.replace('\n', '') if i==0 and fls: hl = '<strong>' + hl + '</strong>' for ext in ['py','txt']: if '.%s - '%ext in hl: s = hl.split('.%s - '%ext, 1) hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1] html.append(hl) wl = line.strip() if i==0 and fls: wl = '*%s*'%wl for ext in ['py','txt']: if '.%s - '%ext in wl: s = wl.split('.%s - '%ext, 1) wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n' wiki.append(wl) self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html))) self.wiki.write('== %s ==\n'%title) self.wiki.write('\n'.join(wiki)) self.wiki.write('----\n\n') def addVariable(self, var, desc): """Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc..""" self.html_variables += '<strong>%s</strong><br/>'%var self.html_variables += '%s<br/><br/>\n'%desc self.wiki_variables += '*`%s`*\n'%var self.wiki_variables += ' %s\n\n'%desc def addFunction(self, func): """Adds a function to the documentation. You provide the actual function instance.""" self.html_functions += self.doc.docroutine(func).replace('&nbsp;',' ') self.html_functions += '\n' name = func.__name__ args, varargs, keywords, defaults = inspect.getargspec(func) doc = inspect.getdoc(func) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_functions += ' %s\n\n'%doc def addClass(self, cls): """Adds a class to the documentation. You provide the actual class object.""" self.html_classes += self.doc.docclass(cls).replace('&nbsp;',' ') self.html_classes += '\n' name = cls.__name__ parents = filter(lambda a: a!=cls, inspect.getmro(cls)) doc = inspect.getdoc(cls) par_str = '' if len(parents)!=0: par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents)) self.wiki_classes += '== %s(%s) ==\n'%(name, par_str) self.wiki_classes += ' %s\n\n'%doc methods = inspect.getmembers(cls, inspect.ismethod) def method_key(pair): if pair[0]=='__init__': return '___' else: return pair[0] methods.sort(key=method_key) for name, method in methods: if not name.startswith('_%s'%cls.__name__): args, varargs, keywords, defaults = inspect.getargspec(method) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords def fetch_doc(cls, name): try: method = getattr(cls, name) if method.__doc__!=None: return inspect.getdoc(method) except: pass for parent in filter(lambda a: a!=cls, inspect.getmro(cls)): ret = fetch_doc(parent, name) if ret!=None: return ret return None doc = fetch_doc(cls, name) self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_classes += ' %s\n\n'%doc variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float)) for name, var in variables: if not name.startswith('__'): self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
[ [ 1, 0, 0.0634, 0.0049, 0, 0.66, 0, 291, 0, 1, 0, 0, 291, 0, 0 ], [ 1, 0, 0.0683, 0.0049, 0, 0.66, 0.5, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 3, 0, 0.5439, 0.9171, 0, 0.6...
[ "import pydoc", "import inspect", "class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from ctypes import * def setProcName(name): """Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases.""" # Call the process control function... libc = cdll.LoadLibrary('libc.so.6') libc.prctl(15, c_char_p(name), 0, 0, 0) # Update argv... charPP = POINTER(POINTER(c_char)) argv = charPP.in_dll(libc,'_dl_argv') size = libc.strlen(argv[0]) libc.strncpy(argv[0],c_char_p(name),size) if __name__=='__main__': # Quick test that it works... import os ps1 = 'ps' ps2 = 'ps -f' os.system(ps1) os.system(ps2) setProcName('wibble_wobble') os.system(ps1) os.system(ps2)
[ [ 1, 0, 0.3636, 0.0227, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 2, 0, 0.5682, 0.25, 0, 0.66, 0.5, 903, 0, 1, 0, 0, 0, 0, 9 ], [ 8, 1, 0.4773, 0.0227, 1, 0.7, ...
[ "from ctypes import *", "def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import multiprocessing as mp import multiprocessing.synchronize # To make sure we have all the functionality. import types import marshal import unittest def repeat(x): """A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant.""" while True: yield x def run_code(code,args): """Internal use function that does the work in each process.""" code = marshal.loads(code) func = types.FunctionType(code, globals(), '_') return func(*args) def mp_map(func, *iters, **keywords): """A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity.""" if 'pool' in keywords: pool = keywords['pool'] else: pool = mp.Pool() code = marshal.dumps(func.func_code) jobs = [] for args in zip(*iters): jobs.append(pool.apply_async(run_code,(code,args))) for i in xrange(len(jobs)): jobs[i] = jobs[i].get() return jobs class TestMpMap(unittest.TestCase): def test_simple1(self): data = ['a','b','c','d'] def noop(data): return data data_noop = mp_map(noop, data) self.assertEqual(data, data_noop) def test_simple2(self): data = [x for x in xrange(1000)] data_double = mp_map(lambda a: a*2, data) self.assertEqual(map(lambda a: a*2,data), data_double) def test_gen(self): def gen(): for i in xrange(100): yield i data_double = mp_map(lambda a: a*2, gen()) self.assertEqual(map(lambda a: a*2,gen()), data_double) def test_repeat(self): def mult(a,b): return a*b data = [x for x in xrange(50,5000,5)] data_triple = mp_map(mult, data, repeat(3)) self.assertEqual(map(lambda a: a*3,data),data_triple) def test_none(self): data = [] data_sqr = mp_map(lambda x: x*x, data) self.assertEqual([],data_sqr) if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.1456, 0.0097, 0, 0.66, 0, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 1, 0, 0.1553, 0.0097, 0, 0.66, 0.1111, 99, 0, 1, 0, 0, 99, 0, 0 ], [ 1, 0, 0.1748, 0.0097, 0, 0....
[ "import multiprocessing as mp", "import multiprocessing.synchronize # To make sure we have all the functionality.", "import types", "import marshal", "import unittest", "def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Defines helper functions for accessing numpy arrays... numpy_util_code = start_cpp() + """ #ifndef NUMPY_UTIL_CODE #define NUMPY_UTIL_CODE float & Float1D(PyArrayObject * arr, int index = 0) { return *(float*)(arr->data + index*arr->strides[0]); } float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } unsigned char & Byte1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index*arr->strides[0]); } unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } int & Int1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index*arr->strides[0]); } int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } #endif """
[ [ 1, 0, 0.1923, 0.0128, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.6282, 0.7564, 0, 0.66, 1, 799, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}" ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import cvarray import mp_map import prog_bar import numpy_help_cpp import python_obj_cpp import matrix_cpp import gamma_cpp import setProcName import start_cpp import make import doc_gen # Setup... doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.') doc.addFile('readme.txt', 'Overview') # Variables... doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.') doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.') doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++') doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++') # Functions... doc.addFunction(make.make_mod) doc.addFunction(cvarray.cv2array) doc.addFunction(cvarray.array2cv) doc.addFunction(mp_map.repeat) doc.addFunction(mp_map.mp_map) doc.addFunction(setProcName.setProcName) doc.addFunction(start_cpp.start_cpp) doc.addFunction(make.make_mod) # Classes... doc.addClass(prog_bar.ProgBar) doc.addClass(doc_gen.DocGen)
[ [ 1, 0, 0.2857, 0.0179, 0, 0.66, 0, 192, 0, 1, 0, 0, 192, 0, 0 ], [ 1, 0, 0.3036, 0.0179, 0, 0.66, 0.0385, 905, 0, 1, 0, 0, 905, 0, 0 ], [ 1, 0, 0.3214, 0.0179, 0, ...
[ "import cvarray", "import mp_map", "import prog_bar", "import numpy_help_cpp", "import python_obj_cpp", "import matrix_cpp", "import gamma_cpp", "import setProcName", "import start_cpp", "import make", "import doc_gen", "doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc...
# Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest import random import math from scipy.special import gammaln, psi, polygamma from scipy import weave from utils.start_cpp import start_cpp # Provides various gamma-related functions... gamma_code = start_cpp() + """ #ifndef GAMMA_CODE #define GAMMA_CODE #include <cmath> // Returns the natural logarithm of the Gamma function... // (Uses Lanczos's approximation.) double lnGamma(double z) { static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7}; if (z<0.5) { // Use reflection formula, as approximation doesn't work down here... return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z); } else { double x = coeff[0]; for (int i=1;i<9;i++) x += coeff[i]/(z+i-1); double t = z + 6.5; return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x); } } // Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values... double digamma(double z) { static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point. double ret = 0.0; while (z<highVal) { ret -= 1.0/z; z += 1.0; } double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz4 = iz2*iz2; double iz6 = iz4*iz2; ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0; return ret; } // Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically... double trigamma(double z) { static const double highVal = 8.0; double ret = 0.0; while (z<highVal) { ret += 1.0/(z*z); z += 1.0; } z -= 1.0; double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz3 = iz1*iz2; double iz5 = iz3*iz2; double iz7 = iz5*iz2; double iz9 = iz7*iz2; ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0; return ret; } #endif """ def lnGamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function""" code = start_cpp(gamma_code) + """ return_val = lnGamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def digamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function""" code = start_cpp(gamma_code) + """ return_val = digamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def trigamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function""" code = start_cpp(gamma_code) + """ return_val = trigamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) class TestFuncs(unittest.TestCase): """Test code for the assorted gamma-related functions.""" def test_compile(self): code = start_cpp(gamma_code) + """ """ weave.inline(code, support_code=gamma_code) def test_error_lngamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = lnGamma(z) good = gammaln(z) assert(math.fabs(own-good)<1e-12) def test_error_digamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = digamma(z) good = psi(z) assert(math.fabs(own-good)<1e-9) def test_error_trigamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = trigamma(z) good = polygamma(1,z) assert(math.fabs(own-good)<1e-9) # If this file is run do the unit tests... if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.0818, 0.0063, 0, 0.66, 0, 88, 0, 1, 0, 0, 88, 0, 0 ], [ 1, 0, 0.0881, 0.0063, 0, 0.66, 0.0909, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0943, 0.0063, 0, 0....
[ "import unittest", "import random", "import math", "from scipy.special import gammaln, psi, polygamma", "from scipy import weave", "from utils.start_cpp import start_cpp", "gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import inspect import hashlib def start_cpp(hash_str = None): """This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>""" frame = inspect.currentframe().f_back info = inspect.getframeinfo(frame) if hash_str==None: return '#line %i "%s"\n'%(info[1],info[0]) else: h = hashlib.md5() h.update(hash_str) hash_val = h.hexdigest() return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
[ [ 1, 0, 0.5, 0.0333, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.5333, 0.0333, 0, 0.66, 0.5, 154, 0, 1, 0, 0, 154, 0, 0 ], [ 2, 0, 0.8333, 0.3667, 0, 0.66, ...
[ "import inspect", "import hashlib", "def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os.path import tempfile import shutil from distutils.core import setup, Extension import distutils.ccompiler import distutils.dep_util try: __default_compiler = distutils.ccompiler.new_compiler() except: __default_compiler = None def make_mod(name, base, source, openCL = False): """Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place.""" if __default_compiler==None: raise Exception('No compiler!') # Work out the various file names - check if we actually need to do anything... if not isinstance(source, list): source = [source] source_path = map(lambda s: os.path.join(base, s), source) library_path = os.path.join(base, __default_compiler.shared_object_filename(name)) if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)): try: print 'b' # Backup the argv variable and create a temporary directory to do all work in... old_argv = sys.argv[:] temp_dir = tempfile.mkdtemp() # Prepare the extension... sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir] comp_path = filter(lambda s: not s.endswith('.h'), source_path) depends = filter(lambda s: s.endswith('.h'), source_path) if openCL: ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends) else: ext = Extension(name, comp_path, depends=depends) # Compile... setup(name=name, version='1.0.0', ext_modules=[ext]) finally: # Cleanup the argv variable and the temporary directory... sys.argv = old_argv shutil.rmtree(temp_dir, True)
[ [ 1, 0, 0.2031, 0.0156, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2188, 0.0156, 0, 0.66, 0.125, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.2344, 0.0156, 0, 0.6...
[ "import sys", "import os.path", "import tempfile", "import shutil", "from distutils.core import setup, Extension", "import distutils.ccompiler", "import distutils.dep_util", "try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None", " __default_compiler...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pydoc import inspect class DocGen: """A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.""" def __init__(self, name, title = None, summary = None): """name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title.""" if title==None: title = name if summary==None: summary = title self.doc = pydoc.HTMLDoc() self.html = open('%s.html'%name,'w') self.html.write('<html>\n') self.html.write('<head>\n') self.html.write('<title>%s</title>\n'%title) self.html.write('</head>\n') self.html.write('<body>\n') self.html_variables = '' self.html_functions = '' self.html_classes = '' self.wiki = open('%s.wiki'%name,'w') self.wiki.write('#summary %s\n\n'%summary) self.wiki.write('= %s= \n\n'%title) self.wiki_variables = '' self.wiki_functions = '' self.wiki_classes = '' def __del__(self): if self.html_variables!='': self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables)) if self.html_functions!='': self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions)) if self.html_classes!='': self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes)) self.html.write('</body>\n') self.html.write('</html>\n') self.html.close() if self.wiki_variables!='': self.wiki.write('= Variables =\n\n') self.wiki.write(self.wiki_variables) self.wiki.write('\n') if self.wiki_functions!='': self.wiki.write('= Functions =\n\n') self.wiki.write(self.wiki_functions) self.wiki.write('\n') if self.wiki_classes!='': self.wiki.write('= Classes =\n\n') self.wiki.write(self.wiki_classes) self.wiki.write('\n') self.wiki.close() def addFile(self, fn, title, fls = True): """Given a filename and section title adds the contents of said file to the output. Various flags influence how this works.""" html = [] wiki = [] for i, line in enumerate(open(fn,'r').readlines()): hl = line.replace('\n', '') if i==0 and fls: hl = '<strong>' + hl + '</strong>' for ext in ['py','txt']: if '.%s - '%ext in hl: s = hl.split('.%s - '%ext, 1) hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1] html.append(hl) wl = line.strip() if i==0 and fls: wl = '*%s*'%wl for ext in ['py','txt']: if '.%s - '%ext in wl: s = wl.split('.%s - '%ext, 1) wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n' wiki.append(wl) self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html))) self.wiki.write('== %s ==\n'%title) self.wiki.write('\n'.join(wiki)) self.wiki.write('----\n\n') def addVariable(self, var, desc): """Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc..""" self.html_variables += '<strong>%s</strong><br/>'%var self.html_variables += '%s<br/><br/>\n'%desc self.wiki_variables += '*`%s`*\n'%var self.wiki_variables += ' %s\n\n'%desc def addFunction(self, func): """Adds a function to the documentation. You provide the actual function instance.""" self.html_functions += self.doc.docroutine(func).replace('&nbsp;',' ') self.html_functions += '\n' name = func.__name__ args, varargs, keywords, defaults = inspect.getargspec(func) doc = inspect.getdoc(func) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_functions += ' %s\n\n'%doc def addClass(self, cls): """Adds a class to the documentation. You provide the actual class object.""" self.html_classes += self.doc.docclass(cls).replace('&nbsp;',' ') self.html_classes += '\n' name = cls.__name__ parents = filter(lambda a: a!=cls, inspect.getmro(cls)) doc = inspect.getdoc(cls) par_str = '' if len(parents)!=0: par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents)) self.wiki_classes += '== %s(%s) ==\n'%(name, par_str) self.wiki_classes += ' %s\n\n'%doc methods = inspect.getmembers(cls, inspect.ismethod) def method_key(pair): if pair[0]=='__init__': return '___' else: return pair[0] methods.sort(key=method_key) for name, method in methods: if not name.startswith('_%s'%cls.__name__): args, varargs, keywords, defaults = inspect.getargspec(method) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords def fetch_doc(cls, name): try: method = getattr(cls, name) if method.__doc__!=None: return inspect.getdoc(method) except: pass for parent in filter(lambda a: a!=cls, inspect.getmro(cls)): ret = fetch_doc(parent, name) if ret!=None: return ret return None doc = fetch_doc(cls, name) self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_classes += ' %s\n\n'%doc variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float)) for name, var in variables: if not name.startswith('__'): self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
[ [ 1, 0, 0.0634, 0.0049, 0, 0.66, 0, 291, 0, 1, 0, 0, 291, 0, 0 ], [ 1, 0, 0.0683, 0.0049, 0, 0.66, 0.5, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 3, 0, 0.5439, 0.9171, 0, 0.6...
[ "import pydoc", "import inspect", "class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from ctypes import * def setProcName(name): """Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases.""" # Call the process control function... libc = cdll.LoadLibrary('libc.so.6') libc.prctl(15, c_char_p(name), 0, 0, 0) # Update argv... charPP = POINTER(POINTER(c_char)) argv = charPP.in_dll(libc,'_dl_argv') size = libc.strlen(argv[0]) libc.strncpy(argv[0],c_char_p(name),size) if __name__=='__main__': # Quick test that it works... import os ps1 = 'ps' ps2 = 'ps -f' os.system(ps1) os.system(ps2) setProcName('wibble_wobble') os.system(ps1) os.system(ps2)
[ [ 1, 0, 0.3636, 0.0227, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 2, 0, 0.5682, 0.25, 0, 0.66, 0.5, 903, 0, 1, 0, 0, 0, 0, 9 ], [ 8, 1, 0.4773, 0.0227, 1, 0.67, ...
[ "from ctypes import *", "def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import multiprocessing as mp import multiprocessing.synchronize # To make sure we have all the functionality. import types import marshal import unittest def repeat(x): """A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant.""" while True: yield x def run_code(code,args): """Internal use function that does the work in each process.""" code = marshal.loads(code) func = types.FunctionType(code, globals(), '_') return func(*args) def mp_map(func, *iters, **keywords): """A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity.""" if 'pool' in keywords: pool = keywords['pool'] else: pool = mp.Pool() code = marshal.dumps(func.func_code) jobs = [] for args in zip(*iters): jobs.append(pool.apply_async(run_code,(code,args))) for i in xrange(len(jobs)): jobs[i] = jobs[i].get() return jobs class TestMpMap(unittest.TestCase): def test_simple1(self): data = ['a','b','c','d'] def noop(data): return data data_noop = mp_map(noop, data) self.assertEqual(data, data_noop) def test_simple2(self): data = [x for x in xrange(1000)] data_double = mp_map(lambda a: a*2, data) self.assertEqual(map(lambda a: a*2,data), data_double) def test_gen(self): def gen(): for i in xrange(100): yield i data_double = mp_map(lambda a: a*2, gen()) self.assertEqual(map(lambda a: a*2,gen()), data_double) def test_repeat(self): def mult(a,b): return a*b data = [x for x in xrange(50,5000,5)] data_triple = mp_map(mult, data, repeat(3)) self.assertEqual(map(lambda a: a*3,data),data_triple) def test_none(self): data = [] data_sqr = mp_map(lambda x: x*x, data) self.assertEqual([],data_sqr) if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.1456, 0.0097, 0, 0.66, 0, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 1, 0, 0.1553, 0.0097, 0, 0.66, 0.1111, 99, 0, 1, 0, 0, 99, 0, 0 ], [ 1, 0, 0.1748, 0.0097, 0, 0....
[ "import multiprocessing as mp", "import multiprocessing.synchronize # To make sure we have all the functionality.", "import types", "import marshal", "import unittest", "def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Defines helper functions for accessing numpy arrays... numpy_util_code = start_cpp() + """ #ifndef NUMPY_UTIL_CODE #define NUMPY_UTIL_CODE float & Float1D(PyArrayObject * arr, int index = 0) { return *(float*)(arr->data + index*arr->strides[0]); } float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } unsigned char & Byte1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index*arr->strides[0]); } unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } int & Int1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index*arr->strides[0]); } int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } #endif """
[ [ 1, 0, 0.1923, 0.0128, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.6282, 0.7564, 0, 0.66, 1, 799, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}" ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import cvarray import mp_map import prog_bar import numpy_help_cpp import python_obj_cpp import matrix_cpp import gamma_cpp import setProcName import start_cpp import make import doc_gen # Setup... doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.') doc.addFile('readme.txt', 'Overview') # Variables... doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.') doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.') doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++') doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++') # Functions... doc.addFunction(make.make_mod) doc.addFunction(cvarray.cv2array) doc.addFunction(cvarray.array2cv) doc.addFunction(mp_map.repeat) doc.addFunction(mp_map.mp_map) doc.addFunction(setProcName.setProcName) doc.addFunction(start_cpp.start_cpp) doc.addFunction(make.make_mod) # Classes... doc.addClass(prog_bar.ProgBar) doc.addClass(doc_gen.DocGen)
[ [ 1, 0, 0.2857, 0.0179, 0, 0.66, 0, 192, 0, 1, 0, 0, 192, 0, 0 ], [ 1, 0, 0.3036, 0.0179, 0, 0.66, 0.0385, 905, 0, 1, 0, 0, 905, 0, 0 ], [ 1, 0, 0.3214, 0.0179, 0, ...
[ "import cvarray", "import mp_map", "import prog_bar", "import numpy_help_cpp", "import python_obj_cpp", "import matrix_cpp", "import gamma_cpp", "import setProcName", "import start_cpp", "import make", "import doc_gen", "doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc...
# Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest import random import math from scipy.special import gammaln, psi, polygamma from scipy import weave from utils.start_cpp import start_cpp # Provides various gamma-related functions... gamma_code = start_cpp() + """ #ifndef GAMMA_CODE #define GAMMA_CODE #include <cmath> // Returns the natural logarithm of the Gamma function... // (Uses Lanczos's approximation.) double lnGamma(double z) { static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7}; if (z<0.5) { // Use reflection formula, as approximation doesn't work down here... return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z); } else { double x = coeff[0]; for (int i=1;i<9;i++) x += coeff[i]/(z+i-1); double t = z + 6.5; return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x); } } // Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values... double digamma(double z) { static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point. double ret = 0.0; while (z<highVal) { ret -= 1.0/z; z += 1.0; } double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz4 = iz2*iz2; double iz6 = iz4*iz2; ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0; return ret; } // Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically... double trigamma(double z) { static const double highVal = 8.0; double ret = 0.0; while (z<highVal) { ret += 1.0/(z*z); z += 1.0; } z -= 1.0; double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz3 = iz1*iz2; double iz5 = iz3*iz2; double iz7 = iz5*iz2; double iz9 = iz7*iz2; ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0; return ret; } #endif """ def lnGamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function""" code = start_cpp(gamma_code) + """ return_val = lnGamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def digamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function""" code = start_cpp(gamma_code) + """ return_val = digamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def trigamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function""" code = start_cpp(gamma_code) + """ return_val = trigamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) class TestFuncs(unittest.TestCase): """Test code for the assorted gamma-related functions.""" def test_compile(self): code = start_cpp(gamma_code) + """ """ weave.inline(code, support_code=gamma_code) def test_error_lngamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = lnGamma(z) good = gammaln(z) assert(math.fabs(own-good)<1e-12) def test_error_digamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = digamma(z) good = psi(z) assert(math.fabs(own-good)<1e-9) def test_error_trigamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = trigamma(z) good = polygamma(1,z) assert(math.fabs(own-good)<1e-9) # If this file is run do the unit tests... if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.0818, 0.0063, 0, 0.66, 0, 88, 0, 1, 0, 0, 88, 0, 0 ], [ 1, 0, 0.0881, 0.0063, 0, 0.66, 0.0909, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0943, 0.0063, 0, 0....
[ "import unittest", "import random", "import math", "from scipy.special import gammaln, psi, polygamma", "from scipy import weave", "from utils.start_cpp import start_cpp", "gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import inspect import hashlib def start_cpp(hash_str = None): """This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>""" frame = inspect.currentframe().f_back info = inspect.getframeinfo(frame) if hash_str==None: return '#line %i "%s"\n'%(info[1],info[0]) else: h = hashlib.md5() h.update(hash_str) hash_val = h.hexdigest() return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
[ [ 1, 0, 0.5, 0.0333, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.5333, 0.0333, 0, 0.66, 0.5, 154, 0, 1, 0, 0, 154, 0, 0 ], [ 2, 0, 0.8333, 0.3667, 0, 0.66, ...
[ "import inspect", "import hashlib", "def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os.path import tempfile import shutil from distutils.core import setup, Extension import distutils.ccompiler import distutils.dep_util try: __default_compiler = distutils.ccompiler.new_compiler() except: __default_compiler = None def make_mod(name, base, source, openCL = False): """Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place.""" if __default_compiler==None: raise Exception('No compiler!') # Work out the various file names - check if we actually need to do anything... if not isinstance(source, list): source = [source] source_path = map(lambda s: os.path.join(base, s), source) library_path = os.path.join(base, __default_compiler.shared_object_filename(name)) if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)): try: print 'b' # Backup the argv variable and create a temporary directory to do all work in... old_argv = sys.argv[:] temp_dir = tempfile.mkdtemp() # Prepare the extension... sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir] comp_path = filter(lambda s: not s.endswith('.h'), source_path) depends = filter(lambda s: s.endswith('.h'), source_path) if openCL: ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends) else: ext = Extension(name, comp_path, depends=depends) # Compile... setup(name=name, version='1.0.0', ext_modules=[ext]) finally: # Cleanup the argv variable and the temporary directory... sys.argv = old_argv shutil.rmtree(temp_dir, True)
[ [ 1, 0, 0.2031, 0.0156, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2188, 0.0156, 0, 0.66, 0.125, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.2344, 0.0156, 0, 0.6...
[ "import sys", "import os.path", "import tempfile", "import shutil", "from distutils.core import setup, Extension", "import distutils.ccompiler", "import distutils.dep_util", "try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None", " __default_compiler...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pydoc import inspect class DocGen: """A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.""" def __init__(self, name, title = None, summary = None): """name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title.""" if title==None: title = name if summary==None: summary = title self.doc = pydoc.HTMLDoc() self.html = open('%s.html'%name,'w') self.html.write('<html>\n') self.html.write('<head>\n') self.html.write('<title>%s</title>\n'%title) self.html.write('</head>\n') self.html.write('<body>\n') self.html_variables = '' self.html_functions = '' self.html_classes = '' self.wiki = open('%s.wiki'%name,'w') self.wiki.write('#summary %s\n\n'%summary) self.wiki.write('= %s= \n\n'%title) self.wiki_variables = '' self.wiki_functions = '' self.wiki_classes = '' def __del__(self): if self.html_variables!='': self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables)) if self.html_functions!='': self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions)) if self.html_classes!='': self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes)) self.html.write('</body>\n') self.html.write('</html>\n') self.html.close() if self.wiki_variables!='': self.wiki.write('= Variables =\n\n') self.wiki.write(self.wiki_variables) self.wiki.write('\n') if self.wiki_functions!='': self.wiki.write('= Functions =\n\n') self.wiki.write(self.wiki_functions) self.wiki.write('\n') if self.wiki_classes!='': self.wiki.write('= Classes =\n\n') self.wiki.write(self.wiki_classes) self.wiki.write('\n') self.wiki.close() def addFile(self, fn, title, fls = True): """Given a filename and section title adds the contents of said file to the output. Various flags influence how this works.""" html = [] wiki = [] for i, line in enumerate(open(fn,'r').readlines()): hl = line.replace('\n', '') if i==0 and fls: hl = '<strong>' + hl + '</strong>' for ext in ['py','txt']: if '.%s - '%ext in hl: s = hl.split('.%s - '%ext, 1) hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1] html.append(hl) wl = line.strip() if i==0 and fls: wl = '*%s*'%wl for ext in ['py','txt']: if '.%s - '%ext in wl: s = wl.split('.%s - '%ext, 1) wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n' wiki.append(wl) self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html))) self.wiki.write('== %s ==\n'%title) self.wiki.write('\n'.join(wiki)) self.wiki.write('----\n\n') def addVariable(self, var, desc): """Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc..""" self.html_variables += '<strong>%s</strong><br/>'%var self.html_variables += '%s<br/><br/>\n'%desc self.wiki_variables += '*`%s`*\n'%var self.wiki_variables += ' %s\n\n'%desc def addFunction(self, func): """Adds a function to the documentation. You provide the actual function instance.""" self.html_functions += self.doc.docroutine(func).replace('&nbsp;',' ') self.html_functions += '\n' name = func.__name__ args, varargs, keywords, defaults = inspect.getargspec(func) doc = inspect.getdoc(func) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_functions += ' %s\n\n'%doc def addClass(self, cls): """Adds a class to the documentation. You provide the actual class object.""" self.html_classes += self.doc.docclass(cls).replace('&nbsp;',' ') self.html_classes += '\n' name = cls.__name__ parents = filter(lambda a: a!=cls, inspect.getmro(cls)) doc = inspect.getdoc(cls) par_str = '' if len(parents)!=0: par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents)) self.wiki_classes += '== %s(%s) ==\n'%(name, par_str) self.wiki_classes += ' %s\n\n'%doc methods = inspect.getmembers(cls, inspect.ismethod) def method_key(pair): if pair[0]=='__init__': return '___' else: return pair[0] methods.sort(key=method_key) for name, method in methods: if not name.startswith('_%s'%cls.__name__): args, varargs, keywords, defaults = inspect.getargspec(method) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords def fetch_doc(cls, name): try: method = getattr(cls, name) if method.__doc__!=None: return inspect.getdoc(method) except: pass for parent in filter(lambda a: a!=cls, inspect.getmro(cls)): ret = fetch_doc(parent, name) if ret!=None: return ret return None doc = fetch_doc(cls, name) self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_classes += ' %s\n\n'%doc variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float)) for name, var in variables: if not name.startswith('__'): self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
[ [ 1, 0, 0.0634, 0.0049, 0, 0.66, 0, 291, 0, 1, 0, 0, 291, 0, 0 ], [ 1, 0, 0.0683, 0.0049, 0, 0.66, 0.5, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 3, 0, 0.5439, 0.9171, 0, 0.6...
[ "import pydoc", "import inspect", "class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from ctypes import * def setProcName(name): """Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases.""" # Call the process control function... libc = cdll.LoadLibrary('libc.so.6') libc.prctl(15, c_char_p(name), 0, 0, 0) # Update argv... charPP = POINTER(POINTER(c_char)) argv = charPP.in_dll(libc,'_dl_argv') size = libc.strlen(argv[0]) libc.strncpy(argv[0],c_char_p(name),size) if __name__=='__main__': # Quick test that it works... import os ps1 = 'ps' ps2 = 'ps -f' os.system(ps1) os.system(ps2) setProcName('wibble_wobble') os.system(ps1) os.system(ps2)
[ [ 1, 0, 0.3636, 0.0227, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 2, 0, 0.5682, 0.25, 0, 0.66, 0.5, 903, 0, 1, 0, 0, 0, 0, 9 ], [ 8, 1, 0.4773, 0.0227, 1, 0.2, ...
[ "from ctypes import *", "def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import multiprocessing as mp import multiprocessing.synchronize # To make sure we have all the functionality. import types import marshal import unittest def repeat(x): """A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant.""" while True: yield x def run_code(code,args): """Internal use function that does the work in each process.""" code = marshal.loads(code) func = types.FunctionType(code, globals(), '_') return func(*args) def mp_map(func, *iters, **keywords): """A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity.""" if 'pool' in keywords: pool = keywords['pool'] else: pool = mp.Pool() code = marshal.dumps(func.func_code) jobs = [] for args in zip(*iters): jobs.append(pool.apply_async(run_code,(code,args))) for i in xrange(len(jobs)): jobs[i] = jobs[i].get() return jobs class TestMpMap(unittest.TestCase): def test_simple1(self): data = ['a','b','c','d'] def noop(data): return data data_noop = mp_map(noop, data) self.assertEqual(data, data_noop) def test_simple2(self): data = [x for x in xrange(1000)] data_double = mp_map(lambda a: a*2, data) self.assertEqual(map(lambda a: a*2,data), data_double) def test_gen(self): def gen(): for i in xrange(100): yield i data_double = mp_map(lambda a: a*2, gen()) self.assertEqual(map(lambda a: a*2,gen()), data_double) def test_repeat(self): def mult(a,b): return a*b data = [x for x in xrange(50,5000,5)] data_triple = mp_map(mult, data, repeat(3)) self.assertEqual(map(lambda a: a*3,data),data_triple) def test_none(self): data = [] data_sqr = mp_map(lambda x: x*x, data) self.assertEqual([],data_sqr) if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.1456, 0.0097, 0, 0.66, 0, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 1, 0, 0.1553, 0.0097, 0, 0.66, 0.1111, 99, 0, 1, 0, 0, 99, 0, 0 ], [ 1, 0, 0.1748, 0.0097, 0, 0....
[ "import multiprocessing as mp", "import multiprocessing.synchronize # To make sure we have all the functionality.", "import types", "import marshal", "import unittest", "def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Defines helper functions for accessing numpy arrays... numpy_util_code = start_cpp() + """ #ifndef NUMPY_UTIL_CODE #define NUMPY_UTIL_CODE float & Float1D(PyArrayObject * arr, int index = 0) { return *(float*)(arr->data + index*arr->strides[0]); } float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } unsigned char & Byte1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index*arr->strides[0]); } unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } int & Int1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index*arr->strides[0]); } int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } #endif """
[ [ 1, 0, 0.1923, 0.0128, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.6282, 0.7564, 0, 0.66, 1, 799, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}" ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import cvarray import mp_map import prog_bar import numpy_help_cpp import python_obj_cpp import matrix_cpp import gamma_cpp import setProcName import start_cpp import make import doc_gen # Setup... doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.') doc.addFile('readme.txt', 'Overview') # Variables... doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.') doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.') doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++') doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++') # Functions... doc.addFunction(make.make_mod) doc.addFunction(cvarray.cv2array) doc.addFunction(cvarray.array2cv) doc.addFunction(mp_map.repeat) doc.addFunction(mp_map.mp_map) doc.addFunction(setProcName.setProcName) doc.addFunction(start_cpp.start_cpp) doc.addFunction(make.make_mod) # Classes... doc.addClass(prog_bar.ProgBar) doc.addClass(doc_gen.DocGen)
[ [ 1, 0, 0.2857, 0.0179, 0, 0.66, 0, 192, 0, 1, 0, 0, 192, 0, 0 ], [ 1, 0, 0.3036, 0.0179, 0, 0.66, 0.0385, 905, 0, 1, 0, 0, 905, 0, 0 ], [ 1, 0, 0.3214, 0.0179, 0, ...
[ "import cvarray", "import mp_map", "import prog_bar", "import numpy_help_cpp", "import python_obj_cpp", "import matrix_cpp", "import gamma_cpp", "import setProcName", "import start_cpp", "import make", "import doc_gen", "doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc...
# Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest import random import math from scipy.special import gammaln, psi, polygamma from scipy import weave from utils.start_cpp import start_cpp # Provides various gamma-related functions... gamma_code = start_cpp() + """ #ifndef GAMMA_CODE #define GAMMA_CODE #include <cmath> // Returns the natural logarithm of the Gamma function... // (Uses Lanczos's approximation.) double lnGamma(double z) { static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7}; if (z<0.5) { // Use reflection formula, as approximation doesn't work down here... return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z); } else { double x = coeff[0]; for (int i=1;i<9;i++) x += coeff[i]/(z+i-1); double t = z + 6.5; return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x); } } // Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values... double digamma(double z) { static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point. double ret = 0.0; while (z<highVal) { ret -= 1.0/z; z += 1.0; } double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz4 = iz2*iz2; double iz6 = iz4*iz2; ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0; return ret; } // Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically... double trigamma(double z) { static const double highVal = 8.0; double ret = 0.0; while (z<highVal) { ret += 1.0/(z*z); z += 1.0; } z -= 1.0; double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz3 = iz1*iz2; double iz5 = iz3*iz2; double iz7 = iz5*iz2; double iz9 = iz7*iz2; ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0; return ret; } #endif """ def lnGamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function""" code = start_cpp(gamma_code) + """ return_val = lnGamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def digamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function""" code = start_cpp(gamma_code) + """ return_val = digamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def trigamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function""" code = start_cpp(gamma_code) + """ return_val = trigamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) class TestFuncs(unittest.TestCase): """Test code for the assorted gamma-related functions.""" def test_compile(self): code = start_cpp(gamma_code) + """ """ weave.inline(code, support_code=gamma_code) def test_error_lngamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = lnGamma(z) good = gammaln(z) assert(math.fabs(own-good)<1e-12) def test_error_digamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = digamma(z) good = psi(z) assert(math.fabs(own-good)<1e-9) def test_error_trigamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = trigamma(z) good = polygamma(1,z) assert(math.fabs(own-good)<1e-9) # If this file is run do the unit tests... if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.0818, 0.0063, 0, 0.66, 0, 88, 0, 1, 0, 0, 88, 0, 0 ], [ 1, 0, 0.0881, 0.0063, 0, 0.66, 0.0909, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0943, 0.0063, 0, 0....
[ "import unittest", "import random", "import math", "from scipy.special import gammaln, psi, polygamma", "from scipy import weave", "from utils.start_cpp import start_cpp", "gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import inspect import hashlib def start_cpp(hash_str = None): """This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>""" frame = inspect.currentframe().f_back info = inspect.getframeinfo(frame) if hash_str==None: return '#line %i "%s"\n'%(info[1],info[0]) else: h = hashlib.md5() h.update(hash_str) hash_val = h.hexdigest() return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
[ [ 1, 0, 0.5, 0.0333, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.5333, 0.0333, 0, 0.66, 0.5, 154, 0, 1, 0, 0, 154, 0, 0 ], [ 2, 0, 0.8333, 0.3667, 0, 0.66, ...
[ "import inspect", "import hashlib", "def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os.path import tempfile import shutil from distutils.core import setup, Extension import distutils.ccompiler import distutils.dep_util try: __default_compiler = distutils.ccompiler.new_compiler() except: __default_compiler = None def make_mod(name, base, source, openCL = False): """Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place.""" if __default_compiler==None: raise Exception('No compiler!') # Work out the various file names - check if we actually need to do anything... if not isinstance(source, list): source = [source] source_path = map(lambda s: os.path.join(base, s), source) library_path = os.path.join(base, __default_compiler.shared_object_filename(name)) if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)): try: print 'b' # Backup the argv variable and create a temporary directory to do all work in... old_argv = sys.argv[:] temp_dir = tempfile.mkdtemp() # Prepare the extension... sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir] comp_path = filter(lambda s: not s.endswith('.h'), source_path) depends = filter(lambda s: s.endswith('.h'), source_path) if openCL: ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends) else: ext = Extension(name, comp_path, depends=depends) # Compile... setup(name=name, version='1.0.0', ext_modules=[ext]) finally: # Cleanup the argv variable and the temporary directory... sys.argv = old_argv shutil.rmtree(temp_dir, True)
[ [ 1, 0, 0.2031, 0.0156, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2188, 0.0156, 0, 0.66, 0.125, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.2344, 0.0156, 0, 0.6...
[ "import sys", "import os.path", "import tempfile", "import shutil", "from distutils.core import setup, Extension", "import distutils.ccompiler", "import distutils.dep_util", "try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None", " __default_compiler...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pydoc import inspect class DocGen: """A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.""" def __init__(self, name, title = None, summary = None): """name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title.""" if title==None: title = name if summary==None: summary = title self.doc = pydoc.HTMLDoc() self.html = open('%s.html'%name,'w') self.html.write('<html>\n') self.html.write('<head>\n') self.html.write('<title>%s</title>\n'%title) self.html.write('</head>\n') self.html.write('<body>\n') self.html_variables = '' self.html_functions = '' self.html_classes = '' self.wiki = open('%s.wiki'%name,'w') self.wiki.write('#summary %s\n\n'%summary) self.wiki.write('= %s= \n\n'%title) self.wiki_variables = '' self.wiki_functions = '' self.wiki_classes = '' def __del__(self): if self.html_variables!='': self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables)) if self.html_functions!='': self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions)) if self.html_classes!='': self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes)) self.html.write('</body>\n') self.html.write('</html>\n') self.html.close() if self.wiki_variables!='': self.wiki.write('= Variables =\n\n') self.wiki.write(self.wiki_variables) self.wiki.write('\n') if self.wiki_functions!='': self.wiki.write('= Functions =\n\n') self.wiki.write(self.wiki_functions) self.wiki.write('\n') if self.wiki_classes!='': self.wiki.write('= Classes =\n\n') self.wiki.write(self.wiki_classes) self.wiki.write('\n') self.wiki.close() def addFile(self, fn, title, fls = True): """Given a filename and section title adds the contents of said file to the output. Various flags influence how this works.""" html = [] wiki = [] for i, line in enumerate(open(fn,'r').readlines()): hl = line.replace('\n', '') if i==0 and fls: hl = '<strong>' + hl + '</strong>' for ext in ['py','txt']: if '.%s - '%ext in hl: s = hl.split('.%s - '%ext, 1) hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1] html.append(hl) wl = line.strip() if i==0 and fls: wl = '*%s*'%wl for ext in ['py','txt']: if '.%s - '%ext in wl: s = wl.split('.%s - '%ext, 1) wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n' wiki.append(wl) self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html))) self.wiki.write('== %s ==\n'%title) self.wiki.write('\n'.join(wiki)) self.wiki.write('----\n\n') def addVariable(self, var, desc): """Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc..""" self.html_variables += '<strong>%s</strong><br/>'%var self.html_variables += '%s<br/><br/>\n'%desc self.wiki_variables += '*`%s`*\n'%var self.wiki_variables += ' %s\n\n'%desc def addFunction(self, func): """Adds a function to the documentation. You provide the actual function instance.""" self.html_functions += self.doc.docroutine(func).replace('&nbsp;',' ') self.html_functions += '\n' name = func.__name__ args, varargs, keywords, defaults = inspect.getargspec(func) doc = inspect.getdoc(func) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_functions += ' %s\n\n'%doc def addClass(self, cls): """Adds a class to the documentation. You provide the actual class object.""" self.html_classes += self.doc.docclass(cls).replace('&nbsp;',' ') self.html_classes += '\n' name = cls.__name__ parents = filter(lambda a: a!=cls, inspect.getmro(cls)) doc = inspect.getdoc(cls) par_str = '' if len(parents)!=0: par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents)) self.wiki_classes += '== %s(%s) ==\n'%(name, par_str) self.wiki_classes += ' %s\n\n'%doc methods = inspect.getmembers(cls, inspect.ismethod) def method_key(pair): if pair[0]=='__init__': return '___' else: return pair[0] methods.sort(key=method_key) for name, method in methods: if not name.startswith('_%s'%cls.__name__): args, varargs, keywords, defaults = inspect.getargspec(method) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords def fetch_doc(cls, name): try: method = getattr(cls, name) if method.__doc__!=None: return inspect.getdoc(method) except: pass for parent in filter(lambda a: a!=cls, inspect.getmro(cls)): ret = fetch_doc(parent, name) if ret!=None: return ret return None doc = fetch_doc(cls, name) self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_classes += ' %s\n\n'%doc variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float)) for name, var in variables: if not name.startswith('__'): self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
[ [ 1, 0, 0.0634, 0.0049, 0, 0.66, 0, 291, 0, 1, 0, 0, 291, 0, 0 ], [ 1, 0, 0.0683, 0.0049, 0, 0.66, 0.5, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 3, 0, 0.5439, 0.9171, 0, 0.6...
[ "import pydoc", "import inspect", "class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from ctypes import * def setProcName(name): """Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases.""" # Call the process control function... libc = cdll.LoadLibrary('libc.so.6') libc.prctl(15, c_char_p(name), 0, 0, 0) # Update argv... charPP = POINTER(POINTER(c_char)) argv = charPP.in_dll(libc,'_dl_argv') size = libc.strlen(argv[0]) libc.strncpy(argv[0],c_char_p(name),size) if __name__=='__main__': # Quick test that it works... import os ps1 = 'ps' ps2 = 'ps -f' os.system(ps1) os.system(ps2) setProcName('wibble_wobble') os.system(ps1) os.system(ps2)
[ [ 1, 0, 0.3636, 0.0227, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 2, 0, 0.5682, 0.25, 0, 0.66, 0.5, 903, 0, 1, 0, 0, 0, 0, 9 ], [ 8, 1, 0.4773, 0.0227, 1, 0.64, ...
[ "from ctypes import *", "def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import multiprocessing as mp import multiprocessing.synchronize # To make sure we have all the functionality. import types import marshal import unittest def repeat(x): """A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant.""" while True: yield x def run_code(code,args): """Internal use function that does the work in each process.""" code = marshal.loads(code) func = types.FunctionType(code, globals(), '_') return func(*args) def mp_map(func, *iters, **keywords): """A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity.""" if 'pool' in keywords: pool = keywords['pool'] else: pool = mp.Pool() code = marshal.dumps(func.func_code) jobs = [] for args in zip(*iters): jobs.append(pool.apply_async(run_code,(code,args))) for i in xrange(len(jobs)): jobs[i] = jobs[i].get() return jobs class TestMpMap(unittest.TestCase): def test_simple1(self): data = ['a','b','c','d'] def noop(data): return data data_noop = mp_map(noop, data) self.assertEqual(data, data_noop) def test_simple2(self): data = [x for x in xrange(1000)] data_double = mp_map(lambda a: a*2, data) self.assertEqual(map(lambda a: a*2,data), data_double) def test_gen(self): def gen(): for i in xrange(100): yield i data_double = mp_map(lambda a: a*2, gen()) self.assertEqual(map(lambda a: a*2,gen()), data_double) def test_repeat(self): def mult(a,b): return a*b data = [x for x in xrange(50,5000,5)] data_triple = mp_map(mult, data, repeat(3)) self.assertEqual(map(lambda a: a*3,data),data_triple) def test_none(self): data = [] data_sqr = mp_map(lambda x: x*x, data) self.assertEqual([],data_sqr) if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.1456, 0.0097, 0, 0.66, 0, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 1, 0, 0.1553, 0.0097, 0, 0.66, 0.1111, 99, 0, 1, 0, 0, 99, 0, 0 ], [ 1, 0, 0.1748, 0.0097, 0, 0....
[ "import multiprocessing as mp", "import multiprocessing.synchronize # To make sure we have all the functionality.", "import types", "import marshal", "import unittest", "def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Defines helper functions for accessing numpy arrays... numpy_util_code = start_cpp() + """ #ifndef NUMPY_UTIL_CODE #define NUMPY_UTIL_CODE float & Float1D(PyArrayObject * arr, int index = 0) { return *(float*)(arr->data + index*arr->strides[0]); } float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } unsigned char & Byte1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index*arr->strides[0]); } unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } int & Int1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index*arr->strides[0]); } int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } #endif """
[ [ 1, 0, 0.1923, 0.0128, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.6282, 0.7564, 0, 0.66, 1, 799, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}" ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import cvarray import mp_map import prog_bar import numpy_help_cpp import python_obj_cpp import matrix_cpp import gamma_cpp import setProcName import start_cpp import make import doc_gen # Setup... doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.') doc.addFile('readme.txt', 'Overview') # Variables... doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.') doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.') doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++') doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++') # Functions... doc.addFunction(make.make_mod) doc.addFunction(cvarray.cv2array) doc.addFunction(cvarray.array2cv) doc.addFunction(mp_map.repeat) doc.addFunction(mp_map.mp_map) doc.addFunction(setProcName.setProcName) doc.addFunction(start_cpp.start_cpp) doc.addFunction(make.make_mod) # Classes... doc.addClass(prog_bar.ProgBar) doc.addClass(doc_gen.DocGen)
[ [ 1, 0, 0.2857, 0.0179, 0, 0.66, 0, 192, 0, 1, 0, 0, 192, 0, 0 ], [ 1, 0, 0.3036, 0.0179, 0, 0.66, 0.0385, 905, 0, 1, 0, 0, 905, 0, 0 ], [ 1, 0, 0.3214, 0.0179, 0, ...
[ "import cvarray", "import mp_map", "import prog_bar", "import numpy_help_cpp", "import python_obj_cpp", "import matrix_cpp", "import gamma_cpp", "import setProcName", "import start_cpp", "import make", "import doc_gen", "doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc...
# Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest import random import math from scipy.special import gammaln, psi, polygamma from scipy import weave from utils.start_cpp import start_cpp # Provides various gamma-related functions... gamma_code = start_cpp() + """ #ifndef GAMMA_CODE #define GAMMA_CODE #include <cmath> // Returns the natural logarithm of the Gamma function... // (Uses Lanczos's approximation.) double lnGamma(double z) { static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7}; if (z<0.5) { // Use reflection formula, as approximation doesn't work down here... return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z); } else { double x = coeff[0]; for (int i=1;i<9;i++) x += coeff[i]/(z+i-1); double t = z + 6.5; return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x); } } // Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values... double digamma(double z) { static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point. double ret = 0.0; while (z<highVal) { ret -= 1.0/z; z += 1.0; } double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz4 = iz2*iz2; double iz6 = iz4*iz2; ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0; return ret; } // Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically... double trigamma(double z) { static const double highVal = 8.0; double ret = 0.0; while (z<highVal) { ret += 1.0/(z*z); z += 1.0; } z -= 1.0; double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz3 = iz1*iz2; double iz5 = iz3*iz2; double iz7 = iz5*iz2; double iz9 = iz7*iz2; ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0; return ret; } #endif """ def lnGamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function""" code = start_cpp(gamma_code) + """ return_val = lnGamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def digamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function""" code = start_cpp(gamma_code) + """ return_val = digamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def trigamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function""" code = start_cpp(gamma_code) + """ return_val = trigamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) class TestFuncs(unittest.TestCase): """Test code for the assorted gamma-related functions.""" def test_compile(self): code = start_cpp(gamma_code) + """ """ weave.inline(code, support_code=gamma_code) def test_error_lngamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = lnGamma(z) good = gammaln(z) assert(math.fabs(own-good)<1e-12) def test_error_digamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = digamma(z) good = psi(z) assert(math.fabs(own-good)<1e-9) def test_error_trigamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = trigamma(z) good = polygamma(1,z) assert(math.fabs(own-good)<1e-9) # If this file is run do the unit tests... if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.0818, 0.0063, 0, 0.66, 0, 88, 0, 1, 0, 0, 88, 0, 0 ], [ 1, 0, 0.0881, 0.0063, 0, 0.66, 0.0909, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0943, 0.0063, 0, 0....
[ "import unittest", "import random", "import math", "from scipy.special import gammaln, psi, polygamma", "from scipy import weave", "from utils.start_cpp import start_cpp", "gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import inspect import hashlib def start_cpp(hash_str = None): """This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>""" frame = inspect.currentframe().f_back info = inspect.getframeinfo(frame) if hash_str==None: return '#line %i "%s"\n'%(info[1],info[0]) else: h = hashlib.md5() h.update(hash_str) hash_val = h.hexdigest() return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
[ [ 1, 0, 0.5, 0.0333, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.5333, 0.0333, 0, 0.66, 0.5, 154, 0, 1, 0, 0, 154, 0, 0 ], [ 2, 0, 0.8333, 0.3667, 0, 0.66, ...
[ "import inspect", "import hashlib", "def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os.path import tempfile import shutil from distutils.core import setup, Extension import distutils.ccompiler import distutils.dep_util try: __default_compiler = distutils.ccompiler.new_compiler() except: __default_compiler = None def make_mod(name, base, source, openCL = False): """Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place.""" if __default_compiler==None: raise Exception('No compiler!') # Work out the various file names - check if we actually need to do anything... if not isinstance(source, list): source = [source] source_path = map(lambda s: os.path.join(base, s), source) library_path = os.path.join(base, __default_compiler.shared_object_filename(name)) if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)): try: print 'b' # Backup the argv variable and create a temporary directory to do all work in... old_argv = sys.argv[:] temp_dir = tempfile.mkdtemp() # Prepare the extension... sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir] comp_path = filter(lambda s: not s.endswith('.h'), source_path) depends = filter(lambda s: s.endswith('.h'), source_path) if openCL: ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends) else: ext = Extension(name, comp_path, depends=depends) # Compile... setup(name=name, version='1.0.0', ext_modules=[ext]) finally: # Cleanup the argv variable and the temporary directory... sys.argv = old_argv shutil.rmtree(temp_dir, True)
[ [ 1, 0, 0.2031, 0.0156, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2188, 0.0156, 0, 0.66, 0.125, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.2344, 0.0156, 0, 0.6...
[ "import sys", "import os.path", "import tempfile", "import shutil", "from distutils.core import setup, Extension", "import distutils.ccompiler", "import distutils.dep_util", "try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None", " __default_compiler...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pydoc import inspect class DocGen: """A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.""" def __init__(self, name, title = None, summary = None): """name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title.""" if title==None: title = name if summary==None: summary = title self.doc = pydoc.HTMLDoc() self.html = open('%s.html'%name,'w') self.html.write('<html>\n') self.html.write('<head>\n') self.html.write('<title>%s</title>\n'%title) self.html.write('</head>\n') self.html.write('<body>\n') self.html_variables = '' self.html_functions = '' self.html_classes = '' self.wiki = open('%s.wiki'%name,'w') self.wiki.write('#summary %s\n\n'%summary) self.wiki.write('= %s= \n\n'%title) self.wiki_variables = '' self.wiki_functions = '' self.wiki_classes = '' def __del__(self): if self.html_variables!='': self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables)) if self.html_functions!='': self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions)) if self.html_classes!='': self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes)) self.html.write('</body>\n') self.html.write('</html>\n') self.html.close() if self.wiki_variables!='': self.wiki.write('= Variables =\n\n') self.wiki.write(self.wiki_variables) self.wiki.write('\n') if self.wiki_functions!='': self.wiki.write('= Functions =\n\n') self.wiki.write(self.wiki_functions) self.wiki.write('\n') if self.wiki_classes!='': self.wiki.write('= Classes =\n\n') self.wiki.write(self.wiki_classes) self.wiki.write('\n') self.wiki.close() def addFile(self, fn, title, fls = True): """Given a filename and section title adds the contents of said file to the output. Various flags influence how this works.""" html = [] wiki = [] for i, line in enumerate(open(fn,'r').readlines()): hl = line.replace('\n', '') if i==0 and fls: hl = '<strong>' + hl + '</strong>' for ext in ['py','txt']: if '.%s - '%ext in hl: s = hl.split('.%s - '%ext, 1) hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1] html.append(hl) wl = line.strip() if i==0 and fls: wl = '*%s*'%wl for ext in ['py','txt']: if '.%s - '%ext in wl: s = wl.split('.%s - '%ext, 1) wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n' wiki.append(wl) self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html))) self.wiki.write('== %s ==\n'%title) self.wiki.write('\n'.join(wiki)) self.wiki.write('----\n\n') def addVariable(self, var, desc): """Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc..""" self.html_variables += '<strong>%s</strong><br/>'%var self.html_variables += '%s<br/><br/>\n'%desc self.wiki_variables += '*`%s`*\n'%var self.wiki_variables += ' %s\n\n'%desc def addFunction(self, func): """Adds a function to the documentation. You provide the actual function instance.""" self.html_functions += self.doc.docroutine(func).replace('&nbsp;',' ') self.html_functions += '\n' name = func.__name__ args, varargs, keywords, defaults = inspect.getargspec(func) doc = inspect.getdoc(func) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_functions += ' %s\n\n'%doc def addClass(self, cls): """Adds a class to the documentation. You provide the actual class object.""" self.html_classes += self.doc.docclass(cls).replace('&nbsp;',' ') self.html_classes += '\n' name = cls.__name__ parents = filter(lambda a: a!=cls, inspect.getmro(cls)) doc = inspect.getdoc(cls) par_str = '' if len(parents)!=0: par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents)) self.wiki_classes += '== %s(%s) ==\n'%(name, par_str) self.wiki_classes += ' %s\n\n'%doc methods = inspect.getmembers(cls, inspect.ismethod) def method_key(pair): if pair[0]=='__init__': return '___' else: return pair[0] methods.sort(key=method_key) for name, method in methods: if not name.startswith('_%s'%cls.__name__): args, varargs, keywords, defaults = inspect.getargspec(method) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords def fetch_doc(cls, name): try: method = getattr(cls, name) if method.__doc__!=None: return inspect.getdoc(method) except: pass for parent in filter(lambda a: a!=cls, inspect.getmro(cls)): ret = fetch_doc(parent, name) if ret!=None: return ret return None doc = fetch_doc(cls, name) self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_classes += ' %s\n\n'%doc variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float)) for name, var in variables: if not name.startswith('__'): self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
[ [ 1, 0, 0.0634, 0.0049, 0, 0.66, 0, 291, 0, 1, 0, 0, 291, 0, 0 ], [ 1, 0, 0.0683, 0.0049, 0, 0.66, 0.5, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 3, 0, 0.5439, 0.9171, 0, 0.6...
[ "import pydoc", "import inspect", "class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from ctypes import * def setProcName(name): """Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases.""" # Call the process control function... libc = cdll.LoadLibrary('libc.so.6') libc.prctl(15, c_char_p(name), 0, 0, 0) # Update argv... charPP = POINTER(POINTER(c_char)) argv = charPP.in_dll(libc,'_dl_argv') size = libc.strlen(argv[0]) libc.strncpy(argv[0],c_char_p(name),size) if __name__=='__main__': # Quick test that it works... import os ps1 = 'ps' ps2 = 'ps -f' os.system(ps1) os.system(ps2) setProcName('wibble_wobble') os.system(ps1) os.system(ps2)
[ [ 1, 0, 0.3636, 0.0227, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 2, 0, 0.5682, 0.25, 0, 0.66, 0.5, 903, 0, 1, 0, 0, 0, 0, 9 ], [ 8, 1, 0.4773, 0.0227, 1, 0.79, ...
[ "from ctypes import *", "def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import multiprocessing as mp import multiprocessing.synchronize # To make sure we have all the functionality. import types import marshal import unittest def repeat(x): """A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant.""" while True: yield x def run_code(code,args): """Internal use function that does the work in each process.""" code = marshal.loads(code) func = types.FunctionType(code, globals(), '_') return func(*args) def mp_map(func, *iters, **keywords): """A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity.""" if 'pool' in keywords: pool = keywords['pool'] else: pool = mp.Pool() code = marshal.dumps(func.func_code) jobs = [] for args in zip(*iters): jobs.append(pool.apply_async(run_code,(code,args))) for i in xrange(len(jobs)): jobs[i] = jobs[i].get() return jobs class TestMpMap(unittest.TestCase): def test_simple1(self): data = ['a','b','c','d'] def noop(data): return data data_noop = mp_map(noop, data) self.assertEqual(data, data_noop) def test_simple2(self): data = [x for x in xrange(1000)] data_double = mp_map(lambda a: a*2, data) self.assertEqual(map(lambda a: a*2,data), data_double) def test_gen(self): def gen(): for i in xrange(100): yield i data_double = mp_map(lambda a: a*2, gen()) self.assertEqual(map(lambda a: a*2,gen()), data_double) def test_repeat(self): def mult(a,b): return a*b data = [x for x in xrange(50,5000,5)] data_triple = mp_map(mult, data, repeat(3)) self.assertEqual(map(lambda a: a*3,data),data_triple) def test_none(self): data = [] data_sqr = mp_map(lambda x: x*x, data) self.assertEqual([],data_sqr) if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.1456, 0.0097, 0, 0.66, 0, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 1, 0, 0.1553, 0.0097, 0, 0.66, 0.1111, 99, 0, 1, 0, 0, 99, 0, 0 ], [ 1, 0, 0.1748, 0.0097, 0, 0....
[ "import multiprocessing as mp", "import multiprocessing.synchronize # To make sure we have all the functionality.", "import types", "import marshal", "import unittest", "def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Defines helper functions for accessing numpy arrays... numpy_util_code = start_cpp() + """ #ifndef NUMPY_UTIL_CODE #define NUMPY_UTIL_CODE float & Float1D(PyArrayObject * arr, int index = 0) { return *(float*)(arr->data + index*arr->strides[0]); } float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } unsigned char & Byte1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index*arr->strides[0]); } unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } int & Int1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index*arr->strides[0]); } int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } #endif """
[ [ 1, 0, 0.1923, 0.0128, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.6282, 0.7564, 0, 0.66, 1, 799, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}" ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import cvarray import mp_map import prog_bar import numpy_help_cpp import python_obj_cpp import matrix_cpp import gamma_cpp import setProcName import start_cpp import make import doc_gen # Setup... doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.') doc.addFile('readme.txt', 'Overview') # Variables... doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.') doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.') doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++') doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++') # Functions... doc.addFunction(make.make_mod) doc.addFunction(cvarray.cv2array) doc.addFunction(cvarray.array2cv) doc.addFunction(mp_map.repeat) doc.addFunction(mp_map.mp_map) doc.addFunction(setProcName.setProcName) doc.addFunction(start_cpp.start_cpp) doc.addFunction(make.make_mod) # Classes... doc.addClass(prog_bar.ProgBar) doc.addClass(doc_gen.DocGen)
[ [ 1, 0, 0.2857, 0.0179, 0, 0.66, 0, 192, 0, 1, 0, 0, 192, 0, 0 ], [ 1, 0, 0.3036, 0.0179, 0, 0.66, 0.0385, 905, 0, 1, 0, 0, 905, 0, 0 ], [ 1, 0, 0.3214, 0.0179, 0, ...
[ "import cvarray", "import mp_map", "import prog_bar", "import numpy_help_cpp", "import python_obj_cpp", "import matrix_cpp", "import gamma_cpp", "import setProcName", "import start_cpp", "import make", "import doc_gen", "doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc...
# Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest import random import math from scipy.special import gammaln, psi, polygamma from scipy import weave from utils.start_cpp import start_cpp # Provides various gamma-related functions... gamma_code = start_cpp() + """ #ifndef GAMMA_CODE #define GAMMA_CODE #include <cmath> // Returns the natural logarithm of the Gamma function... // (Uses Lanczos's approximation.) double lnGamma(double z) { static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7}; if (z<0.5) { // Use reflection formula, as approximation doesn't work down here... return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z); } else { double x = coeff[0]; for (int i=1;i<9;i++) x += coeff[i]/(z+i-1); double t = z + 6.5; return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x); } } // Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values... double digamma(double z) { static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point. double ret = 0.0; while (z<highVal) { ret -= 1.0/z; z += 1.0; } double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz4 = iz2*iz2; double iz6 = iz4*iz2; ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0; return ret; } // Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically... double trigamma(double z) { static const double highVal = 8.0; double ret = 0.0; while (z<highVal) { ret += 1.0/(z*z); z += 1.0; } z -= 1.0; double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz3 = iz1*iz2; double iz5 = iz3*iz2; double iz7 = iz5*iz2; double iz9 = iz7*iz2; ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0; return ret; } #endif """ def lnGamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function""" code = start_cpp(gamma_code) + """ return_val = lnGamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def digamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function""" code = start_cpp(gamma_code) + """ return_val = digamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def trigamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function""" code = start_cpp(gamma_code) + """ return_val = trigamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) class TestFuncs(unittest.TestCase): """Test code for the assorted gamma-related functions.""" def test_compile(self): code = start_cpp(gamma_code) + """ """ weave.inline(code, support_code=gamma_code) def test_error_lngamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = lnGamma(z) good = gammaln(z) assert(math.fabs(own-good)<1e-12) def test_error_digamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = digamma(z) good = psi(z) assert(math.fabs(own-good)<1e-9) def test_error_trigamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = trigamma(z) good = polygamma(1,z) assert(math.fabs(own-good)<1e-9) # If this file is run do the unit tests... if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.0818, 0.0063, 0, 0.66, 0, 88, 0, 1, 0, 0, 88, 0, 0 ], [ 1, 0, 0.0881, 0.0063, 0, 0.66, 0.0909, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0943, 0.0063, 0, 0....
[ "import unittest", "import random", "import math", "from scipy.special import gammaln, psi, polygamma", "from scipy import weave", "from utils.start_cpp import start_cpp", "gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import inspect import hashlib def start_cpp(hash_str = None): """This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>""" frame = inspect.currentframe().f_back info = inspect.getframeinfo(frame) if hash_str==None: return '#line %i "%s"\n'%(info[1],info[0]) else: h = hashlib.md5() h.update(hash_str) hash_val = h.hexdigest() return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
[ [ 1, 0, 0.5, 0.0333, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.5333, 0.0333, 0, 0.66, 0.5, 154, 0, 1, 0, 0, 154, 0, 0 ], [ 2, 0, 0.8333, 0.3667, 0, 0.66, ...
[ "import inspect", "import hashlib", "def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os.path import tempfile import shutil from distutils.core import setup, Extension import distutils.ccompiler import distutils.dep_util try: __default_compiler = distutils.ccompiler.new_compiler() except: __default_compiler = None def make_mod(name, base, source, openCL = False): """Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place.""" if __default_compiler==None: raise Exception('No compiler!') # Work out the various file names - check if we actually need to do anything... if not isinstance(source, list): source = [source] source_path = map(lambda s: os.path.join(base, s), source) library_path = os.path.join(base, __default_compiler.shared_object_filename(name)) if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)): try: print 'b' # Backup the argv variable and create a temporary directory to do all work in... old_argv = sys.argv[:] temp_dir = tempfile.mkdtemp() # Prepare the extension... sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir] comp_path = filter(lambda s: not s.endswith('.h'), source_path) depends = filter(lambda s: s.endswith('.h'), source_path) if openCL: ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends) else: ext = Extension(name, comp_path, depends=depends) # Compile... setup(name=name, version='1.0.0', ext_modules=[ext]) finally: # Cleanup the argv variable and the temporary directory... sys.argv = old_argv shutil.rmtree(temp_dir, True)
[ [ 1, 0, 0.2031, 0.0156, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2188, 0.0156, 0, 0.66, 0.125, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.2344, 0.0156, 0, 0.6...
[ "import sys", "import os.path", "import tempfile", "import shutil", "from distutils.core import setup, Extension", "import distutils.ccompiler", "import distutils.dep_util", "try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None", " __default_compiler...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pydoc import inspect class DocGen: """A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.""" def __init__(self, name, title = None, summary = None): """name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title.""" if title==None: title = name if summary==None: summary = title self.doc = pydoc.HTMLDoc() self.html = open('%s.html'%name,'w') self.html.write('<html>\n') self.html.write('<head>\n') self.html.write('<title>%s</title>\n'%title) self.html.write('</head>\n') self.html.write('<body>\n') self.html_variables = '' self.html_functions = '' self.html_classes = '' self.wiki = open('%s.wiki'%name,'w') self.wiki.write('#summary %s\n\n'%summary) self.wiki.write('= %s= \n\n'%title) self.wiki_variables = '' self.wiki_functions = '' self.wiki_classes = '' def __del__(self): if self.html_variables!='': self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables)) if self.html_functions!='': self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions)) if self.html_classes!='': self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes)) self.html.write('</body>\n') self.html.write('</html>\n') self.html.close() if self.wiki_variables!='': self.wiki.write('= Variables =\n\n') self.wiki.write(self.wiki_variables) self.wiki.write('\n') if self.wiki_functions!='': self.wiki.write('= Functions =\n\n') self.wiki.write(self.wiki_functions) self.wiki.write('\n') if self.wiki_classes!='': self.wiki.write('= Classes =\n\n') self.wiki.write(self.wiki_classes) self.wiki.write('\n') self.wiki.close() def addFile(self, fn, title, fls = True): """Given a filename and section title adds the contents of said file to the output. Various flags influence how this works.""" html = [] wiki = [] for i, line in enumerate(open(fn,'r').readlines()): hl = line.replace('\n', '') if i==0 and fls: hl = '<strong>' + hl + '</strong>' for ext in ['py','txt']: if '.%s - '%ext in hl: s = hl.split('.%s - '%ext, 1) hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1] html.append(hl) wl = line.strip() if i==0 and fls: wl = '*%s*'%wl for ext in ['py','txt']: if '.%s - '%ext in wl: s = wl.split('.%s - '%ext, 1) wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n' wiki.append(wl) self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html))) self.wiki.write('== %s ==\n'%title) self.wiki.write('\n'.join(wiki)) self.wiki.write('----\n\n') def addVariable(self, var, desc): """Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc..""" self.html_variables += '<strong>%s</strong><br/>'%var self.html_variables += '%s<br/><br/>\n'%desc self.wiki_variables += '*`%s`*\n'%var self.wiki_variables += ' %s\n\n'%desc def addFunction(self, func): """Adds a function to the documentation. You provide the actual function instance.""" self.html_functions += self.doc.docroutine(func).replace('&nbsp;',' ') self.html_functions += '\n' name = func.__name__ args, varargs, keywords, defaults = inspect.getargspec(func) doc = inspect.getdoc(func) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_functions += ' %s\n\n'%doc def addClass(self, cls): """Adds a class to the documentation. You provide the actual class object.""" self.html_classes += self.doc.docclass(cls).replace('&nbsp;',' ') self.html_classes += '\n' name = cls.__name__ parents = filter(lambda a: a!=cls, inspect.getmro(cls)) doc = inspect.getdoc(cls) par_str = '' if len(parents)!=0: par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents)) self.wiki_classes += '== %s(%s) ==\n'%(name, par_str) self.wiki_classes += ' %s\n\n'%doc methods = inspect.getmembers(cls, inspect.ismethod) def method_key(pair): if pair[0]=='__init__': return '___' else: return pair[0] methods.sort(key=method_key) for name, method in methods: if not name.startswith('_%s'%cls.__name__): args, varargs, keywords, defaults = inspect.getargspec(method) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords def fetch_doc(cls, name): try: method = getattr(cls, name) if method.__doc__!=None: return inspect.getdoc(method) except: pass for parent in filter(lambda a: a!=cls, inspect.getmro(cls)): ret = fetch_doc(parent, name) if ret!=None: return ret return None doc = fetch_doc(cls, name) self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_classes += ' %s\n\n'%doc variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float)) for name, var in variables: if not name.startswith('__'): self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
[ [ 1, 0, 0.0634, 0.0049, 0, 0.66, 0, 291, 0, 1, 0, 0, 291, 0, 0 ], [ 1, 0, 0.0683, 0.0049, 0, 0.66, 0.5, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 3, 0, 0.5439, 0.9171, 0, 0.6...
[ "import pydoc", "import inspect", "class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from ctypes import * def setProcName(name): """Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases.""" # Call the process control function... libc = cdll.LoadLibrary('libc.so.6') libc.prctl(15, c_char_p(name), 0, 0, 0) # Update argv... charPP = POINTER(POINTER(c_char)) argv = charPP.in_dll(libc,'_dl_argv') size = libc.strlen(argv[0]) libc.strncpy(argv[0],c_char_p(name),size) if __name__=='__main__': # Quick test that it works... import os ps1 = 'ps' ps2 = 'ps -f' os.system(ps1) os.system(ps2) setProcName('wibble_wobble') os.system(ps1) os.system(ps2)
[ [ 1, 0, 0.3636, 0.0227, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 2, 0, 0.5682, 0.25, 0, 0.66, 0.5, 903, 0, 1, 0, 0, 0, 0, 9 ], [ 8, 1, 0.4773, 0.0227, 1, 0.31, ...
[ "from ctypes import *", "def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import multiprocessing as mp import multiprocessing.synchronize # To make sure we have all the functionality. import types import marshal import unittest def repeat(x): """A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant.""" while True: yield x def run_code(code,args): """Internal use function that does the work in each process.""" code = marshal.loads(code) func = types.FunctionType(code, globals(), '_') return func(*args) def mp_map(func, *iters, **keywords): """A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity.""" if 'pool' in keywords: pool = keywords['pool'] else: pool = mp.Pool() code = marshal.dumps(func.func_code) jobs = [] for args in zip(*iters): jobs.append(pool.apply_async(run_code,(code,args))) for i in xrange(len(jobs)): jobs[i] = jobs[i].get() return jobs class TestMpMap(unittest.TestCase): def test_simple1(self): data = ['a','b','c','d'] def noop(data): return data data_noop = mp_map(noop, data) self.assertEqual(data, data_noop) def test_simple2(self): data = [x for x in xrange(1000)] data_double = mp_map(lambda a: a*2, data) self.assertEqual(map(lambda a: a*2,data), data_double) def test_gen(self): def gen(): for i in xrange(100): yield i data_double = mp_map(lambda a: a*2, gen()) self.assertEqual(map(lambda a: a*2,gen()), data_double) def test_repeat(self): def mult(a,b): return a*b data = [x for x in xrange(50,5000,5)] data_triple = mp_map(mult, data, repeat(3)) self.assertEqual(map(lambda a: a*3,data),data_triple) def test_none(self): data = [] data_sqr = mp_map(lambda x: x*x, data) self.assertEqual([],data_sqr) if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.1456, 0.0097, 0, 0.66, 0, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 1, 0, 0.1553, 0.0097, 0, 0.66, 0.1111, 99, 0, 1, 0, 0, 99, 0, 0 ], [ 1, 0, 0.1748, 0.0097, 0, 0....
[ "import multiprocessing as mp", "import multiprocessing.synchronize # To make sure we have all the functionality.", "import types", "import marshal", "import unittest", "def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Defines helper functions for accessing numpy arrays... numpy_util_code = start_cpp() + """ #ifndef NUMPY_UTIL_CODE #define NUMPY_UTIL_CODE float & Float1D(PyArrayObject * arr, int index = 0) { return *(float*)(arr->data + index*arr->strides[0]); } float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } unsigned char & Byte1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index*arr->strides[0]); } unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } int & Int1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index*arr->strides[0]); } int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } #endif """
[ [ 1, 0, 0.1923, 0.0128, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.6282, 0.7564, 0, 0.66, 1, 799, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}" ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import cvarray import mp_map import prog_bar import numpy_help_cpp import python_obj_cpp import matrix_cpp import gamma_cpp import setProcName import start_cpp import make import doc_gen # Setup... doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.') doc.addFile('readme.txt', 'Overview') # Variables... doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.') doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.') doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++') doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++') # Functions... doc.addFunction(make.make_mod) doc.addFunction(cvarray.cv2array) doc.addFunction(cvarray.array2cv) doc.addFunction(mp_map.repeat) doc.addFunction(mp_map.mp_map) doc.addFunction(setProcName.setProcName) doc.addFunction(start_cpp.start_cpp) doc.addFunction(make.make_mod) # Classes... doc.addClass(prog_bar.ProgBar) doc.addClass(doc_gen.DocGen)
[ [ 1, 0, 0.2857, 0.0179, 0, 0.66, 0, 192, 0, 1, 0, 0, 192, 0, 0 ], [ 1, 0, 0.3036, 0.0179, 0, 0.66, 0.0385, 905, 0, 1, 0, 0, 905, 0, 0 ], [ 1, 0, 0.3214, 0.0179, 0, ...
[ "import cvarray", "import mp_map", "import prog_bar", "import numpy_help_cpp", "import python_obj_cpp", "import matrix_cpp", "import gamma_cpp", "import setProcName", "import start_cpp", "import make", "import doc_gen", "doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc...
# Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest import random import math from scipy.special import gammaln, psi, polygamma from scipy import weave from utils.start_cpp import start_cpp # Provides various gamma-related functions... gamma_code = start_cpp() + """ #ifndef GAMMA_CODE #define GAMMA_CODE #include <cmath> // Returns the natural logarithm of the Gamma function... // (Uses Lanczos's approximation.) double lnGamma(double z) { static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7}; if (z<0.5) { // Use reflection formula, as approximation doesn't work down here... return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z); } else { double x = coeff[0]; for (int i=1;i<9;i++) x += coeff[i]/(z+i-1); double t = z + 6.5; return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x); } } // Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values... double digamma(double z) { static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point. double ret = 0.0; while (z<highVal) { ret -= 1.0/z; z += 1.0; } double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz4 = iz2*iz2; double iz6 = iz4*iz2; ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0; return ret; } // Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically... double trigamma(double z) { static const double highVal = 8.0; double ret = 0.0; while (z<highVal) { ret += 1.0/(z*z); z += 1.0; } z -= 1.0; double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz3 = iz1*iz2; double iz5 = iz3*iz2; double iz7 = iz5*iz2; double iz9 = iz7*iz2; ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0; return ret; } #endif """ def lnGamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function""" code = start_cpp(gamma_code) + """ return_val = lnGamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def digamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function""" code = start_cpp(gamma_code) + """ return_val = digamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def trigamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function""" code = start_cpp(gamma_code) + """ return_val = trigamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) class TestFuncs(unittest.TestCase): """Test code for the assorted gamma-related functions.""" def test_compile(self): code = start_cpp(gamma_code) + """ """ weave.inline(code, support_code=gamma_code) def test_error_lngamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = lnGamma(z) good = gammaln(z) assert(math.fabs(own-good)<1e-12) def test_error_digamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = digamma(z) good = psi(z) assert(math.fabs(own-good)<1e-9) def test_error_trigamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = trigamma(z) good = polygamma(1,z) assert(math.fabs(own-good)<1e-9) # If this file is run do the unit tests... if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.0818, 0.0063, 0, 0.66, 0, 88, 0, 1, 0, 0, 88, 0, 0 ], [ 1, 0, 0.0881, 0.0063, 0, 0.66, 0.0909, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0943, 0.0063, 0, 0....
[ "import unittest", "import random", "import math", "from scipy.special import gammaln, psi, polygamma", "from scipy import weave", "from utils.start_cpp import start_cpp", "gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import inspect import hashlib def start_cpp(hash_str = None): """This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>""" frame = inspect.currentframe().f_back info = inspect.getframeinfo(frame) if hash_str==None: return '#line %i "%s"\n'%(info[1],info[0]) else: h = hashlib.md5() h.update(hash_str) hash_val = h.hexdigest() return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
[ [ 1, 0, 0.5, 0.0333, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.5333, 0.0333, 0, 0.66, 0.5, 154, 0, 1, 0, 0, 154, 0, 0 ], [ 2, 0, 0.8333, 0.3667, 0, 0.66, ...
[ "import inspect", "import hashlib", "def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os.path import tempfile import shutil from distutils.core import setup, Extension import distutils.ccompiler import distutils.dep_util try: __default_compiler = distutils.ccompiler.new_compiler() except: __default_compiler = None def make_mod(name, base, source, openCL = False): """Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place.""" if __default_compiler==None: raise Exception('No compiler!') # Work out the various file names - check if we actually need to do anything... if not isinstance(source, list): source = [source] source_path = map(lambda s: os.path.join(base, s), source) library_path = os.path.join(base, __default_compiler.shared_object_filename(name)) if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)): try: print 'b' # Backup the argv variable and create a temporary directory to do all work in... old_argv = sys.argv[:] temp_dir = tempfile.mkdtemp() # Prepare the extension... sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir] comp_path = filter(lambda s: not s.endswith('.h'), source_path) depends = filter(lambda s: s.endswith('.h'), source_path) if openCL: ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends) else: ext = Extension(name, comp_path, depends=depends) # Compile... setup(name=name, version='1.0.0', ext_modules=[ext]) finally: # Cleanup the argv variable and the temporary directory... sys.argv = old_argv shutil.rmtree(temp_dir, True)
[ [ 1, 0, 0.2031, 0.0156, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2188, 0.0156, 0, 0.66, 0.125, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.2344, 0.0156, 0, 0.6...
[ "import sys", "import os.path", "import tempfile", "import shutil", "from distutils.core import setup, Extension", "import distutils.ccompiler", "import distutils.dep_util", "try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None", " __default_compiler...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pydoc import inspect class DocGen: """A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.""" def __init__(self, name, title = None, summary = None): """name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title.""" if title==None: title = name if summary==None: summary = title self.doc = pydoc.HTMLDoc() self.html = open('%s.html'%name,'w') self.html.write('<html>\n') self.html.write('<head>\n') self.html.write('<title>%s</title>\n'%title) self.html.write('</head>\n') self.html.write('<body>\n') self.html_variables = '' self.html_functions = '' self.html_classes = '' self.wiki = open('%s.wiki'%name,'w') self.wiki.write('#summary %s\n\n'%summary) self.wiki.write('= %s= \n\n'%title) self.wiki_variables = '' self.wiki_functions = '' self.wiki_classes = '' def __del__(self): if self.html_variables!='': self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables)) if self.html_functions!='': self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions)) if self.html_classes!='': self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes)) self.html.write('</body>\n') self.html.write('</html>\n') self.html.close() if self.wiki_variables!='': self.wiki.write('= Variables =\n\n') self.wiki.write(self.wiki_variables) self.wiki.write('\n') if self.wiki_functions!='': self.wiki.write('= Functions =\n\n') self.wiki.write(self.wiki_functions) self.wiki.write('\n') if self.wiki_classes!='': self.wiki.write('= Classes =\n\n') self.wiki.write(self.wiki_classes) self.wiki.write('\n') self.wiki.close() def addFile(self, fn, title, fls = True): """Given a filename and section title adds the contents of said file to the output. Various flags influence how this works.""" html = [] wiki = [] for i, line in enumerate(open(fn,'r').readlines()): hl = line.replace('\n', '') if i==0 and fls: hl = '<strong>' + hl + '</strong>' for ext in ['py','txt']: if '.%s - '%ext in hl: s = hl.split('.%s - '%ext, 1) hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1] html.append(hl) wl = line.strip() if i==0 and fls: wl = '*%s*'%wl for ext in ['py','txt']: if '.%s - '%ext in wl: s = wl.split('.%s - '%ext, 1) wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n' wiki.append(wl) self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html))) self.wiki.write('== %s ==\n'%title) self.wiki.write('\n'.join(wiki)) self.wiki.write('----\n\n') def addVariable(self, var, desc): """Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc..""" self.html_variables += '<strong>%s</strong><br/>'%var self.html_variables += '%s<br/><br/>\n'%desc self.wiki_variables += '*`%s`*\n'%var self.wiki_variables += ' %s\n\n'%desc def addFunction(self, func): """Adds a function to the documentation. You provide the actual function instance.""" self.html_functions += self.doc.docroutine(func).replace('&nbsp;',' ') self.html_functions += '\n' name = func.__name__ args, varargs, keywords, defaults = inspect.getargspec(func) doc = inspect.getdoc(func) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_functions += ' %s\n\n'%doc def addClass(self, cls): """Adds a class to the documentation. You provide the actual class object.""" self.html_classes += self.doc.docclass(cls).replace('&nbsp;',' ') self.html_classes += '\n' name = cls.__name__ parents = filter(lambda a: a!=cls, inspect.getmro(cls)) doc = inspect.getdoc(cls) par_str = '' if len(parents)!=0: par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents)) self.wiki_classes += '== %s(%s) ==\n'%(name, par_str) self.wiki_classes += ' %s\n\n'%doc methods = inspect.getmembers(cls, inspect.ismethod) def method_key(pair): if pair[0]=='__init__': return '___' else: return pair[0] methods.sort(key=method_key) for name, method in methods: if not name.startswith('_%s'%cls.__name__): args, varargs, keywords, defaults = inspect.getargspec(method) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords def fetch_doc(cls, name): try: method = getattr(cls, name) if method.__doc__!=None: return inspect.getdoc(method) except: pass for parent in filter(lambda a: a!=cls, inspect.getmro(cls)): ret = fetch_doc(parent, name) if ret!=None: return ret return None doc = fetch_doc(cls, name) self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_classes += ' %s\n\n'%doc variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float)) for name, var in variables: if not name.startswith('__'): self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
[ [ 1, 0, 0.0634, 0.0049, 0, 0.66, 0, 291, 0, 1, 0, 0, 291, 0, 0 ], [ 1, 0, 0.0683, 0.0049, 0, 0.66, 0.5, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 3, 0, 0.5439, 0.9171, 0, 0.6...
[ "import pydoc", "import inspect", "class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from ctypes import * def setProcName(name): """Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases.""" # Call the process control function... libc = cdll.LoadLibrary('libc.so.6') libc.prctl(15, c_char_p(name), 0, 0, 0) # Update argv... charPP = POINTER(POINTER(c_char)) argv = charPP.in_dll(libc,'_dl_argv') size = libc.strlen(argv[0]) libc.strncpy(argv[0],c_char_p(name),size) if __name__=='__main__': # Quick test that it works... import os ps1 = 'ps' ps2 = 'ps -f' os.system(ps1) os.system(ps2) setProcName('wibble_wobble') os.system(ps1) os.system(ps2)
[ [ 1, 0, 0.3636, 0.0227, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 2, 0, 0.5682, 0.25, 0, 0.66, 0.5, 903, 0, 1, 0, 0, 0, 0, 9 ], [ 8, 1, 0.4773, 0.0227, 1, 0.55, ...
[ "from ctypes import *", "def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import multiprocessing as mp import multiprocessing.synchronize # To make sure we have all the functionality. import types import marshal import unittest def repeat(x): """A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant.""" while True: yield x def run_code(code,args): """Internal use function that does the work in each process.""" code = marshal.loads(code) func = types.FunctionType(code, globals(), '_') return func(*args) def mp_map(func, *iters, **keywords): """A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity.""" if 'pool' in keywords: pool = keywords['pool'] else: pool = mp.Pool() code = marshal.dumps(func.func_code) jobs = [] for args in zip(*iters): jobs.append(pool.apply_async(run_code,(code,args))) for i in xrange(len(jobs)): jobs[i] = jobs[i].get() return jobs class TestMpMap(unittest.TestCase): def test_simple1(self): data = ['a','b','c','d'] def noop(data): return data data_noop = mp_map(noop, data) self.assertEqual(data, data_noop) def test_simple2(self): data = [x for x in xrange(1000)] data_double = mp_map(lambda a: a*2, data) self.assertEqual(map(lambda a: a*2,data), data_double) def test_gen(self): def gen(): for i in xrange(100): yield i data_double = mp_map(lambda a: a*2, gen()) self.assertEqual(map(lambda a: a*2,gen()), data_double) def test_repeat(self): def mult(a,b): return a*b data = [x for x in xrange(50,5000,5)] data_triple = mp_map(mult, data, repeat(3)) self.assertEqual(map(lambda a: a*3,data),data_triple) def test_none(self): data = [] data_sqr = mp_map(lambda x: x*x, data) self.assertEqual([],data_sqr) if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.1456, 0.0097, 0, 0.66, 0, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 1, 0, 0.1553, 0.0097, 0, 0.66, 0.1111, 99, 0, 1, 0, 0, 99, 0, 0 ], [ 1, 0, 0.1748, 0.0097, 0, 0....
[ "import multiprocessing as mp", "import multiprocessing.synchronize # To make sure we have all the functionality.", "import types", "import marshal", "import unittest", "def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Defines helper functions for accessing numpy arrays... numpy_util_code = start_cpp() + """ #ifndef NUMPY_UTIL_CODE #define NUMPY_UTIL_CODE float & Float1D(PyArrayObject * arr, int index = 0) { return *(float*)(arr->data + index*arr->strides[0]); } float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } unsigned char & Byte1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index*arr->strides[0]); } unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } int & Int1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index*arr->strides[0]); } int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } #endif """
[ [ 1, 0, 0.1923, 0.0128, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.6282, 0.7564, 0, 0.66, 1, 799, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}" ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import cvarray import mp_map import prog_bar import numpy_help_cpp import python_obj_cpp import matrix_cpp import gamma_cpp import setProcName import start_cpp import make import doc_gen # Setup... doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.') doc.addFile('readme.txt', 'Overview') # Variables... doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.') doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.') doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++') doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++') # Functions... doc.addFunction(make.make_mod) doc.addFunction(cvarray.cv2array) doc.addFunction(cvarray.array2cv) doc.addFunction(mp_map.repeat) doc.addFunction(mp_map.mp_map) doc.addFunction(setProcName.setProcName) doc.addFunction(start_cpp.start_cpp) doc.addFunction(make.make_mod) # Classes... doc.addClass(prog_bar.ProgBar) doc.addClass(doc_gen.DocGen)
[ [ 1, 0, 0.2857, 0.0179, 0, 0.66, 0, 192, 0, 1, 0, 0, 192, 0, 0 ], [ 1, 0, 0.3036, 0.0179, 0, 0.66, 0.0385, 905, 0, 1, 0, 0, 905, 0, 0 ], [ 1, 0, 0.3214, 0.0179, 0, ...
[ "import cvarray", "import mp_map", "import prog_bar", "import numpy_help_cpp", "import python_obj_cpp", "import matrix_cpp", "import gamma_cpp", "import setProcName", "import start_cpp", "import make", "import doc_gen", "doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc...
# Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest import random import math from scipy.special import gammaln, psi, polygamma from scipy import weave from utils.start_cpp import start_cpp # Provides various gamma-related functions... gamma_code = start_cpp() + """ #ifndef GAMMA_CODE #define GAMMA_CODE #include <cmath> // Returns the natural logarithm of the Gamma function... // (Uses Lanczos's approximation.) double lnGamma(double z) { static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7}; if (z<0.5) { // Use reflection formula, as approximation doesn't work down here... return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z); } else { double x = coeff[0]; for (int i=1;i<9;i++) x += coeff[i]/(z+i-1); double t = z + 6.5; return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x); } } // Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values... double digamma(double z) { static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point. double ret = 0.0; while (z<highVal) { ret -= 1.0/z; z += 1.0; } double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz4 = iz2*iz2; double iz6 = iz4*iz2; ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0; return ret; } // Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically... double trigamma(double z) { static const double highVal = 8.0; double ret = 0.0; while (z<highVal) { ret += 1.0/(z*z); z += 1.0; } z -= 1.0; double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz3 = iz1*iz2; double iz5 = iz3*iz2; double iz7 = iz5*iz2; double iz9 = iz7*iz2; ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0; return ret; } #endif """ def lnGamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function""" code = start_cpp(gamma_code) + """ return_val = lnGamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def digamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function""" code = start_cpp(gamma_code) + """ return_val = digamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def trigamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function""" code = start_cpp(gamma_code) + """ return_val = trigamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) class TestFuncs(unittest.TestCase): """Test code for the assorted gamma-related functions.""" def test_compile(self): code = start_cpp(gamma_code) + """ """ weave.inline(code, support_code=gamma_code) def test_error_lngamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = lnGamma(z) good = gammaln(z) assert(math.fabs(own-good)<1e-12) def test_error_digamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = digamma(z) good = psi(z) assert(math.fabs(own-good)<1e-9) def test_error_trigamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = trigamma(z) good = polygamma(1,z) assert(math.fabs(own-good)<1e-9) # If this file is run do the unit tests... if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.0818, 0.0063, 0, 0.66, 0, 88, 0, 1, 0, 0, 88, 0, 0 ], [ 1, 0, 0.0881, 0.0063, 0, 0.66, 0.0909, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0943, 0.0063, 0, 0....
[ "import unittest", "import random", "import math", "from scipy.special import gammaln, psi, polygamma", "from scipy import weave", "from utils.start_cpp import start_cpp", "gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import inspect import hashlib def start_cpp(hash_str = None): """This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>""" frame = inspect.currentframe().f_back info = inspect.getframeinfo(frame) if hash_str==None: return '#line %i "%s"\n'%(info[1],info[0]) else: h = hashlib.md5() h.update(hash_str) hash_val = h.hexdigest() return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
[ [ 1, 0, 0.5, 0.0333, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.5333, 0.0333, 0, 0.66, 0.5, 154, 0, 1, 0, 0, 154, 0, 0 ], [ 2, 0, 0.8333, 0.3667, 0, 0.66, ...
[ "import inspect", "import hashlib", "def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os.path import tempfile import shutil from distutils.core import setup, Extension import distutils.ccompiler import distutils.dep_util try: __default_compiler = distutils.ccompiler.new_compiler() except: __default_compiler = None def make_mod(name, base, source, openCL = False): """Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place.""" if __default_compiler==None: raise Exception('No compiler!') # Work out the various file names - check if we actually need to do anything... if not isinstance(source, list): source = [source] source_path = map(lambda s: os.path.join(base, s), source) library_path = os.path.join(base, __default_compiler.shared_object_filename(name)) if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)): try: print 'b' # Backup the argv variable and create a temporary directory to do all work in... old_argv = sys.argv[:] temp_dir = tempfile.mkdtemp() # Prepare the extension... sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir] comp_path = filter(lambda s: not s.endswith('.h'), source_path) depends = filter(lambda s: s.endswith('.h'), source_path) if openCL: ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends) else: ext = Extension(name, comp_path, depends=depends) # Compile... setup(name=name, version='1.0.0', ext_modules=[ext]) finally: # Cleanup the argv variable and the temporary directory... sys.argv = old_argv shutil.rmtree(temp_dir, True)
[ [ 1, 0, 0.2031, 0.0156, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2188, 0.0156, 0, 0.66, 0.125, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.2344, 0.0156, 0, 0.6...
[ "import sys", "import os.path", "import tempfile", "import shutil", "from distutils.core import setup, Extension", "import distutils.ccompiler", "import distutils.dep_util", "try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None", " __default_compiler...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pydoc import inspect class DocGen: """A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.""" def __init__(self, name, title = None, summary = None): """name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title.""" if title==None: title = name if summary==None: summary = title self.doc = pydoc.HTMLDoc() self.html = open('%s.html'%name,'w') self.html.write('<html>\n') self.html.write('<head>\n') self.html.write('<title>%s</title>\n'%title) self.html.write('</head>\n') self.html.write('<body>\n') self.html_variables = '' self.html_functions = '' self.html_classes = '' self.wiki = open('%s.wiki'%name,'w') self.wiki.write('#summary %s\n\n'%summary) self.wiki.write('= %s= \n\n'%title) self.wiki_variables = '' self.wiki_functions = '' self.wiki_classes = '' def __del__(self): if self.html_variables!='': self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables)) if self.html_functions!='': self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions)) if self.html_classes!='': self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes)) self.html.write('</body>\n') self.html.write('</html>\n') self.html.close() if self.wiki_variables!='': self.wiki.write('= Variables =\n\n') self.wiki.write(self.wiki_variables) self.wiki.write('\n') if self.wiki_functions!='': self.wiki.write('= Functions =\n\n') self.wiki.write(self.wiki_functions) self.wiki.write('\n') if self.wiki_classes!='': self.wiki.write('= Classes =\n\n') self.wiki.write(self.wiki_classes) self.wiki.write('\n') self.wiki.close() def addFile(self, fn, title, fls = True): """Given a filename and section title adds the contents of said file to the output. Various flags influence how this works.""" html = [] wiki = [] for i, line in enumerate(open(fn,'r').readlines()): hl = line.replace('\n', '') if i==0 and fls: hl = '<strong>' + hl + '</strong>' for ext in ['py','txt']: if '.%s - '%ext in hl: s = hl.split('.%s - '%ext, 1) hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1] html.append(hl) wl = line.strip() if i==0 and fls: wl = '*%s*'%wl for ext in ['py','txt']: if '.%s - '%ext in wl: s = wl.split('.%s - '%ext, 1) wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n' wiki.append(wl) self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html))) self.wiki.write('== %s ==\n'%title) self.wiki.write('\n'.join(wiki)) self.wiki.write('----\n\n') def addVariable(self, var, desc): """Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc..""" self.html_variables += '<strong>%s</strong><br/>'%var self.html_variables += '%s<br/><br/>\n'%desc self.wiki_variables += '*`%s`*\n'%var self.wiki_variables += ' %s\n\n'%desc def addFunction(self, func): """Adds a function to the documentation. You provide the actual function instance.""" self.html_functions += self.doc.docroutine(func).replace('&nbsp;',' ') self.html_functions += '\n' name = func.__name__ args, varargs, keywords, defaults = inspect.getargspec(func) doc = inspect.getdoc(func) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_functions += ' %s\n\n'%doc def addClass(self, cls): """Adds a class to the documentation. You provide the actual class object.""" self.html_classes += self.doc.docclass(cls).replace('&nbsp;',' ') self.html_classes += '\n' name = cls.__name__ parents = filter(lambda a: a!=cls, inspect.getmro(cls)) doc = inspect.getdoc(cls) par_str = '' if len(parents)!=0: par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents)) self.wiki_classes += '== %s(%s) ==\n'%(name, par_str) self.wiki_classes += ' %s\n\n'%doc methods = inspect.getmembers(cls, inspect.ismethod) def method_key(pair): if pair[0]=='__init__': return '___' else: return pair[0] methods.sort(key=method_key) for name, method in methods: if not name.startswith('_%s'%cls.__name__): args, varargs, keywords, defaults = inspect.getargspec(method) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords def fetch_doc(cls, name): try: method = getattr(cls, name) if method.__doc__!=None: return inspect.getdoc(method) except: pass for parent in filter(lambda a: a!=cls, inspect.getmro(cls)): ret = fetch_doc(parent, name) if ret!=None: return ret return None doc = fetch_doc(cls, name) self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_classes += ' %s\n\n'%doc variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float)) for name, var in variables: if not name.startswith('__'): self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
[ [ 1, 0, 0.0634, 0.0049, 0, 0.66, 0, 291, 0, 1, 0, 0, 291, 0, 0 ], [ 1, 0, 0.0683, 0.0049, 0, 0.66, 0.5, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 3, 0, 0.5439, 0.9171, 0, 0.6...
[ "import pydoc", "import inspect", "class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from ctypes import * def setProcName(name): """Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases.""" # Call the process control function... libc = cdll.LoadLibrary('libc.so.6') libc.prctl(15, c_char_p(name), 0, 0, 0) # Update argv... charPP = POINTER(POINTER(c_char)) argv = charPP.in_dll(libc,'_dl_argv') size = libc.strlen(argv[0]) libc.strncpy(argv[0],c_char_p(name),size) if __name__=='__main__': # Quick test that it works... import os ps1 = 'ps' ps2 = 'ps -f' os.system(ps1) os.system(ps2) setProcName('wibble_wobble') os.system(ps1) os.system(ps2)
[ [ 1, 0, 0.3636, 0.0227, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 2, 0, 0.5682, 0.25, 0, 0.66, 0.5, 903, 0, 1, 0, 0, 0, 0, 9 ], [ 8, 1, 0.4773, 0.0227, 1, 0.17, ...
[ "from ctypes import *", "def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import multiprocessing as mp import multiprocessing.synchronize # To make sure we have all the functionality. import types import marshal import unittest def repeat(x): """A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant.""" while True: yield x def run_code(code,args): """Internal use function that does the work in each process.""" code = marshal.loads(code) func = types.FunctionType(code, globals(), '_') return func(*args) def mp_map(func, *iters, **keywords): """A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity.""" if 'pool' in keywords: pool = keywords['pool'] else: pool = mp.Pool() code = marshal.dumps(func.func_code) jobs = [] for args in zip(*iters): jobs.append(pool.apply_async(run_code,(code,args))) for i in xrange(len(jobs)): jobs[i] = jobs[i].get() return jobs class TestMpMap(unittest.TestCase): def test_simple1(self): data = ['a','b','c','d'] def noop(data): return data data_noop = mp_map(noop, data) self.assertEqual(data, data_noop) def test_simple2(self): data = [x for x in xrange(1000)] data_double = mp_map(lambda a: a*2, data) self.assertEqual(map(lambda a: a*2,data), data_double) def test_gen(self): def gen(): for i in xrange(100): yield i data_double = mp_map(lambda a: a*2, gen()) self.assertEqual(map(lambda a: a*2,gen()), data_double) def test_repeat(self): def mult(a,b): return a*b data = [x for x in xrange(50,5000,5)] data_triple = mp_map(mult, data, repeat(3)) self.assertEqual(map(lambda a: a*3,data),data_triple) def test_none(self): data = [] data_sqr = mp_map(lambda x: x*x, data) self.assertEqual([],data_sqr) if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.1456, 0.0097, 0, 0.66, 0, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 1, 0, 0.1553, 0.0097, 0, 0.66, 0.1111, 99, 0, 1, 0, 0, 99, 0, 0 ], [ 1, 0, 0.1748, 0.0097, 0, 0....
[ "import multiprocessing as mp", "import multiprocessing.synchronize # To make sure we have all the functionality.", "import types", "import marshal", "import unittest", "def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Defines helper functions for accessing numpy arrays... numpy_util_code = start_cpp() + """ #ifndef NUMPY_UTIL_CODE #define NUMPY_UTIL_CODE float & Float1D(PyArrayObject * arr, int index = 0) { return *(float*)(arr->data + index*arr->strides[0]); } float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } unsigned char & Byte1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index*arr->strides[0]); } unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } int & Int1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index*arr->strides[0]); } int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } #endif """
[ [ 1, 0, 0.1923, 0.0128, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.6282, 0.7564, 0, 0.66, 1, 799, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}" ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import cvarray import mp_map import prog_bar import numpy_help_cpp import python_obj_cpp import matrix_cpp import gamma_cpp import setProcName import start_cpp import make import doc_gen # Setup... doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.') doc.addFile('readme.txt', 'Overview') # Variables... doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.') doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.') doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++') doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++') # Functions... doc.addFunction(make.make_mod) doc.addFunction(cvarray.cv2array) doc.addFunction(cvarray.array2cv) doc.addFunction(mp_map.repeat) doc.addFunction(mp_map.mp_map) doc.addFunction(setProcName.setProcName) doc.addFunction(start_cpp.start_cpp) doc.addFunction(make.make_mod) # Classes... doc.addClass(prog_bar.ProgBar) doc.addClass(doc_gen.DocGen)
[ [ 1, 0, 0.2857, 0.0179, 0, 0.66, 0, 192, 0, 1, 0, 0, 192, 0, 0 ], [ 1, 0, 0.3036, 0.0179, 0, 0.66, 0.0385, 905, 0, 1, 0, 0, 905, 0, 0 ], [ 1, 0, 0.3214, 0.0179, 0, ...
[ "import cvarray", "import mp_map", "import prog_bar", "import numpy_help_cpp", "import python_obj_cpp", "import matrix_cpp", "import gamma_cpp", "import setProcName", "import start_cpp", "import make", "import doc_gen", "doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc...
# Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest import random import math from scipy.special import gammaln, psi, polygamma from scipy import weave from utils.start_cpp import start_cpp # Provides various gamma-related functions... gamma_code = start_cpp() + """ #ifndef GAMMA_CODE #define GAMMA_CODE #include <cmath> // Returns the natural logarithm of the Gamma function... // (Uses Lanczos's approximation.) double lnGamma(double z) { static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7}; if (z<0.5) { // Use reflection formula, as approximation doesn't work down here... return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z); } else { double x = coeff[0]; for (int i=1;i<9;i++) x += coeff[i]/(z+i-1); double t = z + 6.5; return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x); } } // Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values... double digamma(double z) { static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point. double ret = 0.0; while (z<highVal) { ret -= 1.0/z; z += 1.0; } double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz4 = iz2*iz2; double iz6 = iz4*iz2; ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0; return ret; } // Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically... double trigamma(double z) { static const double highVal = 8.0; double ret = 0.0; while (z<highVal) { ret += 1.0/(z*z); z += 1.0; } z -= 1.0; double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz3 = iz1*iz2; double iz5 = iz3*iz2; double iz7 = iz5*iz2; double iz9 = iz7*iz2; ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0; return ret; } #endif """ def lnGamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function""" code = start_cpp(gamma_code) + """ return_val = lnGamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def digamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function""" code = start_cpp(gamma_code) + """ return_val = digamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def trigamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function""" code = start_cpp(gamma_code) + """ return_val = trigamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) class TestFuncs(unittest.TestCase): """Test code for the assorted gamma-related functions.""" def test_compile(self): code = start_cpp(gamma_code) + """ """ weave.inline(code, support_code=gamma_code) def test_error_lngamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = lnGamma(z) good = gammaln(z) assert(math.fabs(own-good)<1e-12) def test_error_digamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = digamma(z) good = psi(z) assert(math.fabs(own-good)<1e-9) def test_error_trigamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = trigamma(z) good = polygamma(1,z) assert(math.fabs(own-good)<1e-9) # If this file is run do the unit tests... if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.0818, 0.0063, 0, 0.66, 0, 88, 0, 1, 0, 0, 88, 0, 0 ], [ 1, 0, 0.0881, 0.0063, 0, 0.66, 0.0909, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0943, 0.0063, 0, 0....
[ "import unittest", "import random", "import math", "from scipy.special import gammaln, psi, polygamma", "from scipy import weave", "from utils.start_cpp import start_cpp", "gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import inspect import hashlib def start_cpp(hash_str = None): """This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>""" frame = inspect.currentframe().f_back info = inspect.getframeinfo(frame) if hash_str==None: return '#line %i "%s"\n'%(info[1],info[0]) else: h = hashlib.md5() h.update(hash_str) hash_val = h.hexdigest() return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
[ [ 1, 0, 0.5, 0.0333, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.5333, 0.0333, 0, 0.66, 0.5, 154, 0, 1, 0, 0, 154, 0, 0 ], [ 2, 0, 0.8333, 0.3667, 0, 0.66, ...
[ "import inspect", "import hashlib", "def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os.path import tempfile import shutil from distutils.core import setup, Extension import distutils.ccompiler import distutils.dep_util try: __default_compiler = distutils.ccompiler.new_compiler() except: __default_compiler = None def make_mod(name, base, source, openCL = False): """Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place.""" if __default_compiler==None: raise Exception('No compiler!') # Work out the various file names - check if we actually need to do anything... if not isinstance(source, list): source = [source] source_path = map(lambda s: os.path.join(base, s), source) library_path = os.path.join(base, __default_compiler.shared_object_filename(name)) if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)): try: print 'b' # Backup the argv variable and create a temporary directory to do all work in... old_argv = sys.argv[:] temp_dir = tempfile.mkdtemp() # Prepare the extension... sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir] comp_path = filter(lambda s: not s.endswith('.h'), source_path) depends = filter(lambda s: s.endswith('.h'), source_path) if openCL: ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends) else: ext = Extension(name, comp_path, depends=depends) # Compile... setup(name=name, version='1.0.0', ext_modules=[ext]) finally: # Cleanup the argv variable and the temporary directory... sys.argv = old_argv shutil.rmtree(temp_dir, True)
[ [ 1, 0, 0.2031, 0.0156, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2188, 0.0156, 0, 0.66, 0.125, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.2344, 0.0156, 0, 0.6...
[ "import sys", "import os.path", "import tempfile", "import shutil", "from distutils.core import setup, Extension", "import distutils.ccompiler", "import distutils.dep_util", "try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None", " __default_compiler...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pydoc import inspect class DocGen: """A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.""" def __init__(self, name, title = None, summary = None): """name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title.""" if title==None: title = name if summary==None: summary = title self.doc = pydoc.HTMLDoc() self.html = open('%s.html'%name,'w') self.html.write('<html>\n') self.html.write('<head>\n') self.html.write('<title>%s</title>\n'%title) self.html.write('</head>\n') self.html.write('<body>\n') self.html_variables = '' self.html_functions = '' self.html_classes = '' self.wiki = open('%s.wiki'%name,'w') self.wiki.write('#summary %s\n\n'%summary) self.wiki.write('= %s= \n\n'%title) self.wiki_variables = '' self.wiki_functions = '' self.wiki_classes = '' def __del__(self): if self.html_variables!='': self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables)) if self.html_functions!='': self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions)) if self.html_classes!='': self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes)) self.html.write('</body>\n') self.html.write('</html>\n') self.html.close() if self.wiki_variables!='': self.wiki.write('= Variables =\n\n') self.wiki.write(self.wiki_variables) self.wiki.write('\n') if self.wiki_functions!='': self.wiki.write('= Functions =\n\n') self.wiki.write(self.wiki_functions) self.wiki.write('\n') if self.wiki_classes!='': self.wiki.write('= Classes =\n\n') self.wiki.write(self.wiki_classes) self.wiki.write('\n') self.wiki.close() def addFile(self, fn, title, fls = True): """Given a filename and section title adds the contents of said file to the output. Various flags influence how this works.""" html = [] wiki = [] for i, line in enumerate(open(fn,'r').readlines()): hl = line.replace('\n', '') if i==0 and fls: hl = '<strong>' + hl + '</strong>' for ext in ['py','txt']: if '.%s - '%ext in hl: s = hl.split('.%s - '%ext, 1) hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1] html.append(hl) wl = line.strip() if i==0 and fls: wl = '*%s*'%wl for ext in ['py','txt']: if '.%s - '%ext in wl: s = wl.split('.%s - '%ext, 1) wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n' wiki.append(wl) self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html))) self.wiki.write('== %s ==\n'%title) self.wiki.write('\n'.join(wiki)) self.wiki.write('----\n\n') def addVariable(self, var, desc): """Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc..""" self.html_variables += '<strong>%s</strong><br/>'%var self.html_variables += '%s<br/><br/>\n'%desc self.wiki_variables += '*`%s`*\n'%var self.wiki_variables += ' %s\n\n'%desc def addFunction(self, func): """Adds a function to the documentation. You provide the actual function instance.""" self.html_functions += self.doc.docroutine(func).replace('&nbsp;',' ') self.html_functions += '\n' name = func.__name__ args, varargs, keywords, defaults = inspect.getargspec(func) doc = inspect.getdoc(func) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_functions += ' %s\n\n'%doc def addClass(self, cls): """Adds a class to the documentation. You provide the actual class object.""" self.html_classes += self.doc.docclass(cls).replace('&nbsp;',' ') self.html_classes += '\n' name = cls.__name__ parents = filter(lambda a: a!=cls, inspect.getmro(cls)) doc = inspect.getdoc(cls) par_str = '' if len(parents)!=0: par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents)) self.wiki_classes += '== %s(%s) ==\n'%(name, par_str) self.wiki_classes += ' %s\n\n'%doc methods = inspect.getmembers(cls, inspect.ismethod) def method_key(pair): if pair[0]=='__init__': return '___' else: return pair[0] methods.sort(key=method_key) for name, method in methods: if not name.startswith('_%s'%cls.__name__): args, varargs, keywords, defaults = inspect.getargspec(method) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords def fetch_doc(cls, name): try: method = getattr(cls, name) if method.__doc__!=None: return inspect.getdoc(method) except: pass for parent in filter(lambda a: a!=cls, inspect.getmro(cls)): ret = fetch_doc(parent, name) if ret!=None: return ret return None doc = fetch_doc(cls, name) self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_classes += ' %s\n\n'%doc variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float)) for name, var in variables: if not name.startswith('__'): self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
[ [ 1, 0, 0.0634, 0.0049, 0, 0.66, 0, 291, 0, 1, 0, 0, 291, 0, 0 ], [ 1, 0, 0.0683, 0.0049, 0, 0.66, 0.5, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 3, 0, 0.5439, 0.9171, 0, 0.6...
[ "import pydoc", "import inspect", "class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from ctypes import * def setProcName(name): """Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases.""" # Call the process control function... libc = cdll.LoadLibrary('libc.so.6') libc.prctl(15, c_char_p(name), 0, 0, 0) # Update argv... charPP = POINTER(POINTER(c_char)) argv = charPP.in_dll(libc,'_dl_argv') size = libc.strlen(argv[0]) libc.strncpy(argv[0],c_char_p(name),size) if __name__=='__main__': # Quick test that it works... import os ps1 = 'ps' ps2 = 'ps -f' os.system(ps1) os.system(ps2) setProcName('wibble_wobble') os.system(ps1) os.system(ps2)
[ [ 1, 0, 0.3636, 0.0227, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 2, 0, 0.5682, 0.25, 0, 0.66, 0.5, 903, 0, 1, 0, 0, 0, 0, 9 ], [ 8, 1, 0.4773, 0.0227, 1, 0.74, ...
[ "from ctypes import *", "def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import multiprocessing as mp import multiprocessing.synchronize # To make sure we have all the functionality. import types import marshal import unittest def repeat(x): """A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant.""" while True: yield x def run_code(code,args): """Internal use function that does the work in each process.""" code = marshal.loads(code) func = types.FunctionType(code, globals(), '_') return func(*args) def mp_map(func, *iters, **keywords): """A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity.""" if 'pool' in keywords: pool = keywords['pool'] else: pool = mp.Pool() code = marshal.dumps(func.func_code) jobs = [] for args in zip(*iters): jobs.append(pool.apply_async(run_code,(code,args))) for i in xrange(len(jobs)): jobs[i] = jobs[i].get() return jobs class TestMpMap(unittest.TestCase): def test_simple1(self): data = ['a','b','c','d'] def noop(data): return data data_noop = mp_map(noop, data) self.assertEqual(data, data_noop) def test_simple2(self): data = [x for x in xrange(1000)] data_double = mp_map(lambda a: a*2, data) self.assertEqual(map(lambda a: a*2,data), data_double) def test_gen(self): def gen(): for i in xrange(100): yield i data_double = mp_map(lambda a: a*2, gen()) self.assertEqual(map(lambda a: a*2,gen()), data_double) def test_repeat(self): def mult(a,b): return a*b data = [x for x in xrange(50,5000,5)] data_triple = mp_map(mult, data, repeat(3)) self.assertEqual(map(lambda a: a*3,data),data_triple) def test_none(self): data = [] data_sqr = mp_map(lambda x: x*x, data) self.assertEqual([],data_sqr) if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.1456, 0.0097, 0, 0.66, 0, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 1, 0, 0.1553, 0.0097, 0, 0.66, 0.1111, 99, 0, 1, 0, 0, 99, 0, 0 ], [ 1, 0, 0.1748, 0.0097, 0, 0....
[ "import multiprocessing as mp", "import multiprocessing.synchronize # To make sure we have all the functionality.", "import types", "import marshal", "import unittest", "def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Defines helper functions for accessing numpy arrays... numpy_util_code = start_cpp() + """ #ifndef NUMPY_UTIL_CODE #define NUMPY_UTIL_CODE float & Float1D(PyArrayObject * arr, int index = 0) { return *(float*)(arr->data + index*arr->strides[0]); } float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } unsigned char & Byte1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index*arr->strides[0]); } unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } int & Int1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index*arr->strides[0]); } int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } #endif """
[ [ 1, 0, 0.1923, 0.0128, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.6282, 0.7564, 0, 0.66, 1, 799, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}" ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import cvarray import mp_map import prog_bar import numpy_help_cpp import python_obj_cpp import matrix_cpp import gamma_cpp import setProcName import start_cpp import make import doc_gen # Setup... doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.') doc.addFile('readme.txt', 'Overview') # Variables... doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.') doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.') doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++') doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++') # Functions... doc.addFunction(make.make_mod) doc.addFunction(cvarray.cv2array) doc.addFunction(cvarray.array2cv) doc.addFunction(mp_map.repeat) doc.addFunction(mp_map.mp_map) doc.addFunction(setProcName.setProcName) doc.addFunction(start_cpp.start_cpp) doc.addFunction(make.make_mod) # Classes... doc.addClass(prog_bar.ProgBar) doc.addClass(doc_gen.DocGen)
[ [ 1, 0, 0.2857, 0.0179, 0, 0.66, 0, 192, 0, 1, 0, 0, 192, 0, 0 ], [ 1, 0, 0.3036, 0.0179, 0, 0.66, 0.0385, 905, 0, 1, 0, 0, 905, 0, 0 ], [ 1, 0, 0.3214, 0.0179, 0, ...
[ "import cvarray", "import mp_map", "import prog_bar", "import numpy_help_cpp", "import python_obj_cpp", "import matrix_cpp", "import gamma_cpp", "import setProcName", "import start_cpp", "import make", "import doc_gen", "doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc...
# Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest import random import math from scipy.special import gammaln, psi, polygamma from scipy import weave from utils.start_cpp import start_cpp # Provides various gamma-related functions... gamma_code = start_cpp() + """ #ifndef GAMMA_CODE #define GAMMA_CODE #include <cmath> // Returns the natural logarithm of the Gamma function... // (Uses Lanczos's approximation.) double lnGamma(double z) { static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7}; if (z<0.5) { // Use reflection formula, as approximation doesn't work down here... return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z); } else { double x = coeff[0]; for (int i=1;i<9;i++) x += coeff[i]/(z+i-1); double t = z + 6.5; return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x); } } // Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values... double digamma(double z) { static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point. double ret = 0.0; while (z<highVal) { ret -= 1.0/z; z += 1.0; } double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz4 = iz2*iz2; double iz6 = iz4*iz2; ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0; return ret; } // Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically... double trigamma(double z) { static const double highVal = 8.0; double ret = 0.0; while (z<highVal) { ret += 1.0/(z*z); z += 1.0; } z -= 1.0; double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz3 = iz1*iz2; double iz5 = iz3*iz2; double iz7 = iz5*iz2; double iz9 = iz7*iz2; ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0; return ret; } #endif """ def lnGamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function""" code = start_cpp(gamma_code) + """ return_val = lnGamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def digamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function""" code = start_cpp(gamma_code) + """ return_val = digamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def trigamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function""" code = start_cpp(gamma_code) + """ return_val = trigamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) class TestFuncs(unittest.TestCase): """Test code for the assorted gamma-related functions.""" def test_compile(self): code = start_cpp(gamma_code) + """ """ weave.inline(code, support_code=gamma_code) def test_error_lngamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = lnGamma(z) good = gammaln(z) assert(math.fabs(own-good)<1e-12) def test_error_digamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = digamma(z) good = psi(z) assert(math.fabs(own-good)<1e-9) def test_error_trigamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = trigamma(z) good = polygamma(1,z) assert(math.fabs(own-good)<1e-9) # If this file is run do the unit tests... if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.0818, 0.0063, 0, 0.66, 0, 88, 0, 1, 0, 0, 88, 0, 0 ], [ 1, 0, 0.0881, 0.0063, 0, 0.66, 0.0909, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0943, 0.0063, 0, 0....
[ "import unittest", "import random", "import math", "from scipy.special import gammaln, psi, polygamma", "from scipy import weave", "from utils.start_cpp import start_cpp", "gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import inspect import hashlib def start_cpp(hash_str = None): """This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>""" frame = inspect.currentframe().f_back info = inspect.getframeinfo(frame) if hash_str==None: return '#line %i "%s"\n'%(info[1],info[0]) else: h = hashlib.md5() h.update(hash_str) hash_val = h.hexdigest() return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
[ [ 1, 0, 0.5, 0.0333, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.5333, 0.0333, 0, 0.66, 0.5, 154, 0, 1, 0, 0, 154, 0, 0 ], [ 2, 0, 0.8333, 0.3667, 0, 0.66, ...
[ "import inspect", "import hashlib", "def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os.path import tempfile import shutil from distutils.core import setup, Extension import distutils.ccompiler import distutils.dep_util try: __default_compiler = distutils.ccompiler.new_compiler() except: __default_compiler = None def make_mod(name, base, source, openCL = False): """Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place.""" if __default_compiler==None: raise Exception('No compiler!') # Work out the various file names - check if we actually need to do anything... if not isinstance(source, list): source = [source] source_path = map(lambda s: os.path.join(base, s), source) library_path = os.path.join(base, __default_compiler.shared_object_filename(name)) if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)): try: print 'b' # Backup the argv variable and create a temporary directory to do all work in... old_argv = sys.argv[:] temp_dir = tempfile.mkdtemp() # Prepare the extension... sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir] comp_path = filter(lambda s: not s.endswith('.h'), source_path) depends = filter(lambda s: s.endswith('.h'), source_path) if openCL: ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends) else: ext = Extension(name, comp_path, depends=depends) # Compile... setup(name=name, version='1.0.0', ext_modules=[ext]) finally: # Cleanup the argv variable and the temporary directory... sys.argv = old_argv shutil.rmtree(temp_dir, True)
[ [ 1, 0, 0.2031, 0.0156, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2188, 0.0156, 0, 0.66, 0.125, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.2344, 0.0156, 0, 0.6...
[ "import sys", "import os.path", "import tempfile", "import shutil", "from distutils.core import setup, Extension", "import distutils.ccompiler", "import distutils.dep_util", "try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None", " __default_compiler...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pydoc import inspect class DocGen: """A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.""" def __init__(self, name, title = None, summary = None): """name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title.""" if title==None: title = name if summary==None: summary = title self.doc = pydoc.HTMLDoc() self.html = open('%s.html'%name,'w') self.html.write('<html>\n') self.html.write('<head>\n') self.html.write('<title>%s</title>\n'%title) self.html.write('</head>\n') self.html.write('<body>\n') self.html_variables = '' self.html_functions = '' self.html_classes = '' self.wiki = open('%s.wiki'%name,'w') self.wiki.write('#summary %s\n\n'%summary) self.wiki.write('= %s= \n\n'%title) self.wiki_variables = '' self.wiki_functions = '' self.wiki_classes = '' def __del__(self): if self.html_variables!='': self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables)) if self.html_functions!='': self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions)) if self.html_classes!='': self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes)) self.html.write('</body>\n') self.html.write('</html>\n') self.html.close() if self.wiki_variables!='': self.wiki.write('= Variables =\n\n') self.wiki.write(self.wiki_variables) self.wiki.write('\n') if self.wiki_functions!='': self.wiki.write('= Functions =\n\n') self.wiki.write(self.wiki_functions) self.wiki.write('\n') if self.wiki_classes!='': self.wiki.write('= Classes =\n\n') self.wiki.write(self.wiki_classes) self.wiki.write('\n') self.wiki.close() def addFile(self, fn, title, fls = True): """Given a filename and section title adds the contents of said file to the output. Various flags influence how this works.""" html = [] wiki = [] for i, line in enumerate(open(fn,'r').readlines()): hl = line.replace('\n', '') if i==0 and fls: hl = '<strong>' + hl + '</strong>' for ext in ['py','txt']: if '.%s - '%ext in hl: s = hl.split('.%s - '%ext, 1) hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1] html.append(hl) wl = line.strip() if i==0 and fls: wl = '*%s*'%wl for ext in ['py','txt']: if '.%s - '%ext in wl: s = wl.split('.%s - '%ext, 1) wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n' wiki.append(wl) self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html))) self.wiki.write('== %s ==\n'%title) self.wiki.write('\n'.join(wiki)) self.wiki.write('----\n\n') def addVariable(self, var, desc): """Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc..""" self.html_variables += '<strong>%s</strong><br/>'%var self.html_variables += '%s<br/><br/>\n'%desc self.wiki_variables += '*`%s`*\n'%var self.wiki_variables += ' %s\n\n'%desc def addFunction(self, func): """Adds a function to the documentation. You provide the actual function instance.""" self.html_functions += self.doc.docroutine(func).replace('&nbsp;',' ') self.html_functions += '\n' name = func.__name__ args, varargs, keywords, defaults = inspect.getargspec(func) doc = inspect.getdoc(func) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_functions += ' %s\n\n'%doc def addClass(self, cls): """Adds a class to the documentation. You provide the actual class object.""" self.html_classes += self.doc.docclass(cls).replace('&nbsp;',' ') self.html_classes += '\n' name = cls.__name__ parents = filter(lambda a: a!=cls, inspect.getmro(cls)) doc = inspect.getdoc(cls) par_str = '' if len(parents)!=0: par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents)) self.wiki_classes += '== %s(%s) ==\n'%(name, par_str) self.wiki_classes += ' %s\n\n'%doc methods = inspect.getmembers(cls, inspect.ismethod) def method_key(pair): if pair[0]=='__init__': return '___' else: return pair[0] methods.sort(key=method_key) for name, method in methods: if not name.startswith('_%s'%cls.__name__): args, varargs, keywords, defaults = inspect.getargspec(method) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords def fetch_doc(cls, name): try: method = getattr(cls, name) if method.__doc__!=None: return inspect.getdoc(method) except: pass for parent in filter(lambda a: a!=cls, inspect.getmro(cls)): ret = fetch_doc(parent, name) if ret!=None: return ret return None doc = fetch_doc(cls, name) self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_classes += ' %s\n\n'%doc variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float)) for name, var in variables: if not name.startswith('__'): self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
[ [ 1, 0, 0.0634, 0.0049, 0, 0.66, 0, 291, 0, 1, 0, 0, 291, 0, 0 ], [ 1, 0, 0.0683, 0.0049, 0, 0.66, 0.5, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 3, 0, 0.5439, 0.9171, 0, 0.6...
[ "import pydoc", "import inspect", "class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from ctypes import * def setProcName(name): """Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases.""" # Call the process control function... libc = cdll.LoadLibrary('libc.so.6') libc.prctl(15, c_char_p(name), 0, 0, 0) # Update argv... charPP = POINTER(POINTER(c_char)) argv = charPP.in_dll(libc,'_dl_argv') size = libc.strlen(argv[0]) libc.strncpy(argv[0],c_char_p(name),size) if __name__=='__main__': # Quick test that it works... import os ps1 = 'ps' ps2 = 'ps -f' os.system(ps1) os.system(ps2) setProcName('wibble_wobble') os.system(ps1) os.system(ps2)
[ [ 1, 0, 0.3636, 0.0227, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 2, 0, 0.5682, 0.25, 0, 0.66, 0.5, 903, 0, 1, 0, 0, 0, 0, 9 ], [ 8, 1, 0.4773, 0.0227, 1, 0.88, ...
[ "from ctypes import *", "def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import multiprocessing as mp import multiprocessing.synchronize # To make sure we have all the functionality. import types import marshal import unittest def repeat(x): """A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant.""" while True: yield x def run_code(code,args): """Internal use function that does the work in each process.""" code = marshal.loads(code) func = types.FunctionType(code, globals(), '_') return func(*args) def mp_map(func, *iters, **keywords): """A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity.""" if 'pool' in keywords: pool = keywords['pool'] else: pool = mp.Pool() code = marshal.dumps(func.func_code) jobs = [] for args in zip(*iters): jobs.append(pool.apply_async(run_code,(code,args))) for i in xrange(len(jobs)): jobs[i] = jobs[i].get() return jobs class TestMpMap(unittest.TestCase): def test_simple1(self): data = ['a','b','c','d'] def noop(data): return data data_noop = mp_map(noop, data) self.assertEqual(data, data_noop) def test_simple2(self): data = [x for x in xrange(1000)] data_double = mp_map(lambda a: a*2, data) self.assertEqual(map(lambda a: a*2,data), data_double) def test_gen(self): def gen(): for i in xrange(100): yield i data_double = mp_map(lambda a: a*2, gen()) self.assertEqual(map(lambda a: a*2,gen()), data_double) def test_repeat(self): def mult(a,b): return a*b data = [x for x in xrange(50,5000,5)] data_triple = mp_map(mult, data, repeat(3)) self.assertEqual(map(lambda a: a*3,data),data_triple) def test_none(self): data = [] data_sqr = mp_map(lambda x: x*x, data) self.assertEqual([],data_sqr) if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.1456, 0.0097, 0, 0.66, 0, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 1, 0, 0.1553, 0.0097, 0, 0.66, 0.1111, 99, 0, 1, 0, 0, 99, 0, 0 ], [ 1, 0, 0.1748, 0.0097, 0, 0....
[ "import multiprocessing as mp", "import multiprocessing.synchronize # To make sure we have all the functionality.", "import types", "import marshal", "import unittest", "def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Defines helper functions for accessing numpy arrays... numpy_util_code = start_cpp() + """ #ifndef NUMPY_UTIL_CODE #define NUMPY_UTIL_CODE float & Float1D(PyArrayObject * arr, int index = 0) { return *(float*)(arr->data + index*arr->strides[0]); } float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } unsigned char & Byte1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index*arr->strides[0]); } unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } int & Int1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index*arr->strides[0]); } int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } #endif """
[ [ 1, 0, 0.1923, 0.0128, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.6282, 0.7564, 0, 0.66, 1, 799, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}" ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import cvarray import mp_map import prog_bar import numpy_help_cpp import python_obj_cpp import matrix_cpp import gamma_cpp import setProcName import start_cpp import make import doc_gen # Setup... doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.') doc.addFile('readme.txt', 'Overview') # Variables... doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.') doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.') doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++') doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++') # Functions... doc.addFunction(make.make_mod) doc.addFunction(cvarray.cv2array) doc.addFunction(cvarray.array2cv) doc.addFunction(mp_map.repeat) doc.addFunction(mp_map.mp_map) doc.addFunction(setProcName.setProcName) doc.addFunction(start_cpp.start_cpp) doc.addFunction(make.make_mod) # Classes... doc.addClass(prog_bar.ProgBar) doc.addClass(doc_gen.DocGen)
[ [ 1, 0, 0.2857, 0.0179, 0, 0.66, 0, 192, 0, 1, 0, 0, 192, 0, 0 ], [ 1, 0, 0.3036, 0.0179, 0, 0.66, 0.0385, 905, 0, 1, 0, 0, 905, 0, 0 ], [ 1, 0, 0.3214, 0.0179, 0, ...
[ "import cvarray", "import mp_map", "import prog_bar", "import numpy_help_cpp", "import python_obj_cpp", "import matrix_cpp", "import gamma_cpp", "import setProcName", "import start_cpp", "import make", "import doc_gen", "doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc...
# Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest import random import math from scipy.special import gammaln, psi, polygamma from scipy import weave from utils.start_cpp import start_cpp # Provides various gamma-related functions... gamma_code = start_cpp() + """ #ifndef GAMMA_CODE #define GAMMA_CODE #include <cmath> // Returns the natural logarithm of the Gamma function... // (Uses Lanczos's approximation.) double lnGamma(double z) { static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7}; if (z<0.5) { // Use reflection formula, as approximation doesn't work down here... return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z); } else { double x = coeff[0]; for (int i=1;i<9;i++) x += coeff[i]/(z+i-1); double t = z + 6.5; return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x); } } // Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values... double digamma(double z) { static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point. double ret = 0.0; while (z<highVal) { ret -= 1.0/z; z += 1.0; } double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz4 = iz2*iz2; double iz6 = iz4*iz2; ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0; return ret; } // Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically... double trigamma(double z) { static const double highVal = 8.0; double ret = 0.0; while (z<highVal) { ret += 1.0/(z*z); z += 1.0; } z -= 1.0; double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz3 = iz1*iz2; double iz5 = iz3*iz2; double iz7 = iz5*iz2; double iz9 = iz7*iz2; ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0; return ret; } #endif """ def lnGamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function""" code = start_cpp(gamma_code) + """ return_val = lnGamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def digamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function""" code = start_cpp(gamma_code) + """ return_val = digamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def trigamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function""" code = start_cpp(gamma_code) + """ return_val = trigamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) class TestFuncs(unittest.TestCase): """Test code for the assorted gamma-related functions.""" def test_compile(self): code = start_cpp(gamma_code) + """ """ weave.inline(code, support_code=gamma_code) def test_error_lngamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = lnGamma(z) good = gammaln(z) assert(math.fabs(own-good)<1e-12) def test_error_digamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = digamma(z) good = psi(z) assert(math.fabs(own-good)<1e-9) def test_error_trigamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = trigamma(z) good = polygamma(1,z) assert(math.fabs(own-good)<1e-9) # If this file is run do the unit tests... if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.0818, 0.0063, 0, 0.66, 0, 88, 0, 1, 0, 0, 88, 0, 0 ], [ 1, 0, 0.0881, 0.0063, 0, 0.66, 0.0909, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0943, 0.0063, 0, 0....
[ "import unittest", "import random", "import math", "from scipy.special import gammaln, psi, polygamma", "from scipy import weave", "from utils.start_cpp import start_cpp", "gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import inspect import hashlib def start_cpp(hash_str = None): """This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>""" frame = inspect.currentframe().f_back info = inspect.getframeinfo(frame) if hash_str==None: return '#line %i "%s"\n'%(info[1],info[0]) else: h = hashlib.md5() h.update(hash_str) hash_val = h.hexdigest() return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
[ [ 1, 0, 0.5, 0.0333, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.5333, 0.0333, 0, 0.66, 0.5, 154, 0, 1, 0, 0, 154, 0, 0 ], [ 2, 0, 0.8333, 0.3667, 0, 0.66, ...
[ "import inspect", "import hashlib", "def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os.path import tempfile import shutil from distutils.core import setup, Extension import distutils.ccompiler import distutils.dep_util try: __default_compiler = distutils.ccompiler.new_compiler() except: __default_compiler = None def make_mod(name, base, source, openCL = False): """Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place.""" if __default_compiler==None: raise Exception('No compiler!') # Work out the various file names - check if we actually need to do anything... if not isinstance(source, list): source = [source] source_path = map(lambda s: os.path.join(base, s), source) library_path = os.path.join(base, __default_compiler.shared_object_filename(name)) if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)): try: print 'b' # Backup the argv variable and create a temporary directory to do all work in... old_argv = sys.argv[:] temp_dir = tempfile.mkdtemp() # Prepare the extension... sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir] comp_path = filter(lambda s: not s.endswith('.h'), source_path) depends = filter(lambda s: s.endswith('.h'), source_path) if openCL: ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends) else: ext = Extension(name, comp_path, depends=depends) # Compile... setup(name=name, version='1.0.0', ext_modules=[ext]) finally: # Cleanup the argv variable and the temporary directory... sys.argv = old_argv shutil.rmtree(temp_dir, True)
[ [ 1, 0, 0.2031, 0.0156, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2188, 0.0156, 0, 0.66, 0.125, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.2344, 0.0156, 0, 0.6...
[ "import sys", "import os.path", "import tempfile", "import shutil", "from distutils.core import setup, Extension", "import distutils.ccompiler", "import distutils.dep_util", "try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None", " __default_compiler...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pydoc import inspect class DocGen: """A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.""" def __init__(self, name, title = None, summary = None): """name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title.""" if title==None: title = name if summary==None: summary = title self.doc = pydoc.HTMLDoc() self.html = open('%s.html'%name,'w') self.html.write('<html>\n') self.html.write('<head>\n') self.html.write('<title>%s</title>\n'%title) self.html.write('</head>\n') self.html.write('<body>\n') self.html_variables = '' self.html_functions = '' self.html_classes = '' self.wiki = open('%s.wiki'%name,'w') self.wiki.write('#summary %s\n\n'%summary) self.wiki.write('= %s= \n\n'%title) self.wiki_variables = '' self.wiki_functions = '' self.wiki_classes = '' def __del__(self): if self.html_variables!='': self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables)) if self.html_functions!='': self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions)) if self.html_classes!='': self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes)) self.html.write('</body>\n') self.html.write('</html>\n') self.html.close() if self.wiki_variables!='': self.wiki.write('= Variables =\n\n') self.wiki.write(self.wiki_variables) self.wiki.write('\n') if self.wiki_functions!='': self.wiki.write('= Functions =\n\n') self.wiki.write(self.wiki_functions) self.wiki.write('\n') if self.wiki_classes!='': self.wiki.write('= Classes =\n\n') self.wiki.write(self.wiki_classes) self.wiki.write('\n') self.wiki.close() def addFile(self, fn, title, fls = True): """Given a filename and section title adds the contents of said file to the output. Various flags influence how this works.""" html = [] wiki = [] for i, line in enumerate(open(fn,'r').readlines()): hl = line.replace('\n', '') if i==0 and fls: hl = '<strong>' + hl + '</strong>' for ext in ['py','txt']: if '.%s - '%ext in hl: s = hl.split('.%s - '%ext, 1) hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1] html.append(hl) wl = line.strip() if i==0 and fls: wl = '*%s*'%wl for ext in ['py','txt']: if '.%s - '%ext in wl: s = wl.split('.%s - '%ext, 1) wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n' wiki.append(wl) self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html))) self.wiki.write('== %s ==\n'%title) self.wiki.write('\n'.join(wiki)) self.wiki.write('----\n\n') def addVariable(self, var, desc): """Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc..""" self.html_variables += '<strong>%s</strong><br/>'%var self.html_variables += '%s<br/><br/>\n'%desc self.wiki_variables += '*`%s`*\n'%var self.wiki_variables += ' %s\n\n'%desc def addFunction(self, func): """Adds a function to the documentation. You provide the actual function instance.""" self.html_functions += self.doc.docroutine(func).replace('&nbsp;',' ') self.html_functions += '\n' name = func.__name__ args, varargs, keywords, defaults = inspect.getargspec(func) doc = inspect.getdoc(func) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_functions += ' %s\n\n'%doc def addClass(self, cls): """Adds a class to the documentation. You provide the actual class object.""" self.html_classes += self.doc.docclass(cls).replace('&nbsp;',' ') self.html_classes += '\n' name = cls.__name__ parents = filter(lambda a: a!=cls, inspect.getmro(cls)) doc = inspect.getdoc(cls) par_str = '' if len(parents)!=0: par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents)) self.wiki_classes += '== %s(%s) ==\n'%(name, par_str) self.wiki_classes += ' %s\n\n'%doc methods = inspect.getmembers(cls, inspect.ismethod) def method_key(pair): if pair[0]=='__init__': return '___' else: return pair[0] methods.sort(key=method_key) for name, method in methods: if not name.startswith('_%s'%cls.__name__): args, varargs, keywords, defaults = inspect.getargspec(method) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords def fetch_doc(cls, name): try: method = getattr(cls, name) if method.__doc__!=None: return inspect.getdoc(method) except: pass for parent in filter(lambda a: a!=cls, inspect.getmro(cls)): ret = fetch_doc(parent, name) if ret!=None: return ret return None doc = fetch_doc(cls, name) self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_classes += ' %s\n\n'%doc variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float)) for name, var in variables: if not name.startswith('__'): self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
[ [ 1, 0, 0.0634, 0.0049, 0, 0.66, 0, 291, 0, 1, 0, 0, 291, 0, 0 ], [ 1, 0, 0.0683, 0.0049, 0, 0.66, 0.5, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 3, 0, 0.5439, 0.9171, 0, 0.6...
[ "import pydoc", "import inspect", "class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from ctypes import * def setProcName(name): """Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases.""" # Call the process control function... libc = cdll.LoadLibrary('libc.so.6') libc.prctl(15, c_char_p(name), 0, 0, 0) # Update argv... charPP = POINTER(POINTER(c_char)) argv = charPP.in_dll(libc,'_dl_argv') size = libc.strlen(argv[0]) libc.strncpy(argv[0],c_char_p(name),size) if __name__=='__main__': # Quick test that it works... import os ps1 = 'ps' ps2 = 'ps -f' os.system(ps1) os.system(ps2) setProcName('wibble_wobble') os.system(ps1) os.system(ps2)
[ [ 1, 0, 0.3636, 0.0227, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 2, 0, 0.5682, 0.25, 0, 0.66, 0.5, 903, 0, 1, 0, 0, 0, 0, 9 ], [ 8, 1, 0.4773, 0.0227, 1, 0.82, ...
[ "from ctypes import *", "def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import multiprocessing as mp import multiprocessing.synchronize # To make sure we have all the functionality. import types import marshal import unittest def repeat(x): """A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant.""" while True: yield x def run_code(code,args): """Internal use function that does the work in each process.""" code = marshal.loads(code) func = types.FunctionType(code, globals(), '_') return func(*args) def mp_map(func, *iters, **keywords): """A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity.""" if 'pool' in keywords: pool = keywords['pool'] else: pool = mp.Pool() code = marshal.dumps(func.func_code) jobs = [] for args in zip(*iters): jobs.append(pool.apply_async(run_code,(code,args))) for i in xrange(len(jobs)): jobs[i] = jobs[i].get() return jobs class TestMpMap(unittest.TestCase): def test_simple1(self): data = ['a','b','c','d'] def noop(data): return data data_noop = mp_map(noop, data) self.assertEqual(data, data_noop) def test_simple2(self): data = [x for x in xrange(1000)] data_double = mp_map(lambda a: a*2, data) self.assertEqual(map(lambda a: a*2,data), data_double) def test_gen(self): def gen(): for i in xrange(100): yield i data_double = mp_map(lambda a: a*2, gen()) self.assertEqual(map(lambda a: a*2,gen()), data_double) def test_repeat(self): def mult(a,b): return a*b data = [x for x in xrange(50,5000,5)] data_triple = mp_map(mult, data, repeat(3)) self.assertEqual(map(lambda a: a*3,data),data_triple) def test_none(self): data = [] data_sqr = mp_map(lambda x: x*x, data) self.assertEqual([],data_sqr) if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.1456, 0.0097, 0, 0.66, 0, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 1, 0, 0.1553, 0.0097, 0, 0.66, 0.1111, 99, 0, 1, 0, 0, 99, 0, 0 ], [ 1, 0, 0.1748, 0.0097, 0, 0....
[ "import multiprocessing as mp", "import multiprocessing.synchronize # To make sure we have all the functionality.", "import types", "import marshal", "import unittest", "def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Defines helper functions for accessing numpy arrays... numpy_util_code = start_cpp() + """ #ifndef NUMPY_UTIL_CODE #define NUMPY_UTIL_CODE float & Float1D(PyArrayObject * arr, int index = 0) { return *(float*)(arr->data + index*arr->strides[0]); } float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } unsigned char & Byte1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index*arr->strides[0]); } unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } int & Int1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index*arr->strides[0]); } int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } #endif """
[ [ 1, 0, 0.1923, 0.0128, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.6282, 0.7564, 0, 0.66, 1, 799, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}" ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import cvarray import mp_map import prog_bar import numpy_help_cpp import python_obj_cpp import matrix_cpp import gamma_cpp import setProcName import start_cpp import make import doc_gen # Setup... doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.') doc.addFile('readme.txt', 'Overview') # Variables... doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.') doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.') doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++') doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++') # Functions... doc.addFunction(make.make_mod) doc.addFunction(cvarray.cv2array) doc.addFunction(cvarray.array2cv) doc.addFunction(mp_map.repeat) doc.addFunction(mp_map.mp_map) doc.addFunction(setProcName.setProcName) doc.addFunction(start_cpp.start_cpp) doc.addFunction(make.make_mod) # Classes... doc.addClass(prog_bar.ProgBar) doc.addClass(doc_gen.DocGen)
[ [ 1, 0, 0.2857, 0.0179, 0, 0.66, 0, 192, 0, 1, 0, 0, 192, 0, 0 ], [ 1, 0, 0.3036, 0.0179, 0, 0.66, 0.0385, 905, 0, 1, 0, 0, 905, 0, 0 ], [ 1, 0, 0.3214, 0.0179, 0, ...
[ "import cvarray", "import mp_map", "import prog_bar", "import numpy_help_cpp", "import python_obj_cpp", "import matrix_cpp", "import gamma_cpp", "import setProcName", "import start_cpp", "import make", "import doc_gen", "doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc...
# Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest import random import math from scipy.special import gammaln, psi, polygamma from scipy import weave from utils.start_cpp import start_cpp # Provides various gamma-related functions... gamma_code = start_cpp() + """ #ifndef GAMMA_CODE #define GAMMA_CODE #include <cmath> // Returns the natural logarithm of the Gamma function... // (Uses Lanczos's approximation.) double lnGamma(double z) { static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7}; if (z<0.5) { // Use reflection formula, as approximation doesn't work down here... return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z); } else { double x = coeff[0]; for (int i=1;i<9;i++) x += coeff[i]/(z+i-1); double t = z + 6.5; return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x); } } // Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values... double digamma(double z) { static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point. double ret = 0.0; while (z<highVal) { ret -= 1.0/z; z += 1.0; } double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz4 = iz2*iz2; double iz6 = iz4*iz2; ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0; return ret; } // Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically... double trigamma(double z) { static const double highVal = 8.0; double ret = 0.0; while (z<highVal) { ret += 1.0/(z*z); z += 1.0; } z -= 1.0; double iz1 = 1.0/z; double iz2 = iz1*iz1; double iz3 = iz1*iz2; double iz5 = iz3*iz2; double iz7 = iz5*iz2; double iz9 = iz7*iz2; ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0; return ret; } #endif """ def lnGamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function""" code = start_cpp(gamma_code) + """ return_val = lnGamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def digamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function""" code = start_cpp(gamma_code) + """ return_val = digamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) def trigamma(z): """Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function""" code = start_cpp(gamma_code) + """ return_val = trigamma(z); """ return weave.inline(code, ['z'], support_code=gamma_code) class TestFuncs(unittest.TestCase): """Test code for the assorted gamma-related functions.""" def test_compile(self): code = start_cpp(gamma_code) + """ """ weave.inline(code, support_code=gamma_code) def test_error_lngamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = lnGamma(z) good = gammaln(z) assert(math.fabs(own-good)<1e-12) def test_error_digamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = digamma(z) good = psi(z) assert(math.fabs(own-good)<1e-9) def test_error_trigamma(self): for _ in xrange(1000): z = random.uniform(0.01, 100.0) own = trigamma(z) good = polygamma(1,z) assert(math.fabs(own-good)<1e-9) # If this file is run do the unit tests... if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.0818, 0.0063, 0, 0.66, 0, 88, 0, 1, 0, 0, 88, 0, 0 ], [ 1, 0, 0.0881, 0.0063, 0, 0.66, 0.0909, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0943, 0.0063, 0, 0....
[ "import unittest", "import random", "import math", "from scipy.special import gammaln, psi, polygamma", "from scipy import weave", "from utils.start_cpp import start_cpp", "gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import inspect import hashlib def start_cpp(hash_str = None): """This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>""" frame = inspect.currentframe().f_back info = inspect.getframeinfo(frame) if hash_str==None: return '#line %i "%s"\n'%(info[1],info[0]) else: h = hashlib.md5() h.update(hash_str) hash_val = h.hexdigest() return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
[ [ 1, 0, 0.5, 0.0333, 0, 0.66, 0, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 1, 0, 0.5333, 0.0333, 0, 0.66, 0.5, 154, 0, 1, 0, 0, 154, 0, 0 ], [ 2, 0, 0.8333, 0.3667, 0, 0.66, ...
[ "import inspect", "import hashlib", "def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import os.path import tempfile import shutil from distutils.core import setup, Extension import distutils.ccompiler import distutils.dep_util try: __default_compiler = distutils.ccompiler.new_compiler() except: __default_compiler = None def make_mod(name, base, source, openCL = False): """Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place.""" if __default_compiler==None: raise Exception('No compiler!') # Work out the various file names - check if we actually need to do anything... if not isinstance(source, list): source = [source] source_path = map(lambda s: os.path.join(base, s), source) library_path = os.path.join(base, __default_compiler.shared_object_filename(name)) if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)): try: print 'b' # Backup the argv variable and create a temporary directory to do all work in... old_argv = sys.argv[:] temp_dir = tempfile.mkdtemp() # Prepare the extension... sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir] comp_path = filter(lambda s: not s.endswith('.h'), source_path) depends = filter(lambda s: s.endswith('.h'), source_path) if openCL: ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends) else: ext = Extension(name, comp_path, depends=depends) # Compile... setup(name=name, version='1.0.0', ext_modules=[ext]) finally: # Cleanup the argv variable and the temporary directory... sys.argv = old_argv shutil.rmtree(temp_dir, True)
[ [ 1, 0, 0.2031, 0.0156, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2188, 0.0156, 0, 0.66, 0.125, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.2344, 0.0156, 0, 0.6...
[ "import sys", "import os.path", "import tempfile", "import shutil", "from distutils.core import setup, Extension", "import distutils.ccompiler", "import distutils.dep_util", "try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None", " __default_compiler...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import pydoc import inspect class DocGen: """A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.""" def __init__(self, name, title = None, summary = None): """name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title.""" if title==None: title = name if summary==None: summary = title self.doc = pydoc.HTMLDoc() self.html = open('%s.html'%name,'w') self.html.write('<html>\n') self.html.write('<head>\n') self.html.write('<title>%s</title>\n'%title) self.html.write('</head>\n') self.html.write('<body>\n') self.html_variables = '' self.html_functions = '' self.html_classes = '' self.wiki = open('%s.wiki'%name,'w') self.wiki.write('#summary %s\n\n'%summary) self.wiki.write('= %s= \n\n'%title) self.wiki_variables = '' self.wiki_functions = '' self.wiki_classes = '' def __del__(self): if self.html_variables!='': self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables)) if self.html_functions!='': self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions)) if self.html_classes!='': self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes)) self.html.write('</body>\n') self.html.write('</html>\n') self.html.close() if self.wiki_variables!='': self.wiki.write('= Variables =\n\n') self.wiki.write(self.wiki_variables) self.wiki.write('\n') if self.wiki_functions!='': self.wiki.write('= Functions =\n\n') self.wiki.write(self.wiki_functions) self.wiki.write('\n') if self.wiki_classes!='': self.wiki.write('= Classes =\n\n') self.wiki.write(self.wiki_classes) self.wiki.write('\n') self.wiki.close() def addFile(self, fn, title, fls = True): """Given a filename and section title adds the contents of said file to the output. Various flags influence how this works.""" html = [] wiki = [] for i, line in enumerate(open(fn,'r').readlines()): hl = line.replace('\n', '') if i==0 and fls: hl = '<strong>' + hl + '</strong>' for ext in ['py','txt']: if '.%s - '%ext in hl: s = hl.split('.%s - '%ext, 1) hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1] html.append(hl) wl = line.strip() if i==0 and fls: wl = '*%s*'%wl for ext in ['py','txt']: if '.%s - '%ext in wl: s = wl.split('.%s - '%ext, 1) wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n' wiki.append(wl) self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html))) self.wiki.write('== %s ==\n'%title) self.wiki.write('\n'.join(wiki)) self.wiki.write('----\n\n') def addVariable(self, var, desc): """Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc..""" self.html_variables += '<strong>%s</strong><br/>'%var self.html_variables += '%s<br/><br/>\n'%desc self.wiki_variables += '*`%s`*\n'%var self.wiki_variables += ' %s\n\n'%desc def addFunction(self, func): """Adds a function to the documentation. You provide the actual function instance.""" self.html_functions += self.doc.docroutine(func).replace('&nbsp;',' ') self.html_functions += '\n' name = func.__name__ args, varargs, keywords, defaults = inspect.getargspec(func) doc = inspect.getdoc(func) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_functions += ' %s\n\n'%doc def addClass(self, cls): """Adds a class to the documentation. You provide the actual class object.""" self.html_classes += self.doc.docclass(cls).replace('&nbsp;',' ') self.html_classes += '\n' name = cls.__name__ parents = filter(lambda a: a!=cls, inspect.getmro(cls)) doc = inspect.getdoc(cls) par_str = '' if len(parents)!=0: par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents)) self.wiki_classes += '== %s(%s) ==\n'%(name, par_str) self.wiki_classes += ' %s\n\n'%doc methods = inspect.getmembers(cls, inspect.ismethod) def method_key(pair): if pair[0]=='__init__': return '___' else: return pair[0] methods.sort(key=method_key) for name, method in methods: if not name.startswith('_%s'%cls.__name__): args, varargs, keywords, defaults = inspect.getargspec(method) if defaults==None: defaults = list() defaults = (len(args)-len(defaults)) * [None] + list(defaults) arg_str = '' if len(args)!=0: arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults)) if varargs!=None: arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs if keywords!=None: arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords def fetch_doc(cls, name): try: method = getattr(cls, name) if method.__doc__!=None: return inspect.getdoc(method) except: pass for parent in filter(lambda a: a!=cls, inspect.getmro(cls)): ret = fetch_doc(parent, name) if ret!=None: return ret return None doc = fetch_doc(cls, name) self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str) self.wiki_classes += ' %s\n\n'%doc variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float)) for name, var in variables: if not name.startswith('__'): self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
[ [ 1, 0, 0.0634, 0.0049, 0, 0.66, 0, 291, 0, 1, 0, 0, 291, 0, 0 ], [ 1, 0, 0.0683, 0.0049, 0, 0.66, 0.5, 878, 0, 1, 0, 0, 878, 0, 0 ], [ 3, 0, 0.5439, 0.9171, 0, 0.6...
[ "import pydoc", "import inspect", "class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from ctypes import * def setProcName(name): """Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases.""" # Call the process control function... libc = cdll.LoadLibrary('libc.so.6') libc.prctl(15, c_char_p(name), 0, 0, 0) # Update argv... charPP = POINTER(POINTER(c_char)) argv = charPP.in_dll(libc,'_dl_argv') size = libc.strlen(argv[0]) libc.strncpy(argv[0],c_char_p(name),size) if __name__=='__main__': # Quick test that it works... import os ps1 = 'ps' ps2 = 'ps -f' os.system(ps1) os.system(ps2) setProcName('wibble_wobble') os.system(ps1) os.system(ps2)
[ [ 1, 0, 0.3636, 0.0227, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 2, 0, 0.5682, 0.25, 0, 0.66, 0.5, 903, 0, 1, 0, 0, 0, 0, 9 ], [ 8, 1, 0.4773, 0.0227, 1, 0.22, ...
[ "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 # 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 df from utils import doc_gen # Setup... doc = doc_gen.DocGen('df', 'Decision Forests', 'Extensive random forests implimentation') doc.addFile('readme.txt', 'Overview') # Classes... doc.addClass(df.DF) doc.addClass(df.ExemplarSet) doc.addClass(df.MatrixES) doc.addClass(df.MatrixGrow) doc.addClass(df.Goal) doc.addClass(df.Classification) doc.addClass(df.DensityGaussian) doc.addClass(df.Pruner) doc.addClass(df.PruneCap) doc.addClass(df.Test) doc.addClass(df.AxisSplit) doc.addClass(df.LinearSplit) doc.addClass(df.DiscreteBucket) doc.addClass(df.Generator) doc.addClass(df.MergeGen) doc.addClass(df.RandomGen) doc.addClass(df.AxisMedianGen) doc.addClass(df.LinearMedianGen) doc.addClass(df.AxisRandomGen) doc.addClass(df.LinearRandomGen) doc.addClass(df.DiscreteRandomGen) doc.addClass(df.AxisClassifyGen) doc.addClass(df.LinearClassifyGen) doc.addClass(df.DiscreteClassifyGen) doc.addClass(df.SVMClassifyGen) doc.addClass(df.Node)
[ [ 1, 0, 0.26, 0.02, 0, 0.66, 0, 411, 0, 1, 0, 0, 411, 0, 0 ], [ 1, 0, 0.3, 0.02, 0, 0.66, 0.0345, 970, 0, 1, 0, 0, 970, 0, 0 ], [ 14, 0, 0.4, 0.02, 0, 0.66, 0.0...
[ "import df", "from utils import doc_gen", "doc = doc_gen.DocGen('df', 'Decision Forests', 'Extensive random forests implimentation')", "doc.addFile('readme.txt', 'Overview')", "doc.addClass(df.DF)", "doc.addClass(df.ExemplarSet)", "doc.addClass(df.MatrixES)", "doc.addClass(df.MatrixGrow)", "doc.addC...
# 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. class Pruner: """This abstracts the decision of when to stop growing a tree. It takes various statistics and stops growing when some condition is met.""" def clone(self): """Returns a copy of this object.""" raise NotImplementedError def keep(self, depth, trueCount, falseCount, infoGain, node): """Each time a node is split this method is called to decide if the split should be kept or not - it returns True to keep (And hence the children will be recursivly split, and have keep called on them, etc..) and False to discard the nodes children and stop. depth is how deep the node in question is, where the root node is 0, its children 1, and do on. trueCount and falseCount indicate how many data points in the training set go each way, whilst infoGain is the information gained by the split. Finally, node is the actual node incase some more complicated analysis is desired - at the time of passing in its test and stats will exist, but everything else will not.""" raise NotImplementedError class PruneCap(Pruner): """A simple but effective Pruner implimentation - simply provides a set of thresholds on depth, number of training samples required to split and information gained - when any one of the thresholds is tripped it stops further branching.""" def __init__(self, maxDepth = 8, minTrain = 8, minGain = 1e-3, minDepth = 2): """maxDepth is the maximum depth of a node in the tree, after which it stops - remember that the maximum node count based on this threshold increases dramatically as this number goes up, so don't go too crazy. minTrain is the smallest size node it will consider for further splitting. minGain is a lower limit on how much information gain a split must provide to be accepted. minDepth overrides the minimum node size - as long as the node count does not reach zero in either branch it will always split to the given depth - used to force it to at least learn something.""" self.maxDepth = maxDepth self.minDepth = minDepth self.minTrain = minTrain self.minGain = minGain def clone(self): return PruneCap(self.maxDepth, self.minTrain, self.minGain) def keep(self, depth, trueCount, falseCount, infoGain, node): if depth>=self.maxDepth: return False if depth>=self.minDepth and (trueCount+falseCount)<self.minTrain: return False if infoGain<self.minGain: return False return True def setMinDepth(self, minDepth): """Sets the minimum tree growing depth - trees will be grown at least this deep, baring insurmountable issues.""" self.minDepth = minDepth def setMaxDepth(self, maxDepth): """Sets the depth cap on the trees.""" self.maxDepth = maxDepth def setMinTrain(self, minTrain): """Sets the minimum number of nodes allowed to be split.""" self.minTrain = minTrain def setMinGain(self, mingain): """Sets the minimum gain that is allowed for a split to be accepted.""" self.minGain = mingain
[ [ 3, 0, 0.2719, 0.1754, 0, 0.66, 0, 843, 0, 2, 0, 0, 0, 0, 0 ], [ 8, 1, 0.2105, 0.0175, 1, 0.43, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 2, 1, 0.2632, 0.0526, 1, 0.43, 0...
[ "class Pruner:\n \"\"\"This abstracts the decision of when to stop growing a tree. It takes various statistics and stops growing when some condition is met.\"\"\"\n \n def clone(self):\n \"\"\"Returns a copy of this object.\"\"\"\n raise NotImplementedError\n \n def keep(self, depth, trueCount, falseCo...
# Copyright 2012 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import numpy import numpy.random from generators import Generator from tests import * from utils.start_cpp import start_cpp class AxisRandomGen(Generator, AxisSplit): """Provides a generator for axis-aligned split planes that split the data set at random - uses a normal distribution constructed from the data. Has random selection of the dimension to split the axis on.""" def __init__(self, channel, dimCount, splitCount, ignoreWeights=False): """channel is which channel to select the values from; dimCount is how many dimensions to try splits on; splitCount how many random split points to try for each selected dimension. Setting ignore weights to True means it will not consider the weights when calculating the normal distribution to draw random split points from.""" AxisSplit.__init__(self, channel) self.dimCount = dimCount self.splitCount = splitCount self.ignoreWeights = ignoreWeights def clone(self): return AxisRandomGen(self.channel, self.dimCount, self.splitCount, self.ignoreWeights) def itertests(self, es, index, weights = None): for _ in xrange(self.dimCount): ind = numpy.random.randint(es.features(self.channel)) values = es[self.channel, index, ind] if weights==None or self.ignoreWeights: mean = numpy.mean(values) std = max(numpy.std(values), 1e-6) else: w = weights[index] mean = numpy.average(values, weights=w) std = max(numpy.average(numpy.fabs(values-mean), weights=w), 1e-6) for _ in xrange(self.splitCount): split = numpy.random.normal(mean, std) yield numpy.asarray([ind], dtype=numpy.int32).tostring() + numpy.asarray([split], dtype=numpy.float32).tostring() def genCodeC(self, name, exemplar_list): code = start_cpp() + """ struct State%(name)s { void * test; // Will be the length of a 32 bit int followed by a float. size_t length; int dimRemain; int splitRemain; int feat; float mean; float sd; }; void %(name)s_init(State%(name)s & state, PyObject * data, Exemplar * test_set) { assert(sizeof(int)==4); state.length = sizeof(int) + sizeof(float); state.test = malloc(state.length); state.dimRemain = %(dimCount)i; state.splitRemain = 0; } bool %(name)s_next(State%(name)s & state, PyObject * data, Exemplar * test_set) { // If we have used up all splits for this feature select a new one... if (state.splitRemain==0) { // If we have run out of features to select we are done - return as such... if (state.dimRemain==0) { free(state.test); return false; } state.dimRemain--; // Get the relevent channels object... %(channelType)s cd = (%(channelType)s)PyTuple_GetItem(data, %(channel)i); // Select a new feature... state.feat = lrand48() %% %(channelName)s_features(cd); // Calculate the mean and standard deviation of the data set, for the selected feature... float sum = 0.0; float mean = 0.0; float mean2 = 0.0; while (test_set) { float x = %(channelName)s_get(cd, test_set->index, state.feat); if (%(ignoreWeights)s) { sum += 1.0; float delta = x - mean; mean += delta/sum; mean2 += delta * (x - mean); } else { float newSum = sum + test_set->weight; float delta = x - mean; float mean_delta = delta * test_set->weight / newSum; mean += mean_delta; mean2 += sum * delta * mean_delta; sum = newSum; } test_set = test_set->next; } state.mean = mean; state.sd = sqrt(mean2/sum); if (state.sd<1e-6) state.sd = 1e-6; state.splitRemain = %(splitCount)i; } // Output a split point drawn from the Gaussian... state.splitRemain--; double u = 1.0-drand48(); double v = 1.0-drand48(); float bg = sqrt(-2.0*log(u)) * cos(2.0*M_PI*v); float split = state.mean + state.sd * bg; ((int*)state.test)[0] = state.feat; ((float*)state.test)[1] = split; return true; } """%{'name':name, 'channel':self.channel, 'channelName':exemplar_list[self.channel]['name'], 'channelType':exemplar_list[self.channel]['itype'], 'dimCount':self.dimCount, 'splitCount':self.splitCount, 'ignoreWeights':('true' if self.ignoreWeights else 'false')} return (code, 'State'+name) class LinearRandomGen(Generator, LinearSplit): """Provides a generator for split planes that it is entirly random. Randomly selects which dimensions to work with, the orientation of the split plane and then where to put the split plane, with this last bit done with a normal distribution.""" def __init__(self, channel, dims, dimCount, dirCount, splitCount, ignoreWeights = False): """channel is which channel to select for and dims how many features (dimensions) to test on for any given test. dimCount is how many sets of dimensions to randomly select to generate tests from, whilst dirCount is how many random dimensions (From a uniform distribution over a hyper-sphere.) to use for selection. It actually generates the two independantly and trys every combination, as generating uniform random directions is somewhat expensive. For each of these splitCount split points are then tried, as drawn from a normal distribution. Setting ignore weights to True means it will not consider the weights when calculating the normal distribution to draw random split points from.""" LinearSplit.__init__(self, channel, dims) self.dimCount = dimCount self.dirCount = dirCount self.splitCount = splitCount self.ignoreWeights = ignoreWeights def clone(self): return LinearRandomGen(self.channel, self.dims, self.dimCount, self.dirCount, self.splitCount, self.ignoreWeights) def itertests(self, es, index, weights = None): # Generate random points on the hyper-sphere... dirs = numpy.random.normal(size=(self.dirCount, self.dims)) dirs /= numpy.sqrt(numpy.square(dirs).sum(axis=1)).reshape((-1,1)) # Iterate and select a set of dimensions before trying each direction on them... for _ in xrange(self.dimCount): #dims = numpy.random.choice(es.features(self.channel), size=self.dims, replace=False) For when numpy 1.7.0 is common dims = numpy.zeros(self.dims, dtype=numpy.int32) feats = es.features(self.channel) for i in xrange(self.dims): # This loop is not quite right - could result in the same feature twice. Odds are low enough that its not really worth caring about however. dims[i] = numpy.random.randint(feats-i) dims[i] += (dims[:i]<=dims[i]).sum() for di in dirs: dists = (es[self.channel, index, dims] * di.reshape((1,-1))).sum(axis=1) if weights==None or self.ignoreWeights: mean = numpy.mean(dists) std = max(numpy.std(dists), 1e-6) else: w = weights[index] mean = numpy.average(dists, weights=w) std = max(numpy.average(numpy.fabs(dists-mean), weights=w), 1e-6) for _ in xrange(self.splitCount): split = numpy.random.normal(mean, std) yield numpy.asarray(dims, dtype=numpy.int32).tostring() + numpy.asarray(di, dtype=numpy.float32).tostring() + numpy.asarray([split], dtype=numpy.float32).tostring() def genCodeC(self, name, exemplar_list): code = start_cpp() + """ struct State%(name)s { void * test; size_t length; float * dirs; // Vectors giving points uniformly distributed on the hyper-sphere. int * feat; // The features to index at this moment. float mean; float sd; // Control counters - all count down... int featRemain; int dirRemain; int splitRemain; }; void %(name)s_init(State%(name)s & state, PyObject * data, Exemplar * test_set) { assert(sizeof(int)==4); // Output state... state.length = sizeof(int) * %(dims)i + sizeof(float) * (%(dims)i+1); state.test = malloc(state.length); // Generate a bunch of random directions... state.dirs = (float*)malloc(sizeof(float)*%(dims)i*%(dirCount)i); for (int d=0;d<%(dirCount)i;d++) { float length = 0.0; int base = %(dims)i * d; for (int f=0; f<%(dims)i; f++) { double u = 1.0-drand48(); double v = 1.0-drand48(); float bg = sqrt(-2.0*log(u)) * cos(2.0*M_PI*v); length += bg*bg; state.dirs[base+f] = bg; } length = sqrt(length); for (int f=0; f<%(dims)i; f++) { state.dirs[base+f] /= length; } } // Which features are currently being used... state.feat = (int*)malloc(sizeof(int)*%(dims)i); // Setup the counters so we do the required work when next is called... state.featRemain = %(dimCount)i; state.dirRemain = 0; state.splitRemain = 0; // Safety... %(channelType)s cd = (%(channelType)s)PyTuple_GetItem(data, %(channel)i); int featCount = %(channelName)s_features(cd); if (%(dims)i>featCount) { state.featRemain = 0; // Effectivly cancels work. } } bool %(name)s_next(State%(name)s & state, PyObject * data, Exemplar * test_set) { if (state.splitRemain==0) { %(channelType)s cd = (%(channelType)s)PyTuple_GetItem(data, %(channel)i); if (state.dirRemain==0) { if (state.featRemain==0) { free(state.feat); free(state.dirs); free(state.test); return false; } state.featRemain--; // Select a new set of features... int featCount = %(channelName)s_features(cd); for (int f=0; f<%(dims)i; f++) { state.feat[f] = lrand48() %% (featCount-f); for (int j=0; j<f; j++) { if (state.feat[j]<=state.feat[f]) state.feat[f]++; } } // Reset the counter... state.dirRemain = %(dirCount)i; } state.dirRemain--; // For the new direction calculate the mean and standard deviation with the current features... float sum = 0.0; float mean = 0.0; float mean2 = 0.0; while (test_set) { float x = 0.0; int base = %(dims)i * state.dirRemain; for (int f=0; f<%(dims)i; f++) { x += state.dirs[base+f] * %(channelName)s_get(cd, test_set->index, state.feat[f]); } if (%(ignoreWeights)s) { sum += 1.0; float delta = x - mean; mean += delta/sum; mean2 += delta * (x - mean); } else { float newSum = sum + test_set->weight; float delta = x - mean; float mean_delta = delta * test_set->weight / newSum; mean += mean_delta; mean2 += sum * delta * mean_delta; sum = newSum; } test_set = test_set->next; } state.mean = mean; state.sd = sqrt(mean2/sum); if (state.sd<1e-6) state.sd = 1e-6; // Reset the counter... state.splitRemain = %(splitCount)i; } state.splitRemain--; // Use the mean and standard deviation to select a split point... double u = 1.0-drand48(); double v = 1.0-drand48(); float bg = sqrt(-2.0*log(u)) * cos(2.0*M_PI*v); float split = state.mean + state.sd * bg; // Store it all in the output... for (int i=0; i<%(dims)i;i++) { ((int*)state.test)[i] = state.feat[i]; } int base = %(dims)i * state.dirRemain; for (int i=0; i<%(dims)i;i++) { ((float*)state.test)[%(dims)i+i] = state.dirs[base+i]; } ((float*)state.test)[2*%(dims)i] = split; return true; } """%{'name':name, 'channel':self.channel, 'channelName':exemplar_list[self.channel]['name'], 'channelType':exemplar_list[self.channel]['itype'], 'dims':self.dims, 'dimCount':self.dimCount, 'dirCount':self.dirCount, 'splitCount':self.splitCount, 'ignoreWeights':('true' if self.ignoreWeights else 'false')} return (code, 'State'+name) class DiscreteRandomGen(Generator, DiscreteBucket): """Defines a generator for discrete data. It basically takes a single discrete feature and randomly assigns just one value to pass and all others to fail the test. The selection is from the values provided by the data passed in, weighted by how many of them there are.""" def __init__(self, channel, featCount, valueCount): """channel is the channel to build discrete tests for. featCount is how many different features to select to generate tests for whilst valueCount is how many values to draw and offer as tests for each feature selected.""" DiscreteBucket.__init__(self, channel) self.featCount = featCount self.valueCount = valueCount def clone(self): return DiscreteRandomGen(self.channel, self.featCount, self.valueCount) def itertests(self, es, index, weights = None): # Iterate and yield the right number of tests... for _ in xrange(self.featCount): # Randomly select a feature... feat = numpy.random.randint(es.features(self.channel)) values = es[self.channel, index, feat] histo = numpy.bincount(values, weights=weights[index] if weights!=None else None) histo /= histo.sum() # Draw and iterate the values - do a fun trick to avoid duplicate yields,,, values = numpy.random.multinomial(self.valueCount, histo) for value in numpy.where(values!=0): # Yield a discrete decision object... yield numpy.asarray(feat, dtype=numpy.int32).tostring() + numpy.asarray(value, dtype=numpy.int32).tostring() def genCodeC(self, name, exemplar_list): code = start_cpp() + """ struct State%(name)s { void * test; // Will be the length of two 32 bit ints. size_t length; int feat; // Current feature. int featRemain; // How many more times we need to select a feature to play with. int * value; // List of values drawn from the feature - we return each in turn. int valueLength; // Reduced as each feature is drawn. float * weight; // Aligns with value; temporary used for the sampling. }; int %(name)s_int_comp(const void * lhs, const void * rhs) { return (*(int*)lhs) - (*(int*)rhs); } void %(name)s_init(State%(name)s & state, PyObject * data, Exemplar * test_set) { assert(sizeof(int)==4); state.test = malloc(2*sizeof(int)); state.length = 2*sizeof(int); state.feat = -1; state.featRemain = %(featCount)i; state.value = (int*)malloc(%(valueCount)i*sizeof(int)); state.valueLength = 0; state.weight = (float*)malloc(%(valueCount)i*sizeof(float)); } bool %(name)s_next(State%(name)s & state, PyObject * data, Exemplar * test_set) { // Check if we need to create a new set of values... if (state.valueLength==0) { // Check if we are done - if so clean up and return... if (state.featRemain==0) { free(state.weight); free(state.value); free(state.test); return false; } state.featRemain--; // Get the relevent channels object... %(channelType)s cd = (%(channelType)s)PyTuple_GetItem(data, %(channel)i); // Select a new feature... state.feat = lrand48() %% %(channelName)s_features(cd); // Generate a set of values - use a method based on a single pass through the linked list... float minWeight = 1.0; while (test_set) { if (test_set->weight>1e-6) { float w = pow(drand48(), 1.0/test_set->weight); if (state.valueLength<%(valueCount)i) { state.value[state.valueLength] = test_set->index; state.weight[state.valueLength] = w; if (minWeight>w) minWeight = w; state.valueLength++; } else { if (w>minWeight) // Below is not very efficient, but don't really care - valueCount tends to be low enough that optimisation is not worthwhile.. { int lowest = 0; for (int i=1; i<%(valueCount)i; i++) { if (state.weight[lowest]>state.weight[i]) lowest = i; } state.value[lowest] = test_set->index; state.weight[lowest] = w; minWeight = 1.0; for (int i=0; i<%(valueCount)i; i++) { if (minWeight>state.weight[i]) minWeight = state.weight[i]; } } } } test_set = test_set->next; } // Convert exemplar numbers to actual values... for (int i=0; i<state.valueLength; i++) { state.value[i] = %(channelName)s_get(cd, state.value[i], state.feat); } // Remove duplicates... qsort(state.value, state.valueLength, sizeof(int), %(name)s_int_comp); int out = 1; for (int i=1; i<state.valueLength; i++) { if (state.value[i]!=state.value[i-1]) { state.value[out] = state.value[i]; out++; } } state.valueLength = out; } // Get and arrange as the output the next value... state.valueLength -= 1; ((int*)state.test)[0] = state.feat; ((int*)state.test)[1] = state.value[state.valueLength]; return true; } """%{'name':name, 'channel':self.channel, 'channelName':exemplar_list[self.channel]['name'], 'channelType':exemplar_list[self.channel]['itype'], 'featCount':self.featCount, 'valueCount':self.valueCount} return (code, 'State'+name)
[ [ 1, 0, 0.0214, 0.0019, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0234, 0.0019, 0, 0.66, 0.1429, 181, 0, 1, 0, 0, 181, 0, 0 ], [ 1, 0, 0.0273, 0.0019, 0, ...
[ "import numpy", "import numpy.random", "from generators import Generator", "from tests import *", "from utils.start_cpp import start_cpp", "class AxisRandomGen(Generator, AxisSplit):\n \"\"\"Provides a generator for axis-aligned split planes that split the data set at random - uses a normal distribution ...
# -*- 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 numpy import operator class Dataset: """Contains a dataset - lots of pairs of feature vectors and labels. For conveniance labels can be arbitrary python objects, or at least python objects that work for indexing a dictionary.""" def __init__(self): # labels are internally stored as consecutive integers - this does the conversion... self.labelToNum = dict() self.numToLabel = [] # Store of data blocks - each block is a data matrix and label list pair (A lot of blocks could be of length one of course.)... self.blocks = [] def add(self, featVect, label): """Adds a single feature vector and label.""" if label in self.labelToNum: l = self.labelToNum[label] else: l = len(self.numToLabel) self.numToLabel.append(label) self.labelToNum[label] = l self.blocks.append((featVect.reshape((1,featVect.shape[0])).astype(numpy.double),[l])) def addMatrix(self, dataMatrix, labels): """This adds a data matrix alongside a list of labels for it. The number of rows in the matrix should match the number of labels in the list.""" assert(dataMatrix.shape[0]==len(labels)) # Add any labels not yet seen... for l in labels: if l not in self.labelToNum.keys(): num = len(self.numToLabel) self.numToLabel.append(l) self.labelToNum[l] = num # Convert the given labels list to a list of numerical labels... ls = map(lambda l:self.labelToNum[l],labels) # Store... self.blocks.append((dataMatrix.astype(numpy.double),ls)) def getLabels(self): """Returns a list of all the labels in the data set.""" return self.numToLabel def getCounts(self): """Returns a how many features with each label have been seen - as a list which aligns with the output of getLabels.""" ret = [0]*len(self.numToLabel) for block in self.blocks: for label in block[1]: ret[label] += 1 return ret def subsampleData(self, count): """Returns a new dataset object which contains count instances of the data, sampled from the data contained within without repetition. Returned Dataset could miss some of the classes.""" size = 0 for block in self.blocks: size += len(block[1]) subset = numpy.random.permutation(size)[:count] subset.sort() pos = 0 index = 0 ret = Dataset() for block in self.blocks: while subset[index]<(pos+len(block[1])): loc = subset[index] - pos ret.add(block[0][loc,:], block[1][loc]) index += 1 if index==subset.shape[0]: return ret pos += len(block[1]) return ret def getTrainData(self, lNeg, lPos): """Given two labels this returns a pair of a data matrix and a y vector, where lPos features have +1 and lNeg features have -1. Features that do not have one of these two labels will not be included.""" # Convert the given labels to label numbers... if lNeg in self.labelToNum: ln = self.labelToNum[lNeg] else: ln = -1 if lPos in self.labelToNum: lp = self.labelToNum[lPos] else: lp = -1 # Go through the blocks and extract the relevant info... dataList = [] yList = [] for dataMatrix, labels in self.blocks: y = filter(lambda l:l==lp or l==ln,labels) if len(y)!=0: def signRes(l): if l==lp: return 1.0 else: return -1.0 y = numpy.array(map(signRes,y), dtype=numpy.float_) inds = map(operator.itemgetter(0), filter(lambda l:l[1]==lp or l[1]==ln, enumerate(labels))) data = dataMatrix[numpy.array(inds),:] dataList.append(data) yList.append(y) # Glue it all together into big blocks, and return 'em... return (numpy.vstack(dataList),numpy.concatenate(yList))
[ [ 1, 0, 0.1074, 0.0083, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.1157, 0.0083, 0, 0.66, 0.5, 616, 0, 1, 0, 0, 616, 0, 0 ], [ 3, 0, 0.5744, 0.8595, 0, 0.6...
[ "import numpy", "import operator", "class Dataset:\n \"\"\"Contains a dataset - lots of pairs of feature vectors and labels. For conveniance labels can be arbitrary python objects, or at least python objects that work for indexing a dictionary.\"\"\"\n def __init__(self):\n # labels are internally stored a...
# -*- 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 Params from smo import SMO from loo import looPair, looPairRange, looPairBrute import math import time import multiprocessing as mp import numpy def mpLooPairRange(params, data, lNeg, lPos, looDist): """multiprocess wrapper around looPair needed for multiprocessing support.""" model = looPairRange(params, data, looDist) return (lNeg,lPos,model[0],model[1]) class MultiModel: """This represents a model with multiple labels - uses one against one voting. Even if you only have two labels you are best off using this interface, as it makes everything neat. Supports model selection as well.""" def __init__(self, params, dataset, weightSVM = True, callback = None, pool = None, looDist = 1.1): """Trains the model given the dataset and either a params object or a iterator of params objects. If a list it trys all entrys of the list for each pairing, and selects the one that gives the best loo, i.e. does model selection. If weightSVM is True (The default) then it makes use of the leave one out scores calculated during model selection to weight the classification boundaries - this can result in slightly better behavour at the meeting points of multiple classes in feature space. The pool parameter can be passed in a Pool() object from the multiprocessing python module, or set to True to have it create an instance itself. This enables multiprocessor mode for doing each loo calculation required - good if you have lots of models to test and/or lots of labels.""" self.weightSVM = weightSVM # Get a list of labels, create all the relevant pairings. A mapping from labels to numbers is used... self.labels = dataset.getLabels() self.labelToNum = dict() for i,label in enumerate(self.labels): self.labelToNum[label] = i self.models = dict() for lNeg in xrange(len(self.labels)): for lPos in xrange(lNeg+1,len(self.labels)): #print self.labels[lNeg], self.labels[lPos] self.models[(lNeg,lPos)] = None # Generate the list of models that need solving... solveList = [] for lNeg,lPos in self.models.keys(): if isinstance(params,Params): solveList.append((lNeg,lPos,params)) else: for p in params: solveList.append((lNeg,lPos,p)) # Loop through all models and solve them, reporting progress if required... if pool==None: # Single process implimentation... for i,data in enumerate(solveList): lNeg,lPos,params = data if callback: callback(i,len(solveList)) model = looPairRange(params, dataset.getTrainData(self.labels[lNeg], self.labels[lPos]), looDist) #print model[0], looPair(params, dataset.getTrainData(self.labels[lNeg], self.labels[lPos]))[0], looPairBrute(params, dataset.getTrainData(self.labels[lNeg], self.labels[lPos]))[0] if self.models[lNeg,lPos]==None or model[0]>self.models[lNeg,lPos][0]: self.models[lNeg,lPos] = model else: # Multiprocess implimentation... # Create a pool if it hasn't been provided... if type(pool)==type(True): pool = mp.Pool() # Callback for when each job completes... self.numComplete = 0 if callback: callback(self.numComplete,len(solveList)) def taskComplete(ret): self.numComplete += 1 if callback: callback(self.numComplete,len(solveList)) lNeg = ret[0] lPos = ret[1] model = (ret[2],ret[3]) if self.models[lNeg,lPos]==None or model[0]>self.models[lNeg,lPos][0]: self.models[lNeg,lPos] = model try: # Create all the jobs, set them running... jobs = [] for lNeg,lPos,params in solveList: jobs.append(pool.apply_async(mpLooPairRange,(params,dataset.getTrainData(self.labels[lNeg], self.labels[lPos]), lNeg, lPos, looDist), callback = taskComplete)) finally: # Wait for them all to complete... while len(jobs)!=0: if jobs[0].ready(): del jobs[0] continue time.sleep(0.1) def getLabels(self): """Returns a list of the labels supported.""" return self.labels def getModel(self,labA,labB): """Returns a tuple of (model,neg label,pos label, loo) where model is the model between the pair and the two labels indicate which label is associated with the negative result and which with the positive result. loo is the leave one out score of this particular boundary.""" la = self.labelToNum[labA] lb = self.labelToNum[labB] if la<lb: return (self.models[(la,lb)][1],labA,labB,self.models[(la,lb)][0]) else: return (self.models[(lb,la)][1],labB,labA,self.models[(lb,la)][0]) def paramsList(self): """Returns a list of parameters objects used by the model - good for curiosity.""" return map(lambda x: x[1].getParams(),self.models.values()) def classify(self,feature): """Classifies a single feature vector - returns the most likelly label.""" if self.weightSVM: cost = numpy.zeros(len(self.labels),dtype=numpy.float_) for lNeg,lPos in self.models.keys(): m = self.models[lNeg,lPos] cg = -math.log(max((m[0],1e-3))) cb = -math.log(max((1.0-m[0],1e-3))) # max required incase its perfect. val = m[1].classify(feature) if val<0: cost[lNeg] += cg cost[lPos] += cb else: cost[lNeg] += cb cost[lPos] += cg return self.labels[cost.argmin()] else: score = numpy.zeros(len(self.labels),dtype=numpy.int_) for lNeg,lPos in self.models.keys(): val = self.models[lNeg,lPos][1].classify(feature) if val<0: score[lNeg] += 1 else: score[lPos] += 1 return self.labels[score.argmax()] def multiClassify(self,features): """Given a matrix where every row is a feature - returns a list of labels for the rows.""" if self.weightSVM: cost = numpy.zeros((features.shape[0], len(self.labels)), dtype=numpy.float_) for lNeg,lPos in self.models.keys(): m = self.models[lNeg,lPos] cg = -math.log(m[0]) cb = -math.log(max((1.0-m[0],1e-3))) # max required incase its perfect. vals = m[1].multiClassify(features) cost[numpy.nonzero(vals<0)[0],lNeg] += cg cost[numpy.nonzero(vals>0)[0],lNeg] += cb cost[numpy.nonzero(vals>0)[0],lPos] += cg cost[numpy.nonzero(vals<0)[0],lPos] += cb ret = [] for i in xrange(features.shape[0]): ret.append(self.labels[cost[i,:].argmin()]) return ret else: score = numpy.zeros((features.shape[0], len(self.labels)), dtype=numpy.int_) for lNeg,lPos in self.models.keys(): vals = self.models[lNeg,lPos][1].multiClassify(features) score[numpy.nonzero(vals<0)[0],lNeg] += 1 score[numpy.nonzero(vals>0)[0],lPos] += 1 ret = [] for i in xrange(features.shape[0]): ret.append(self.labels[score[i,:].argmax()]) return ret
[ [ 1, 0, 0.0707, 0.0054, 0, 0.66, 0, 206, 0, 1, 0, 0, 206, 0, 0 ], [ 1, 0, 0.0761, 0.0054, 0, 0.66, 0.125, 105, 0, 1, 0, 0, 105, 0, 0 ], [ 1, 0, 0.0815, 0.0054, 0, 0...
[ "from params import Params", "from smo import SMO", "from loo import looPair, looPairRange, looPairBrute", "import math", "import time", "import multiprocessing as mp", "import numpy", "def mpLooPairRange(params, data, lNeg, lPos, looDist):\n \"\"\"multiprocess wrapper around looPair needed for multi...
# -*- 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 numpy from params import * from scipy.weave import inline class Model: """Defines a model - this will consist of a parameters object to define the kernel (C is ignored, but will be the same as the trainning parameter if needed for reference.), a list of support vectors in a dataMatrix and then a vector of weights, plus the b parameter. The weights are the multiple of the y value and alpha value. Uses weave to make evaluation of new features fast.""" def __init__(self, params, supportVectors, supportWeights, b): """Sets up a model given the parameters. Note that if given a linear kernel and multiple support vectors it does the obvious optimisation.""" self.params = params self.supportVectors = supportVectors self.supportWeights = supportWeights self.b = b # Get the kernel code ready for the weave call... self.kernel = self.params.getCode() self.kernelKey = self.params.kernelKey() # Optimise the linear kernel if needed... if self.params.getKernel()==Kernel.linear and len(self.supportWeights)>1: self.supportVectors = (self.supportVectors.T * self.supportWeights).sum(axis=1) self.supportVectors = self.supportVectors.reshape((1, self.supportVectors.shape[0])) self.supportWeights = numpy.array((1.0,), dtype=numpy.double) def getParams(self): """Returns the parameters the svm was trainned with.""" return self.params def getSupportVectors(self): """Returns a 2D array where each row is a support vector.""" return self.supportVectors def getSupportWeights(self): """Returns the vector of weights matching the support vectors.""" return self.supportWeights def getB(self): """Returns the addative offset of the function defined by the support vectors to locate the decision boundary at 0.""" return self.b def decision(self,feature): """Given a feature vector this returns its decision boundary evaluation, specifically the weighted sum of each of the kernel evaluations for the support vectors against the given feature vector, plus b.""" code = '// Kernel = '+self.kernelKey+'\n' + """ double ret = b; for (int v=0;v<Nsw[0];v++) { ret += SW1(v) * kernel(Nsv[1],feature,&SV2(v,0)); } return_val = ret; """ sv = self.supportVectors sw = self.supportWeights b = self.b return inline(code,['feature','sv','sw','b'], support_code=self.kernel) def classify(self,feature): """Classifies a single feature vector - returns -1 or +1 depending on its class. Just the sign of the decision method.""" if self.decision(feature)<0.0: return -1 else: return 1 def multiDecision(self,features): """Given a matrix where every row is a feature returns the decision boundary evaluation for each feature as an array of values.""" code = '// Kernel = '+self.kernelKey+'\n' + """ for (int f=0;f<Nfeatures[0];f++) { RET1(f) = b; for (int v=0;v<Nsw[0];v++) { RET1(f) += SW1(v) * kernel(Nsv[1],&FEATURES2(f,0),&SV2(v,0)); } } """ sv = self.supportVectors sw = self.supportWeights b = self.b ret = numpy.empty(features.shape[0], dtype=numpy.float_) inline(code, ['features','sv','sw','b','ret'], support_code=self.kernel) return ret def multiClassify(self,features): """Given a matrix where every row is a feature returns - returns -1 or +1 depending on the class of each vector, as an array. Just the sign of the multiDecision method. Be warned the classification vector is returned with a type of int8.""" dec = self.multiDecision(features) ret = numpy.zeros(features.shape[0],dtype=numpy.int8) code = """ for (int i=0;i<Ndec[0];i++) { if (dec[i]<0.0) ret[i] = -1; else ret[i] = 1; } """ inline(code,['dec','ret']) return ret
[ [ 1, 0, 0.113, 0.0087, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.1304, 0.0087, 0, 0.66, 0.3333, 206, 0, 1, 0, 0, 206, 0, 0 ], [ 1, 0, 0.1391, 0.0087, 0, 0...
[ "import numpy", "from params import *", "from scipy.weave import inline", "class Model:\n \"\"\"Defines a model - this will consist of a parameters object to define the kernel (C is ignored, but will be the same as the trainning parameter if needed for reference.), a list of support vectors in a dataMatrix a...