code
stringlengths
1
1.49M
vector
listlengths
0
7.38k
snippet
listlengths
0
7.38k
# 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.43, ...
[ "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.47, ...
[ "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.63, ...
[ "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.94, ...
[ "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.27, ...
[ "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 # -*- 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.3, ...
[ "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.02, ...
[ "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.04, ...
[ "from ctypes import *", "def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import multiprocessing as mp import multiprocessing.synchronize # To make sure we have all the functionality. import types import marshal import unittest def repeat(x): """A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant.""" while True: yield x def run_code(code,args): """Internal use function that does the work in each process.""" code = marshal.loads(code) func = types.FunctionType(code, globals(), '_') return func(*args) def mp_map(func, *iters, **keywords): """A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity.""" if 'pool' in keywords: pool = keywords['pool'] else: pool = mp.Pool() code = marshal.dumps(func.func_code) jobs = [] for args in zip(*iters): jobs.append(pool.apply_async(run_code,(code,args))) for i in xrange(len(jobs)): jobs[i] = jobs[i].get() return jobs class TestMpMap(unittest.TestCase): def test_simple1(self): data = ['a','b','c','d'] def noop(data): return data data_noop = mp_map(noop, data) self.assertEqual(data, data_noop) def test_simple2(self): data = [x for x in xrange(1000)] data_double = mp_map(lambda a: a*2, data) self.assertEqual(map(lambda a: a*2,data), data_double) def test_gen(self): def gen(): for i in xrange(100): yield i data_double = mp_map(lambda a: a*2, gen()) self.assertEqual(map(lambda a: a*2,gen()), data_double) def test_repeat(self): def mult(a,b): return a*b data = [x for x in xrange(50,5000,5)] data_triple = mp_map(mult, data, repeat(3)) self.assertEqual(map(lambda a: a*3,data),data_triple) def test_none(self): data = [] data_sqr = mp_map(lambda x: x*x, data) self.assertEqual([],data_sqr) if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.1456, 0.0097, 0, 0.66, 0, 901, 0, 1, 0, 0, 901, 0, 0 ], [ 1, 0, 0.1553, 0.0097, 0, 0.66, 0.1111, 99, 0, 1, 0, 0, 99, 0, 0 ], [ 1, 0, 0.1748, 0.0097, 0, 0....
[ "import multiprocessing as mp", "import multiprocessing.synchronize # To make sure we have all the functionality.", "import types", "import marshal", "import unittest", "def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Defines helper functions for accessing numpy arrays... numpy_util_code = start_cpp() + """ #ifndef NUMPY_UTIL_CODE #define NUMPY_UTIL_CODE float & Float1D(PyArrayObject * arr, int index = 0) { return *(float*)(arr->data + index*arr->strides[0]); } float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } unsigned char & Byte1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index*arr->strides[0]); } unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(unsigned char)); return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } int & Int1D(PyArrayObject * arr, int index = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index*arr->strides[0]); } int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]); } int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0) { //assert(arr->strides[0]==sizeof(int)); return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]); } #endif """
[ [ 1, 0, 0.1923, 0.0128, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.6282, 0.7564, 0, 0.66, 1, 799, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}" ]
# -*- coding: utf-8 -*- # Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import math import random import numpy import scipy.weave as weave from kmeans1 import KMeans1 from kmeans2 import KMeans2 class KMeans3(KMeans2): """Takes the initialisation improvememnts of KMeans2 and additionally makes improvements to the kmeans implimentation. Specifically it presumes that distance computations are expensive and avoids doing them where possible, by additionally storing how far each cluster centre moved since the last step. This allows a lot of such computations to be pruned, especially later on when cluster centres are not moving. It does not work if distance computations are cheap however, so only worth it for long feature vectors.""" def __kmeans(self, centres, data, minSize = 3, maxIters = 1024, assignOut = None): """Internal method - does k-means on the data set as it is treated internally. Given the initial set of centres and a data matrix - the centres matrix is then updated to the new positions.""" assignment = numpy.empty(data.shape[0], dtype=numpy.int_) assignmentDist = numpy.empty(data.shape[0], dtype=numpy.float_) # Distance squared assignment[:] = -1 assignmentDist[:] = 0.0 assignmentCount = numpy.empty(centres.shape[0], dtype=numpy.int_) motion = numpy.empty(centres.shape[0], dtype=numpy.float_) # This is distance, rather than distance squared, unlike for assignments. motion[:] = 1e100 tempCentres = numpy.empty(centres.shape, dtype=numpy.float_) code = """ for (int i=0;i<maxIters;i++) { // Reassign features to clusters... bool change = false; for (int f=0;f<Ndata[0];f++) { // Initialise the best to the previous best... int best = ASSIGNMENT1(f); float bestDist; // Squared distance. if (best==-1) bestDist = 1e100; else { if (MOTION1(best)<1e-6) bestDist = ASSIGNMENTDIST1(f); else { bestDist = 0.0; for (int e=0;e<Ndata[1];e++) { float d = DATA2(f,e) - CENTRES2(best,e); bestDist += d*d; } } } // Check all the centres to see if they are better than the current best... float rad = sqrt(ASSIGNMENTDIST1(f)); // Distance to closest center from *previous* iteration - all other centers must of been further away in this iteration. for (int c=0;c<Ncentres[0];c++) { if (c==ASSIGNMENT1(f)) continue; // Only do the distance calculation if the node could actually suceded.. float optDist = rad - MOTION1(c); optDist *= optDist; // Distance -> distance squared. if (optDist<bestDist) { // Node stands a chance - do the full calculation... float dist = 0.0; for (int e=0;e<Ndata[1];e++) { float d = DATA2(f,e) - CENTRES2(c,e); dist += d*d; } if (dist<bestDist) { best = c; bestDist = dist; } } } change |= (best!=ASSIGNMENT1(f)); ASSIGNMENT1(f) = best; ASSIGNMENTDIST1(f) = bestDist; } // If no reassignments happen break out early... if (change==false) break; // Recalculate cluster centres with an incrimental mean... for (int c=0;c<Ncentres[0];c++) { for (int e=0;e<Ndata[1];e++) {TEMPCENTRES2(c,e) = 0.0;} ASSIGNMENTCOUNT1(c) = 0; } for (int f=0;f<Ndata[0];f++) { int c = ASSIGNMENT1(f); ASSIGNMENTCOUNT1(c) += 1; float div = ASSIGNMENTCOUNT1(c); for (int e=0;e<Ndata[1];e++) { TEMPCENTRES2(c,e) += (DATA2(f,e) - TEMPCENTRES2(c,e)) / div; } } // Transfer over, storing the motion vectors... for (int c=0;c<Ncentres[0];c++) { MOTION1(c) = 0.0; for (int e=0;e<Ndata[1];e++) { float delta = TEMPCENTRES2(c,e) - CENTRES2(c,e); MOTION1(c) += delta*delta; CENTRES2(c,e) = TEMPCENTRES2(c,e); } MOTION1(c) = sqrt(MOTION1(c)); } // Reassign puny clusters... for (int c=0;c<Ncentres[0];c++) { if (ASSIGNMENTCOUNT1(c)<minSize) { int rf = rand() % Ndata[0]; for (int e=0;e<Ndata[1];e++) { CENTRES2(c,e) = DATA2(rf,e); } MOTION1(c) = 1e100; } } } """ weave.inline(code,['centres', 'assignment', 'assignmentDist', 'assignmentCount', 'motion', 'data', 'tempCentres', 'maxIters', 'minSize']) if assignOut!=None: assignOut[:] = assignment
[ [ 1, 0, 0.0872, 0.0067, 0, 0.66, 0, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 1, 0, 0.094, 0.0067, 0, 0.66, 0.1667, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.1074, 0.0067, 0, 0...
[ "import math", "import random", "import numpy", "import scipy.weave as weave", "from kmeans1 import KMeans1", "from kmeans2 import KMeans2", "class KMeans3(KMeans2):\n \"\"\"Takes the initialisation improvememnts of KMeans2 and additionally makes improvements to the kmeans implimentation. Specifically ...
# -*- coding: utf-8 -*- # Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import math import random import numpy import scipy.cluster.vq from kmeans_shared import KMeansShared class KMeans0(KMeansShared): """Wraps the kmeans implimentation provided by scipy with the same interface as provided by the other kmeans implimentations in the system. My experiance shows that this is insanely slow - not sure why, but even my brute force C implimentation is faster (Best guess is its coded in python, and not optimised in any way.).""" def doTrain(self, feats, clusters, maxIters = 512, restarts = 8, assignOut = None): """Given a large number of features as a data matrix this finds a good set of cluster centres. clusters is the number of clusters to create, maxIters is the maximum number of iterations for convergance of a cluster and restarts how many times to run - the most probable result is used. minSize is the smallest cluster size - if a cluster is smaller than this it is reinitialised.""" self.means = numpy.empty((clusters, feats.shape[1]), dtype=numpy.float_) self.means[:,:] = scipy.cluster.vq.kmeans(feats, clusters, restarts)[0] if assignOut!=None: assignOut[:], _ = scipy.cluster.vq.vq(feats, centres)
[ [ 1, 0, 0.3939, 0.0303, 0, 0.66, 0, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 1, 0, 0.4242, 0.0303, 0, 0.66, 0.2, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.4848, 0.0303, 0, 0.6...
[ "import math", "import random", "import numpy", "import scipy.cluster.vq", "from kmeans_shared import KMeansShared", "class KMeans0(KMeansShared):\n \"\"\"Wraps the kmeans implimentation provided by scipy with the same interface as provided by the other kmeans implimentations in the system. My experiance...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import gmm from utils import doc_gen # Setup... doc = doc_gen.DocGen('gmm', 'Gaussian Mixture Model (plus K-means)', 'Gaussian mixture model, with EM, plus assorted k-means implimentations') doc.addFile('readme.txt', 'Overview') # Function that removes the methods that start with 'do' from a class - to hide them in the documentation... def pruneClassOfDo(cls): methods = dir(cls) for method in methods: if method[:2]=='do': delattr(cls, method) pruneClassOfDo(gmm.KMeansShared) pruneClassOfDo(gmm.KMeans0) pruneClassOfDo(gmm.KMeans1) pruneClassOfDo(gmm.KMeans2) pruneClassOfDo(gmm.KMeans3) pruneClassOfDo(gmm.Mixture) pruneClassOfDo(gmm.IsotropicGMM) # Variables... doc.addVariable('KMeans', 'The prefered k-means implimentation can be referenced as KMeans') doc.addVariable('KMeansShort', 'The prefered k-means implimentation is choosen on the assumption of long feature vectors - if the feature vectors are in fact short then this is a synonym of a more appropriate fitter. (By short think less than 20, though this is somewhat computer dependent.)') # Functions... doc.addFunction(gmm.modelSelectBIC) # Classes... doc.addClass(gmm.KMeansShared) doc.addClass(gmm.KMeans0) doc.addClass(gmm.KMeans1) doc.addClass(gmm.KMeans2) doc.addClass(gmm.KMeans3) doc.addClass(gmm.Mixture) doc.addClass(gmm.IsotropicGMM)
[ [ 1, 0, 0.2456, 0.0175, 0, 0.66, 0, 987, 0, 1, 0, 0, 987, 0, 0 ], [ 1, 0, 0.2807, 0.0175, 0, 0.66, 0.0476, 970, 0, 1, 0, 0, 970, 0, 0 ], [ 14, 0, 0.3684, 0.0175, 0, ...
[ "import gmm", "from utils import doc_gen", "doc = doc_gen.DocGen('gmm', 'Gaussian Mixture Model (plus K-means)', 'Gaussian mixture model, with EM, plus assorted k-means implimentations')", "doc.addFile('readme.txt', 'Overview')", "def pruneClassOfDo(cls):\n methods = dir(cls)\n for method in methods:\n ...
# -*- coding: utf-8 -*- # Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import math import exceptions import cPickle as pickle import numpy class KMeansShared: """Provides a standard interface for k-means, so that all implimentations provide the same one. key issue is that features can be provided in 3 ways - an array where each row is a feature, a list of feature vectors, a list of tuples where the last entry of each tuple is the feature vector. These are then passed through to return values, but the actual implimentation only has to deal with one interface.""" def __init__(self): self.means = None # Matrix of mean points, where each row is the coordinate of the centre of a cluster. def parameters(self): """Returns how many parameters the currently fitted model has, used for model selection.""" return self.means.shape[0]*self.means.shape[1] def clusterCount(self): """returns how many clusters it has been trained with, returns 0 if it has not been trainned.""" if self.means!=None: return self.means.shape[0] else: return 0 def getCentre(self, i): """Returns the centre of the indexed cluster.""" return self.means[i,:] def doTrain(self, feats, clusters): """Should train the model given a data matrix, where each row is a feature.""" raise exceptions.NotImplementedError() def doGetCluster(self, feats): """feats should arrive as a 2D array, where each row is a feature - should return an integer vector of which cluster each array is assigned to. Default implimentation uses brute force, which is typically fast enough assuming a reasonable number of clusters.""" ret = numpy.empty(feats.shape[0],dtype=numpy.int_) for i in xrange(feats.shape[0]): ret[i] = ((self.means-feats[i,:])**2).sum(axis=1).argmin() return ret def train(self, feats, clusters, *listArgs, **dictArgs): """Given the features and number of clusters, plus any implimentation specific arguments, this trains the model. Features can be provided as a data matrix, as a list of feature vectors or as a list of tuples where the last entry of each tuple is a feature vector.""" if isinstance(feats,numpy.ndarray): # Numpy array - just pass through... assert(len(feats.shape)==2) self.doTrain(feats,clusters,*listArgs,**dictArgs) del listArgs,dictArgs elif isinstance(feats,list): if isinstance(feats[0],numpy.ndarray): # List of vectors - glue them all together to create a data matrix and pass on through... data = numpy.vstack(feats) self.doTrain(data,clusters,*listArgs,**dictArgs) del listArgs,dictArgs elif isinstance(feats[0],tuple): # List of tuples where the last item should be a numpy.array as a feature vector... vecs = map(lambda x:x[-1],feats) data = numpy.vstack(vecs) self.doTrain(data,clusters,*listArgs,**dictArgs) del listArgs,dictArgs else: raise exceptions.TypeError('bad type for features - when given a list it must contain numpy.array vectors or tuples with the last element a vector') else: raise exceptions.TypeError('bad type for features - expects a numpy.array or a list') def getCluster(self, feats): """Converts the feature vectors of the input into integers, which represent the cluster which each feature is most likelly a member of. Output will be the same form as the input, but with the features converted to integers. In the case of a feature matrix it will become a vector of integers. For a list of feature vectors it will become a list of integers. For a list of tuples with the last element a feature vector it will return a list of tuples where the last element has been replaced with an integer.""" if isinstance(feats,numpy.ndarray): # Numpy array - just pass through... assert(len(feats.shape)==2) return self.doGetCluster(feats) elif isinstance(feats,list): if isinstance(feats[0],numpy.ndarray): # List of vectors - glue them all together to create a data matrix and pass on through... data = numpy.vstack(feats) asVec = self.doGetCluster(data) return map(lambda i:asVec[i],xrange(asVec.shape[0])) elif isinstance(feats[0],tuple): # List of tuples where the last item should be a numpy.array as a feature vector... vecs = map(lambda x:x[-1],feats) data = numpy.vstack(vecs) asVec = self.doGetCluster(data) return map(lambda i:feats[i][:-1] + (asVec[i],),xrange(asVec.shape[0])) else: raise exceptions.TypeError('bad type for features - when given a list it must contain numpy.array vectors or tuples with the last element a vector') else: raise exceptions.TypeError('bad type for features - expects a numpy.array or a list') def doGetNLL(self, feats): """Takes feats as a 2D data matrix and calculates the negative log likelihood of those features comming from the model, noting that it assumes a symmetric Gaussian for each centre and calculates the standard deviation using the provided features.""" # Record each features distance from its nearest cluster centre... distSqr = numpy.empty(feats.shape[0], dtype=numpy.float_) cat = numpy.empty(feats.shape[0], dtype=numpy.int_) for i in xrange(feats.shape[0]): distsSqr = ((self.means-feats[i,:].reshape((1,-1)))**2).sum(axis=1) cat[i] = distsSqr.argmin() distSqr[i] = distsSqr.min() # Calculate the standard deviation to use for all clusters... var = distSqr.sum() / (feats.shape[0] - self.means.shape[0]) # Sum up the log likelihood for all features... mult = -0.5/var norm = numpy.log(numpy.bincount(cat)) norm -= numpy.log(feats.shape[0]) norm -= 0.5 * (numpy.log(2.0*numpy.pi) + self.means.shape[1]*numpy.log(var)) ll = (distSqr*mult).sum() ll += norm[cat].sum() # Return the negative ll... return -ll def getNLL(self, feats): """Given a set of features returns the negative log likelihood of the given features being generated by the model. Note that as the k-means model is not probabilistic this is technically wrong, but it hacks it by treating each cluster as a symmetric Gaussian with a standard deviation calculated using the provided features, with equal probability of selecting each cluster.""" if isinstance(feats,numpy.ndarray): # Numpy array - just pass through... assert(len(feats.shape)==2) return self.doGetNLL(feats) elif isinstance(feats,list): if isinstance(feats[0],numpy.ndarray): # List of vectors - glue them all together to create a data matrix and pass on through... data = numpy.vstack(feats) return self.doGetNLL(data) elif isinstance(feats[0],tuple): # List of tuples where the last item should be a numpy.array as a feature vector... vecs = map(lambda x:x[-1],feats) data = numpy.vstack(vecs) return self.doGetNLL(data) else: raise exceptions.TypeError('bad type for features - when given a list it must contain numpy.array vectors or tuples with the last element a vector') else: raise exceptions.TypeError('bad type for features - expects a numpy.array or a list') def save(self, filename): """Saves the learned parameters to a file.""" pickle.dump(self.means, open(filename,'wb'), pickle.HIGHEST_PROTOCOL) def load(self, filename): """Loads the learned parameters from a file.""" self.means = pickle.load(open(filename,'rb')) def getData(self): """Returns the data contained within, so it can be serialised with other data. (You can of course serialise this class directly if you want, but the returned object is a numpy array, so less likely to be an issue for any program that loads it.)""" return self.means def setData(self,data): """Sets the data for the object, should be same form as returned from getData.""" self.means = data
[ [ 1, 0, 0.0769, 0.0059, 0, 0.66, 0, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 1, 0, 0.0828, 0.0059, 0, 0.66, 0.25, 63, 0, 1, 0, 0, 63, 0, 0 ], [ 1, 0, 0.0888, 0.0059, 0, 0.66...
[ "import math", "import exceptions", "import cPickle as pickle", "import numpy", "class KMeansShared:\n \"\"\"Provides a standard interface for k-means, so that all implimentations provide the same one. key issue is that features can be provided in 3 ways - an array where each row is a feature, a list of fe...
# -*- coding: utf-8 -*- # Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import math import random import numpy import scipy.weave as weave from kmeans_shared import KMeansShared class KMeans1(KMeansShared): """The most basic implimentation of k-means possible - just brute force with multiple restarts.""" def doTrain(self, feats, clusters, maxIters = 512, restarts = 8, minSize = 4, callback = None, assignOut = None): """Given a large number of features as a data matrix this finds a good set of cluster centres. clusters is the number of clusters to create, maxIters is the maximum number of iterations for convergance of a cluster and restarts how many times to run - the most probable result is used. minSize is the smallest cluster size - if a cluster is smaller than this it is reinitialised.""" if callback!=None: callback(0,restarts+1) # Required data structures... bestModelScore = None # Score of the model currently in self.means centres = numpy.empty((clusters,feats.shape[1]), dtype=numpy.float_) assignment = numpy.empty(feats.shape[0], dtype=numpy.int_) assignmentCount = numpy.empty(clusters, dtype=numpy.int_) # Iterate and run the algorithm from scratch a number of times, calculating the log likelihood of the model each time, so we can ultimatly select the best... for r in xrange(restarts): if callback!=None: callback(1+r,restarts+1) # Initialisation - fill in the matrix of cluster centres, where centres are initialised by randomly selecting a point from the data set (With duplication - we let the reinitalisation code deal with them.)... for c in xrange(centres.shape[0]): ri = random.randrange(feats.shape[0]) centres[c,:] = feats[ri,:] assignment[:] = -1 try: code = """ for (int i=0;i<maxIters;i++) { // Reassign features to clusters... bool change = false; for (int f=0;f<Nfeats[0];f++) { int best = -1; float bestDist = 1e100; for (int c=0;c<Ncentres[0];c++) { float dist = 0.0; for (int e=0;e<Nfeats[1];e++) { float d = FEATS2(f,e) - CENTRES2(c,e); dist += d*d; } if (dist<bestDist) { best = c; bestDist = dist; } } if (best!=ASSIGNMENT1(f)) { ASSIGNMENT1(f) = best; change = true; } } // If no reassignments happen break out early... if (change==false) break; // Recalculate cluster centres with an incrimental mean... for (int c=0;c<Ncentres[0];c++) { for (int e=0;e<Nfeats[1];e++) {CENTRES2(c,e) = 0.0;} ASSIGNMENTCOUNT1(c) = 0; } for (int f=0;f<Nfeats[0];f++) { int c = ASSIGNMENT1(f); ASSIGNMENTCOUNT1(c) += 1; float div = ASSIGNMENTCOUNT1(c); for (int e=0;e<Nfeats[1];e++) { CENTRES2(c,e) += (FEATS2(f,e) - CENTRES2(c,e)) / div; } } // Reassign puny clusters... for (int c=0;c<Ncentres[0];c++) { if (ASSIGNMENTCOUNT1(c)<minSize) { int rf = rand() % Nfeats[0]; for (int e=0;e<Nfeats[1];e++) { CENTRES2(c,e) = FEATS2(rf,e); } } } } """ weave.inline(code,['centres', 'assignment', 'assignmentCount','feats','maxIters','minSize']) except: # Iterate until convergance... for i in xrange(maxIters): # Re-assign features to clusters... beenChange = False for i in xrange(feats.shape[0]): # Slow bit nearest = ((centres-feats[i,:])**2).sum(axis=1).argmin() if nearest!=assignment[i]: beenChange = True assignment[i] = nearest # If no reassignments happen break out early... if beenChange==False: break # Recalculate cluster centres (Incrimental mean used)... centres[:] = 0.0 assignmentCount[:] = 0 for i in xrange(feats.shape[0]): c = assignment[i] assignmentCount[c] += 1 centres[c,:] += (feats[i,:]-centres[c,:])/float(assignmentCount[c]) # Find all puny clusters and reinitialise... indices = numpy.argsort(assignmentCount) for ic in xrange(indices.shape[0]): c = indices[ic] if assignmentCount[c]>=minSize: break ri = random.randrange(feats.shape[0]) centres[c,:] = feats[ri,:] # Calculate the models negative log likelihood - if better than the current model replace it (This is done proportionally)... if bestModelScore==None: self.means = centres.copy() else: negLogLike = 0.0 for i in xrange(feats.shape[0]): negLogLike += ((feats[i,:]-centres[assignment[i],:])**2).sum() if negLogLike<bestModelScore: self.means = centres.copy() if assignOut!=None: assignOut[:] = assignment
[ [ 1, 0, 0.0788, 0.0061, 0, 0.66, 0, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 1, 0, 0.0848, 0.0061, 0, 0.66, 0.2, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.097, 0.0061, 0, 0.66...
[ "import math", "import random", "import numpy", "import scipy.weave as weave", "from kmeans_shared import KMeansShared", "class KMeans1(KMeansShared):\n \"\"\"The most basic implimentation of k-means possible - just brute force with multiple restarts.\"\"\"\n\n def doTrain(self, feats, clusters, maxIter...
# -*- coding: utf-8 -*- # Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. # Includes everything needed to use the module in a single namespace, for conveniance... from kmeans import * from isotropic import IsotropicGMM from bic import modelSelectBIC from kmeans_shared import KMeansShared from mixture import Mixture
[ [ 1, 0, 0.7895, 0.0526, 0, 0.66, 0, 622, 0, 1, 0, 0, 622, 0, 0 ], [ 1, 0, 0.8421, 0.0526, 0, 0.66, 0.25, 783, 0, 1, 0, 0, 783, 0, 0 ], [ 1, 0, 0.8947, 0.0526, 0, 0....
[ "from kmeans import *", "from isotropic import IsotropicGMM", "from bic import modelSelectBIC", "from kmeans_shared import KMeansShared", "from mixture import Mixture" ]
# -*- coding: utf-8 -*- # Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import math import random import numpy import scipy.weave as weave from kmeans_shared import KMeansShared class KMeans2(KMeansShared): """This version of kmeans gets clever with its initialisation, running k-means on a subset of points, repeatedly, then combining the various runs, before ultimatly only doing k-means on the full dataset just once. This optimisation is only valuable for large data sets, e.g. with at least 10k feature vectors, and will cause slow down for small data sets.""" def __kmeans(self, centres, data, minSize = 3, maxIters = 1024, assignOut = None): """Internal method - does k-means on the data set as it is treated internally. Given the initial set of centres and a data matrix - the centres matrix is then updated to the new positions.""" assignment = numpy.empty(data.shape[0], dtype=numpy.int_) assignmentCount = numpy.empty(centres.shape[0], dtype=numpy.int_) assignment[:] = -1 code = """ for (int i=0;i<maxIters;i++) { // Reassign features to clusters... bool change = false; for (int f=0;f<Ndata[0];f++) { int best = -1; float bestDist = 1e100; for (int c=0;c<Ncentres[0];c++) { float dist = 0.0; for (int e=0;e<Ndata[1];e++) { float d = DATA2(f,e) - CENTRES2(c,e); dist += d*d; } if (dist<bestDist) { best = c; bestDist = dist; } } if (best!=ASSIGNMENT1(f)) { ASSIGNMENT1(f) = best; change = true; } } // If no reassignments happen break out early... if (change==false) break; // Recalculate cluster centres with an incrimental mean... for (int c=0;c<Ncentres[0];c++) { for (int e=0;e<Ndata[1];e++) {CENTRES2(c,e) = 0.0;} ASSIGNMENTCOUNT1(c) = 0; } for (int f=0;f<Ndata[0];f++) { int c = ASSIGNMENT1(f); ASSIGNMENTCOUNT1(c) += 1; float div = ASSIGNMENTCOUNT1(c); for (int e=0;e<Ndata[1];e++) { CENTRES2(c,e) += (DATA2(f,e) - CENTRES2(c,e)) / div; } } // Reassign puny clusters... for (int c=0;c<Ncentres[0];c++) { if (ASSIGNMENTCOUNT1(c)<minSize) { int rf = rand() % Ndata[0]; for (int e=0;e<Ndata[1];e++) { CENTRES2(c,e) = DATA2(rf,e); } } } } """ weave.inline(code,['centres', 'assignment', 'assignmentCount','data','maxIters','minSize']) if assignOut!=None: assignOut[:] = assignment def doTrain(self, feats, clusters, callback = None, smallCount = 32, smallMult = 3, minSize = 2, maxIters = 256, assignOut = None): """Given a features data matrix this finds a good set of cluster centres. clusters is the number of clusters to create.""" if callback!=None: callback(0,smallCount*2+2) # Iterate through and create a set of centres derived from small samples... smallSize = clusters * smallMult * minSize startOptions = [] for i in xrange(smallCount): if callback!=None: callback(1+i,smallCount*2+2) # Grab a small sample from the data matrix, in randomised order... sample = feats[numpy.random.permutation(feats.shape[0])[:smallSize],:] # Select the first 'clusters' rows as the initial centres - its already in random order so no point in more randomisation... centres = sample[:clusters,:] # Run k-means... self.__kmeans(centres, sample, minSize, maxIters) # Store the set of centres ready for the next bit... startOptions.append(centres) # Iterate through each of the centres calculated above, using them to initialise kmeans on all the centres combined; select the centres that have the minimum negative log likelihood on this limited data set as the intialisation for the final step (Use a value that is proportional rather than actually calculating -log likelihood.)... allStarts = numpy.vstack(startOptions) bestStart = None bestScore = 1e100 for i,centres in enumerate(startOptions): if callback!=None: callback(1+smallCount+i,smallCount*2+2) # Run k-means... self.__kmeans(centres, allStarts, minSize, maxIters) # Calculate the sum of distances from the nearest centres, which is proportional to the negative log likelihood of the model... distSum = 0.0 for i in xrange(allStarts.shape[0]): distSum += ((centres-allStarts[i])**2).sum(axis=1).min() # If better then previous scores store it for use... if distSum<bestScore: bestStart = centres bestScore = distSum # Finally do k-means on the full data set, using the initialisation that has been calculated... if callback!=None: callback(1+smallCount*2,smallCount*2+2) self.__kmeans(bestStart, feats, minSize, maxIters, assignOut) self.means = bestStart del callback # There is a bug in here somewhere and this fixes it. Fixing the actual bug might be wise, but I just can't see it. (Somehow the functions callspace is kept, but can't see how.)
[ [ 1, 0, 0.0818, 0.0063, 0, 0.66, 0, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 1, 0, 0.0881, 0.0063, 0, 0.66, 0.2, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.1006, 0.0063, 0, 0.6...
[ "import math", "import random", "import numpy", "import scipy.weave as weave", "from kmeans_shared import KMeansShared", "class KMeans2(KMeansShared):\n \"\"\"This version of kmeans gets clever with its initialisation, running k-means on a subset of points, repeatedly, then combining the various runs, be...
# -*- coding: utf-8 -*- # Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import math import random import numpy import scipy.weave as weave from kmeans import KMeans from mixture import Mixture class IsotropicGMM(Mixture): """Fits a gaussian mixture model to a data set, using isotropic Gaussians, i.e. so each is parameterised by only a single standard deviation, in addition to position and weight.""" def __init__(self): self.mix = None # Vector of mixing probabilities. self.mean = None # 2D array where each row is the mean of a distribution. self.sd = None # Vector of standard deviations. def clusterCount(self): """Returns how many clusters it has been fitted with, or 0 if it is yet to be trainned.""" if self.mix!=None: return self.mix.shape[0] else: return 0 def parameters(self): """Returns how many parameters the currently fitted model has, used for model selection.""" return self.mean.shape[0]*(self.mean.shape[1]+2) def getMix(self,i): """Returns the mixing weight for the given cluster.""" return self.mix[i] def getCentre(self,i): """Returns the mean/centre of the given cluster.""" return self.mean[i,:] def getSD(self,i): """Returns the standard deviation for the given cluster.""" return self.sd[i] def doTrain(self, feats, clusters, maxIters = 1024, epsilon = 1e-4): # Initialise using kmeans... km = KMeans() kmAssignment = numpy.empty(feats.shape[0],dtype=numpy.float_) km.train(feats,clusters,assignOut = kmAssignment) # Create the assorted data structures needed... mix = numpy.ones(clusters,dtype=numpy.float_)/float(clusters) mean = numpy.empty((clusters,feats.shape[1]),dtype=numpy.float_) for c in xrange(clusters): mean[c,:] = km.getCentre(c) sd = numpy.zeros(clusters,dtype=numpy.float_) tempCount = numpy.zeros(clusters,dtype=numpy.int_) for f in xrange(feats.shape[0]): c = kmAssignment[f] dist = ((feats[f,:] - mean[c,:])**2).sum() tempCount[c] += 1 sd += (dist-sd)/float(tempCount[c]) sd = numpy.sqrt(sd/float(feats.shape[1])) wv = numpy.ones((feats.shape[0],clusters),dtype=numpy.float_) # Weight vectors calculated in e-step. pwv = numpy.empty(clusters,dtype=numpy.float_) # For convergance detection. norms = numpy.empty(clusters,dtype=numpy.float_) # Normalising constants for the distributions, to save repeated calculation. sqrt2pi = math.sqrt(2.0*math.pi) # The code... code = """ for (int iter=0;iter<maxIters;iter++) { // e-step - for all features calculate the weight vector (Also do convergance detection.)... for (int c=0;c<Nmean[0];c++) { norms[c] = pow(sqrt2pi*sd[c], Nmean[1]); } bool done = true; for (int f=0;f<Nfeats[0];f++) { float sum = 0.0; for (int c=0;c<Nmean[0];c++) { float distSqr = 0.0; for (int i=0;i<Nmean[1];i++) { float diff = FEATS2(f,i) - MEAN2(c,i); distSqr += diff*diff; } pwv[c] = WV2(f,c); float core = -0.5*distSqr / (sd[c]*sd[c]); WV2(f,c) = mix[c]*exp(core); // Unnormalised. WV2(f,c) /= norms[c]; // Normalisation sum += WV2(f,c); } for (int c=0;c<Nmean[0];c++) { WV2(f,c) /= sum; done = done && (fabs(WV2(f,c)-pwv[c])<epsilon); } } if (done) break; // Zero out mix,mean and sd, ready for filling... for (int c=0;c<Nmean[0];c++) { mix[c] = 0.0; for (int i=0;i<Nmean[1];i++) MEAN2(c,i) = 0.0; sd[c] = 0.0; } // m-step - update the mixing vector, means and sd... // *Calculate mean and mixing vector incrimentally... for (int f=0;f<Nfeats[0];f++) { for (int c=0;c<Nmean[0];c++) { mix[c] += WV2(f,c); if (WV2(f,c)>1e-6) // Msut not update if value is too low due to division in update - NaN avoidance. { for (int i=0;i<Nmean[1];i++) { MEAN2(c,i) += WV2(f,c) * (FEATS2(f,i) - MEAN2(c,i)) / mix[c]; } } } } // prevent the mix of any given component getting too low - will cause the algorithm to NaN... for (int c=0;c<Nmean[0];c++) { if (mix[c]<1e-6) mix[c] = 1e-6; } // *Calculate the sd simply, initial calculation is sum of squared differences... for (int f=0;f<Nfeats[0];f++) { for (int c=0;c<Nmean[0];c++) { float distSqr = 0.0; for (int i=0;i<Nmean[1];i++) { float delta = FEATS2(f,i) - MEAN2(c,i); distSqr += delta*delta; } sd[c] += WV2(f,c) * distSqr; } } // *Final adjustments for the new state... float mixSum = 0.0; for (int c=0;c<Nmean[0];c++) { sd[c] = sqrt(sd[c]/(mix[c]*float(Nfeats[1]))); mixSum += mix[c]; } for (int c=0;c<Nmean[0];c++) mix[c] /= mixSum; } """ # Weave it... weave.inline(code,['feats', 'maxIters', 'epsilon', 'mix', 'mean', 'sd', 'wv', 'pwv', 'norms', 'sqrt2pi']) # Store result... self.mix = mix self.mean = mean self.sd = sd def doGetUnnormWeight(self,feats): ret = numpy.empty((feats.shape[0],self.mix.shape[0]),dtype=numpy.float_) norms = numpy.empty(self.mix.shape[0],dtype=numpy.float_) # Normalising constants for the distributions, to save repeated calculation. sqrt2pi = math.sqrt(2.0*math.pi) code = """ for (int c=0;c<Nmean[0];c++) norms[c] = pow(sqrt2pi*sd[c],Nmean[1]); for (int f=0;f<Nfeats[0];f++) { float sum = 0.0; for (int c=0;c<Nmean[0];c++) { float distSqr = 0.0; for (int i=0;i<Nmean[1];i++) { float diff = FEATS2(f,i) - MEAN2(c,i); distSqr += diff*diff; } RET2(f,c) = mix[c]*exp(-0.5*distSqr/(sd[c]*sd[c])); // Unnormalised. RET2(f,c) /= norms[c]; // Normalisation } } """ mix = self.mix mean = self.mean sd = self.sd weave.inline(code,['feats', 'ret', 'mix', 'mean', 'sd', 'norms', 'sqrt2pi']) return ret def doGetWeight(self,feats): """Returns the probability of it being drawn from each of the clusters, as a vector. It will obviously sum to one.""" ret = self.doGetUnnormWeight(feats) ret = (ret.T/ret.sum(axis=1)).T return ret def doGetCluster(self,feats): """Returns the cluster it is, with greatest probability, a member of.""" return self.doGetUnnormWeight(feats).argmax(axis=1) def doGetNLL(self,feats): """returns the negative log likelihood of the given set of features being drawn from the model.""" return -numpy.log(self.doGetUnnormWeight(feats).sum(axis=1)).sum() def getData(self): """Returns the data contained within, so it can be serialised with other data. (You can of course serialise this class directly if you want, but the returned object is a tuple of numpy arrays, so less likely to be an issue for any program that loads it.)""" return (self.mix,self.mean,self.sd) def setData(self,data): """Sets the data for the object, should be same form as returned from getData.""" self.mix = data[0] self.mean = data[1] self.sd = data[2]
[ [ 1, 0, 0.0535, 0.0041, 0, 0.66, 0, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 1, 0, 0.0576, 0.0041, 0, 0.66, 0.1667, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.0658, 0.0041, 0, ...
[ "import math", "import random", "import numpy", "import scipy.weave as weave", "from kmeans import KMeans", "from mixture import Mixture", "class IsotropicGMM(Mixture):\n \"\"\"Fits a gaussian mixture model to a data set, using isotropic Gaussians, i.e. so each is parameterised by only a single standar...
# -*- coding: utf-8 -*-
[]
[]
# -*- coding: utf-8 -*- # Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. # Simple file that imports the various implimentations and provides a default implimentation of kmeans, which happens to be the most sophisticated version... from kmeans0 import KMeans0 from kmeans1 import KMeans1 from kmeans2 import KMeans2 from kmeans3 import KMeans3 KMeansShort = KMeans1 KMeans = KMeans3
[ [ 1, 0, 0.7143, 0.0476, 0, 0.66, 0, 470, 0, 1, 0, 0, 470, 0, 0 ], [ 1, 0, 0.7619, 0.0476, 0, 0.66, 0.2, 177, 0, 1, 0, 0, 177, 0, 0 ], [ 1, 0, 0.8095, 0.0476, 0, 0.6...
[ "from kmeans0 import KMeans0", "from kmeans1 import KMeans1", "from kmeans2 import KMeans2", "from kmeans3 import KMeans3", "KMeansShort = KMeans1", "KMeans = KMeans3" ]
# -*- coding: utf-8 -*- # Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import exceptions import cPickle as pickle import numpy class Mixture: """Defines the basic interface to a mixture model - the methods to train, and then classify basically. Includes funky conversions to allow many forms of input/output, for conveniance.""" def clusterCount(self): """To be implimented by the inheriting class - returns how many elements the mixture has, i.e. the cluster count.""" raise exceptions.NotImplementedError() def parameters(self): """To be implimented by the inheriting class - returns how many parameters the model has.""" raise exceptions.NotImplementedError() def doTrain(self,feats,clusters): """To be implimented by the inheriting class, possibly with further implimentation specific parameters. Accepts a data matrix and a cluster count.""" raise exceptions.NotImplementedError() def doGetWeight(self,feats): """To be implimented by the inheriting class. Given a data matrix returns a new matrix, where the feature vectors have been replaced by the probabilities of the feature being generated by each of the clusters.""" raise exceptions.NotImplementedError() def doGetCluster(self,feats): """To be implimented by the inheriting class. Given a data matrix returns an integer vector, where each feature vector has assigned the cluster from which it most likelly comes.""" raise exceptions.NotImplementedError() def doGetNLL(self,feats): """To be implimented by the inheriting class. Given a data matrix returns the negative log likelihood of the data comming from this model.""" raise exceptions.NotImplementedError() def train(self,feats,clusters,*listArgs,**dictArgs): """Accepts as input the features, how many clusters to use and any further implimentation specific variables. The features can be represented as a data matrix, a list of vectors or as a list of tuples where the last entry is a feature vector. Will then train the model on the given data set.""" if isinstance(feats,numpy.ndarray): # Numpy array - just pass through... assert(len(feats.shape)==2) self.doTrain(feats,clusters,*listArgs,**dictArgs) elif isinstance(feats,list): if isinstance(feats[0],numpy.ndarray): # List of vectors - glue them all together to create a data matrix and pass on through... data = numpy.vstack(feats) self.doTrain(data,clusters,*listArgs,**dictArgs) elif isinstance(feats[0],tuple): # List of tuples where the last item should be a numpy.array as a feature vector... vecs = map(lambda x:x[-1],feats) data = numpy.vstack(vecs) self.doTrain(data,clusters,*listArgs,**dictArgs) else: raise exceptions.TypeError('bad type for features - when given a list it must contain numpy.array vectors or tuples with the last element a vector') else: raise exceptions.TypeError('bad type for features - expects a numpy.array or a list') def getWeight(self,feats): """Given a set of features returns for each feature the probability of having been generated by each mixture member - this vector will sum to one. Multiple input/output modes are supported. If a data matrix is input then the output will be a matrix where each row has been replaced by the mixing vector. If the input is a list of feature vectors the output will be a list of mixing vectors. If the input is a list of tuples with the last elements a feature vector the output will be identical, but with the feature vectors replaced with mixing vectors.""" if isinstance(feats,numpy.ndarray): # Numpy array - just pass through... assert(len(feats.shape)==2) return self.doGetWeight(feats) elif isinstance(feats,list): if isinstance(feats[0],numpy.ndarray): # List of vectors - glue them all together to create a data matrix and pass on through... data = numpy.vstack(feats) asMat = self.doGetWeight(data) return map(lambda i:asMat[i,:],xrange(asMat.shape[0])) elif isinstance(feats[0],tuple): # List of tuples where the last item should be a numpy.array as a feature vector... vecs = map(lambda x:x[-1],feats) data = numpy.vstack(vecs) asMat = self.doGetWeight(data) return map(lambda i:feats[i][:-1] + (asMat[i,:],),xrange(asMat.shape[0])) else: raise exceptions.TypeError('bad type for features - when given a list it must contain numpy.array vectors or tuples with the last element a vector') else: raise exceptions.TypeError('bad type for features - expects a numpy.array or a list') def getCluster(self,feats): """Given a set of features returns for each feature the cluster with the highest probability of having generated it. Multiple input/output modes are supported. If a data matrix is input then the output will be an integer vector of cluster indices. If the input is a list of feature vectors the output will be a list of cluster indices. If the input is a list of tuples with the last elements a feature vector the output will be identical, but with the feature vectors replaced by cluster integers.""" if isinstance(feats,numpy.ndarray): # Numpy array - just pass through... assert(len(feats.shape)==2) return self.doGetCluster(feats) elif isinstance(feats,list): if isinstance(feats[0],numpy.ndarray): # List of vectors - glue them all together to create a data matrix and pass on through... data = numpy.vstack(feats) asVec = self.doGetCluster(data) return map(lambda i:asVec[i],xrange(asVec.shape[0])) elif isinstance(feats[0],tuple): # List of tuples where the last item should be a numpy.array as a feature vector... vecs = map(lambda x:x[-1],feats) data = numpy.vstack(vecs) asVec = self.doGetCluster(data) return map(lambda i:feats[i][:-1] + (asVec[i],),xrange(asVec.shape[0])) else: raise exceptions.TypeError('bad type for features - when given a list it must contain numpy.array vectors or tuples with the last element a vector') else: raise exceptions.TypeError('bad type for features - expects a numpy.array or a list') def getNLL(self,feats): """Given a set of features returns the negative log likelihood of the given features being generated by the model.""" if isinstance(feats,numpy.ndarray): # Numpy array - just pass through... assert(len(feats.shape)==2) return self.doGetNLL(feats) elif isinstance(feats,list): if isinstance(feats[0],numpy.ndarray): # List of vectors - glue them all together to create a data matrix and pass on through... data = numpy.vstack(feats) return self.doGetNLL(data) elif isinstance(feats[0],tuple): # List of tuples where the last item should be a numpy.array as a feature vector... vecs = map(lambda x:x[-1],feats) data = numpy.vstack(vecs) return self.doGetNLL(data) else: raise exceptions.TypeError('bad type for features - when given a list it must contain numpy.array vectors or tuples with the last element a vector') else: raise exceptions.TypeError('bad type for features - expects a numpy.array or a list') def getData(self): """Returns the data contained within, so it can be serialised with other data. (You can of course serialise this class directly if you want, but the returned object is a tuple of numpy arrays, so less likely to be an issue for any program that loads it.)""" raise exceptions.NotImplementedError() def setData(self,data): """Sets the data for the object, should be same form as returned from getData.""" raise exceptions.NotImplementedError()
[ [ 1, 0, 0.089, 0.0068, 0, 0.66, 0, 63, 0, 1, 0, 0, 63, 0, 0 ], [ 1, 0, 0.0959, 0.0068, 0, 0.66, 0.3333, 279, 0, 1, 0, 0, 279, 0, 0 ], [ 1, 0, 0.1096, 0.0068, 0, 0.6...
[ "import exceptions", "import cPickle as pickle", "import numpy", "class Mixture:\n \"\"\"Defines the basic interface to a mixture model - the methods to train, and then classify basically. Includes funky conversions to allow many forms of input/output, for conveniance.\"\"\"\n def clusterCount(self):\n \...
# Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. class PriorConcDP: """Contains the parameters required for the concentration parameter of a DP - specifically its Gamma prior and initial concentration value.""" def __init__(self, other = None): if other!=None: self.__alpha = other.alpha self.__beta = other.beta self.__conc = other.conc else: self.__alpha = 1.0 self.__beta = 1.0 self.__conc = 16.0 def getAlpha(self): """Getter for alpha.""" return self.__alpha def getBeta(self): """Getter for beta.""" return self.__beta def getConc(self): """Getter for the initial concentration.""" return self.__conc def setAlpha(self, alpha): """Setter for alpha.""" assert(alpha>0.0) self.__alpha = alpha def setBeta(self, beta): """Setter for beta.""" assert(beta>0.0) self.__beta = beta def setConc(self, conc): """Setter for the initial concentration.""" assert(conc>=0.0) self.__conc = conc alpha = property(getAlpha, setAlpha, None, "The alpha parameter of the Gamma prior over the concentration parameter.") beta = property(getBeta, setBeta, None, "The beta parameter of the Gamma prior over the concentration parameter.") conc = property(getConc, setConc, None, "The starting value of the concentration parameter, to be updated.")
[ [ 3, 0, 0.6058, 0.8077, 0, 0.66, 0, 607, 0, 7, 0, 0, 0, 0, 3 ], [ 8, 1, 0.2308, 0.0192, 1, 0.35, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 2, 1, 0.3269, 0.1731, 1, 0.35, 0...
[ "class PriorConcDP:\n \"\"\"Contains the parameters required for the concentration parameter of a DP - specifically its Gamma prior and initial concentration value.\"\"\"\n def __init__(self, other = None):\n if other!=None:\n self.__alpha = other.alpha\n self.__beta = other.beta\n self.__conc =...
# Copyright 2011 Tom SF Haines # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from scipy import weave import unittest from utils.start_cpp import start_cpp from ds_cpp import ds_code # Provides code for converting from the python to the C++ data structure, and back again - this is so the data can be stored in a suitable form in both situations, though it comes at the expense of a complex conversion... ds_link_code = ds_code + start_cpp() + """ // Helper for extracting a boolean from a Python object... bool GetObjectBool(PyObject * obj, const char * name) { PyObject * boolObj = PyObject_GetAttrString(obj, name); bool ret = boolObj==Py_True; Py_DECREF(boolObj); return ret; } // Helper converter for the Conc class and its python equivalent, PriorConcDP - just need to go one way. Given an object and the name of the variable in the object that is the PriorConcDP object... void ConcPyToCpp(PyObject * obj, const char * name, Conc & out) { PyObject * pyConc = PyObject_GetAttrString(obj,name); PyObject * alpha = PyObject_GetAttrString(pyConc,"_PriorConcDP__alpha"); out.alpha = PyFloat_AsDouble(alpha); Py_DECREF(alpha); PyObject * beta = PyObject_GetAttrString(pyConc,"_PriorConcDP__beta"); out.beta = PyFloat_AsDouble(beta); Py_DECREF(beta); PyObject * conc = PyObject_GetAttrString(pyConc,"_PriorConcDP__conc"); out.conc = PyFloat_AsDouble(conc); Py_DECREF(conc); Py_DECREF(pyConc); } // Python -> C++ - given pointers to the State class and a State object... // (The State object should be empty when passed.) void StatePyToCpp(PyObject * from, State * to) { // Extract the flags... to->dnrDocInsts = GetObjectBool(from,"dnrDocInsts"); to->dnrCluInsts = GetObjectBool(from,"dnrCluInsts"); to->seperateClusterConc = GetObjectBool(from,"seperateClusterConc"); to->seperateDocumentConc = GetObjectBool(from,"seperateDocumentConc"); to->oneCluster = GetObjectBool(from,"oneCluster"); to->calcBeta = GetObjectBool(from,"calcBeta"); to->calcCluBmn = GetObjectBool(from,"calcCluBmn"); to->calcPhi = GetObjectBool(from,"calcPhi"); to->resampleConcs = GetObjectBool(from,"resampleConcs"); to->behSamples = GetObjectInt(from,"behSamples"); // Extract all the parameters, though only rho and beta get stored in the state - others get used later when filling out other structures... Conc alpha; ConcPyToCpp(from,"alpha",alpha); PyArrayObject * beta = (PyArrayObject*)PyObject_GetAttrString(from,"beta"); to->beta = new float[beta->dimensions[0]]; to->betaSum = 0.0; for (int i=0;i<beta->dimensions[0];i++) { to->beta[i] = Float1D(beta,i); to->betaSum += to->beta[i]; } Py_DECREF(beta); Conc gamma; ConcPyToCpp(from,"gamma",gamma); ConcPyToCpp(from,"rho",to->rho); Conc mu; ConcPyToCpp(from,"mu",mu); PyArrayObject * phi = (PyArrayObject*)PyObject_GetAttrString(from,"phi"); to->phi = new float[phi->dimensions[0]]; for (int i=0;i<phi->dimensions[0];i++) { to->phi[i] = Float1D(phi,i); } Py_DECREF(phi); // Number of behaviours... { PyObject * abnorms = PyObject_GetAttrString(from,"abnorms"); to->behCount = 1 + PyDict_Size(abnorms); Py_DECREF(abnorms); } // Store the flag set matrix (Involves calling a python function.)... { PyObject * fia = PyObject_GetAttrString(from,"fia"); PyObject * func = PyObject_GetAttrString(fia,"getFlagMatrix"); to->flagSets = (PyArrayObject*)PyObject_CallObject(func, 0); Py_DECREF(func); Py_DECREF(fia); } // Create the topic objects... PyArrayObject * topicWord = (PyArrayObject*)PyObject_GetAttrString(from,"topicWord"); PyArrayObject * topicUse = (PyArrayObject*)PyObject_GetAttrString(from,"topicUse"); int topicCount = topicWord->dimensions[0]; int wordCount = topicWord->dimensions[1]; to->wordCount = wordCount; ItemRef<Topic,Conc> ** topicArray = new ItemRef<Topic,Conc>*[topicCount]; for (int t=0;t<topicCount;t++) { ItemRef<Topic,Conc> * topic = to->topics.Append(); topicArray[t] = topic; topic->id = t; topic->wc = new int[wordCount]; topic->wcTotal = 0; for (int w=0;w<wordCount;w++) { int val = Int2D(topicWord,t,w); topic->wc[w] = val; topic->wcTotal += val; } topic->beh = 0; topic->IncRef(Int1D(topicUse,t)); } Py_DECREF(topicUse); Py_DECREF(topicWord); PyObject * topicConc = PyObject_GetAttrString(from,"topicConc"); to->topics.Body().alpha = gamma.alpha; to->topics.Body().beta = gamma.beta; to->topics.Body().conc = PyFloat_AsDouble(topicConc); Py_DECREF(topicConc); // Do the abnormal topics... PyArrayObject * abnormTopicWord = (PyArrayObject*)PyObject_GetAttrString(from, "abnormTopicWord"); ItemRef<ClusterInst,Conc> ** abArray = new ItemRef<ClusterInst,Conc>*[to->behCount]; for (int b=0;b<to->behCount;b++) { ItemRef<Topic,Conc> * topic = to->behTopics.Append(); ItemRef<ClusterInst,Conc> * cluInst = to->behCluInsts.Append(); abArray[b] = cluInst; topic->IncRef(); cluInst->IncRef(); cluInst->SetTopic(topic,false); topic->id = -1; topic->wc = new int[wordCount]; topic->wcTotal = 0; for (int w=0;w<wordCount;w++) { int val = Int2D(abnormTopicWord,b,w); topic->wc[w] = val; topic->wcTotal += val; } topic->beh = b; cluInst->id = -1; } Py_DECREF(abnormTopicWord); // Now create the clusters... PyObject * cluster = PyObject_GetAttrString(from,"cluster"); PyArrayObject * clusterUse = (PyArrayObject*)PyObject_GetAttrString(from,"clusterUse"); int clusterCount = PyList_Size(cluster); ItemRef<Cluster,Conc> ** clusterArray = new ItemRef<Cluster,Conc>*[clusterCount]; ItemRef<ClusterInst,Conc> *** clusterInstArray = new ItemRef<ClusterInst,Conc>**[clusterCount]; for (int c=0;c<clusterCount;c++) { PyObject * cluEntry = PyList_GetItem(cluster,c); PyArrayObject * cluInst = (PyArrayObject*)PyTuple_GetItem(cluEntry,0); PyObject * cluConc = PyTuple_GetItem(cluEntry,1); PyArrayObject * cluBMN = (PyArrayObject*)PyTuple_GetItem(cluEntry,2); PyArrayObject * cluPriorBMN = (PyArrayObject*)PyTuple_GetItem(cluEntry,3); // Create the cluster instance... ItemRef<Cluster,Conc> * clu = to->clusters.Append(); clu->id = c; clusterArray[c] = clu; clu->IncRef(Int1D(clusterUse,c)); // Create the clusters topic instances, including filling in the counts... clusterInstArray[c] = new ItemRef<ClusterInst,Conc>*[cluInst->dimensions[0]]; for (int ci=0;ci<cluInst->dimensions[0];ci++) { ItemRef<ClusterInst,Conc> * nci = clu->Append(); nci->id = ci; clusterInstArray[c][ci] = nci; int topic = Int2D(cluInst,ci,0); int users = Int2D(cluInst,ci,1); if (topic!=-1) nci->SetTopic(topicArray[topic],false); nci->IncRef(users); } // Fill in the clusters concentration stuff... clu->Body().alpha = to->rho.alpha; clu->Body().beta = to->rho.beta; clu->Body().conc = PyFloat_AsDouble(cluConc); // Do the multinomial... float * bmn = new float[to->behCount]; for (int b=0;b<to->behCount;b++) { bmn[b] = Float1D(cluBMN, b); } clu->SetBMN(bmn); // Do the prior on bmn... int * bmnPrior = new int[to->flagSets->dimensions[0]]; for (int fs=0;fs<to->flagSets->dimensions[0];fs++) { bmnPrior[fs] = Int1D(cluPriorBMN, fs); } clu->SetBehCountPrior(bmnPrior); } Py_DECREF(clusterUse); Py_DECREF(cluster); PyObject * clusterConc = PyObject_GetAttrString(from,"clusterConc"); to->clusters.Body().alpha = mu.alpha; to->clusters.Body().beta = mu.beta; to->clusters.Body().conc = PyFloat_AsDouble(clusterConc); Py_DECREF(clusterConc); // Finally, create the documents... PyObject * docList = PyObject_GetAttrString(from,"doc"); to->docCount = PyList_Size(docList); delete[] to->doc; to->doc = new Document[to->docCount]; for (int d=0;d<to->docCount;d++) { // Get the relevant entities... PyObject * fromDoc = PyList_GetItem(docList,d); Document & toDoc = to->doc[d]; // Setup the link to the cluster... PyObject * clusterIndex = PyObject_GetAttrString(fromDoc,"cluster"); int cluIndex = PyInt_AsLong(clusterIndex); Py_DECREF(clusterIndex); if (cluIndex!=-1) toDoc.SetCluster(clusterArray[cluIndex],false); // Prep the documents DP... PyArrayObject * use = (PyArrayObject*)PyObject_GetAttrString(fromDoc,"use"); ItemRef<DocInst,Conc> ** docInstArray = new ItemRef<DocInst,Conc>*[use->dimensions[0]]; for (int di=0;di<use->dimensions[0];di++) { ItemRef<DocInst,Conc> * docInst = toDoc.Append(); docInst->id = di; docInstArray[di] = docInst; int ciBeh = Int2D(use,di,0); int ciIndex = Int2D(use,di,1); int ciUse = Int2D(use,di,2); if (ciBeh!=-1) { if (ciBeh==0) { docInst->SetClusterInst(clusterInstArray[cluIndex][ciIndex],false); } else { docInst->SetClusterInst(abArray[ciBeh]); } } docInst->IncRef(ciUse); } Py_DECREF(use); PyObject * docConc = PyObject_GetAttrString(fromDoc,"conc"); toDoc.Body().alpha = alpha.alpha; toDoc.Body().beta = alpha.beta; toDoc.Body().conc = PyFloat_AsDouble(docConc); Py_DECREF(docConc); // Store the samples... PyArrayObject * samples = (PyArrayObject*)PyObject_GetAttrString(fromDoc,"samples"); Sample * sArray = new Sample[samples->dimensions[0]]; for (int s=0;s<samples->dimensions[0];s++) { int di = Int2D(samples,s,0); if (di!=-1) sArray[s].SetDocInst(docInstArray[di],false); sArray[s].SetWord(Int2D(samples,s,1)); } toDoc.SetSamples(samples->dimensions[0],sArray); Py_DECREF(samples); // Do the abnormality vectors... PyArrayObject * behFlags = (PyArrayObject*)PyObject_GetAttrString(fromDoc,"behFlags"); PyArrayObject * behCounts = (PyArrayObject*)PyObject_GetAttrString(fromDoc,"behCounts"); unsigned char * bFlags = new unsigned char[behFlags->dimensions[0]]; int * bCounts = new int[behCounts->dimensions[0]]; for (int b=0;b<behFlags->dimensions[0];b++) { bFlags[b] = Byte1D(behFlags,b); bCounts[b] = Int1D(behCounts,b); } toDoc.SetBehFlags(bFlags); toDoc.SetFlagIndex(GetObjectInt(fromDoc,"behFlagsIndex")); toDoc.SetBehCounts(bCounts); Py_DECREF(behCounts); Py_DECREF(behFlags); // Clean up... delete[] docInstArray; } Py_DECREF(docList); // Some temporary storage... to->tempWord = new int[to->wordCount]; // Clean up... for (int c=0;c<clusterCount;c++) delete[] clusterInstArray[c]; delete[] clusterInstArray; delete[] clusterArray; delete[] abArray; delete[] topicArray; } // C++ -> Python - given pointers to the State class and a State object... // Note that this assumes that the State object was created from the PyObject in the first place - if not it will almost certainly break. void StateCppToPy(State * from, PyObject * to) { // Update the initial values of alpha, gamma, rho and mu to the current values... { float alpha = from->doc[0].Body().conc; float gamma = from->topics.Body().conc; float rho = from->rho.conc; float mu = from->clusters.Body().conc; PyObject * pyAlpha = PyFloat_FromDouble(alpha); PyObject * pyGamma = PyFloat_FromDouble(gamma); PyObject * pyRho = PyFloat_FromDouble(rho); PyObject * pyMu = PyFloat_FromDouble(mu); PyObject * alphaStore = PyObject_GetAttrString(to, "alpha"); PyObject * gammaStore = PyObject_GetAttrString(to, "gamma"); PyObject * rhoStore = PyObject_GetAttrString(to, "rho"); PyObject * muStore = PyObject_GetAttrString(to, "mu"); PyObject_SetAttrString(alphaStore, "conc", pyAlpha); PyObject_SetAttrString(gammaStore, "conc", pyGamma); PyObject_SetAttrString(rhoStore, "conc", pyRho); PyObject_SetAttrString(muStore, "conc", pyMu); Py_DECREF(pyAlpha); Py_DECREF(pyGamma); Py_DECREF(pyRho); Py_DECREF(pyMu); } // Extract beta - it could of been updated... npy_intp size[2]; size[0] = from->wordCount; PyArrayObject * beta = (PyArrayObject*)PyArray_SimpleNew(1,size,NPY_FLOAT); for (int i=0;i<from->wordCount;i++) { Float1D(beta,i) = from->beta[i]; } PyObject_SetAttrString(to,"beta",(PyObject*)beta); Py_DECREF(beta); // Extract phi - same as for beta... size[0] = from->behCount; PyArrayObject * phi = (PyArrayObject*)PyArray_SimpleNew(1,size,NPY_FLOAT); for (int i=0;i<from->behCount;i++) { Float1D(phi,i) = from->phi[i]; } PyObject_SetAttrString(to,"phi",(PyObject*)phi); Py_DECREF(phi); // Update the topics information - replace current... size[0] = from->topics.Size(); size[1] = from->wordCount; PyArrayObject * topicWord = (PyArrayObject*)PyArray_SimpleNew(2,size,NPY_INT); PyArrayObject * topicUse = (PyArrayObject*)PyArray_SimpleNew(1,size,NPY_INT); { ItemRef<Topic,Conc> * targ = from->topics.First(); for (int t=0;t<topicWord->dimensions[0];t++) { targ->id = t; for (int w=0;w<topicWord->dimensions[1];w++) { Int2D(topicWord,t,w) = targ->wc[w]; } Int1D(topicUse,t) = targ->RefCount(); targ = targ->Next(); } } PyObject_SetAttrString(to,"topicUse",(PyObject*)topicUse); PyObject_SetAttrString(to,"topicWord",(PyObject*)topicWord); Py_DECREF(topicUse); Py_DECREF(topicWord); PyObject * topicConc = PyFloat_FromDouble(from->topics.Body().conc); PyObject_SetAttrString(to,"topicConc",topicConc); Py_DECREF(topicConc); // Update the abnormal topic information - treat as an update... PyArrayObject * abnormTopicWord = (PyArrayObject*)PyObject_GetAttrString(to, "abnormTopicWord"); { ItemRef<Topic,Conc> * topic = from->behTopics.First(); while (topic->Valid()) { for (int w=0;w<abnormTopicWord->dimensions[1];w++) { Int2D(abnormTopicWord,topic->beh,w) = topic->wc[w]; } topic = topic->Next(); } } Py_DECREF(abnormTopicWord); // Update the clusters information - replace current... size[0] = from->clusters.Size(); PyObject * cluster = PyList_New(size[0]); PyArrayObject * clusterUse = (PyArrayObject*)PyArray_SimpleNew(1,size,NPY_INT); { ItemRef<Cluster,Conc> * clu = from->clusters.First(); for (int c=0;c<from->clusters.Size();c++) { clu->id = c; PyObject * tup = PyTuple_New(4); PyList_SetItem(cluster,c,tup); size[0] = clu->Size(); size[1] = 2; PyArrayObject * clusterInstance = (PyArrayObject*)PyArray_SimpleNew(2,size,NPY_INT); size[0] = from->behCount; PyArrayObject * behMultinomial = (PyArrayObject*)PyArray_SimpleNew(1,size,NPY_FLOAT); size[0] = from->flagSets->dimensions[0]; PyArrayObject * behPriorMulti = (PyArrayObject*)PyArray_SimpleNew(1,size,NPY_INT); PyTuple_SetItem(tup, 0, (PyObject*)clusterInstance); PyTuple_SetItem(tup, 1, PyFloat_FromDouble(clu->Body().conc)); PyTuple_SetItem(tup, 2, (PyObject*)behMultinomial); PyTuple_SetItem(tup, 3, (PyObject*)behPriorMulti); ItemRef<ClusterInst,Conc> * cluInst = clu->First(); for (int ci=0;ci<clu->Size();ci++) { cluInst->id = ci; if (cluInst->GetTopic()) Int2D(clusterInstance,ci,0) = cluInst->GetTopic()->id; else Int2D(clusterInstance,ci,0) = -1; Int2D(clusterInstance,ci,1) = cluInst->RefCount(); cluInst = cluInst->Next(); } for (int b=0;b<from->behCount;b++) { Float1D(behMultinomial,b) = clu->GetBMN()[b]; } if (clu->GetBehCountPrior()) // Easier to introduce it here - lets the rest of the code be null pointer safe as I made it that due to incrimental implimentation anyway. { for (int fs=0;fs<from->flagSets->dimensions[0];fs++) { Int1D(behPriorMulti,fs) = clu->GetBehCountPrior()[fs]; } } else { for (int fs=0;fs<from->flagSets->dimensions[0];fs++) { Int1D(behPriorMulti,fs) = 0; } } Int1D(clusterUse,c) = clu->RefCount(); clu = clu->Next(); } } PyObject_SetAttrString(to,"clusterUse",(PyObject*)clusterUse); PyObject_SetAttrString(to,"cluster",cluster); Py_DECREF(clusterUse); Py_DECREF(cluster); PyObject * clusterConc = PyFloat_FromDouble(from->clusters.Body().conc); PyObject_SetAttrString(to,"clusterConc",clusterConc); Py_DECREF(clusterConc); // Update the documents information - keep it simple by just overwriting cluster and sample assignments whilst replacing the per-document DP... PyObject * docList = PyObject_GetAttrString(to,"doc"); for (int d=0;d<from->docCount;d++) { Document & fromDoc = from->doc[d]; PyObject * toDoc = PyList_GetItem(docList,d); // Set cluster... int clusterID = -1; if (fromDoc.GetCluster()) clusterID = fromDoc.GetCluster()->id; PyObject * cluID = PyInt_FromLong(clusterID); PyObject_SetAttrString(toDoc,"cluster",cluID); Py_DECREF(cluID); // Replace DP... size[0] = fromDoc.Size(); size[1] = 3; PyArrayObject * use = (PyArrayObject*)PyArray_SimpleNew(2,size,NPY_INT); ItemRef<DocInst,Conc> * docInst = fromDoc.First(); for (int di=0;di<size[0];di++) { docInst->id = di; if (docInst->GetClusterInst()) { Int2D(use,di,0) = docInst->GetClusterInst()->GetTopic()->beh; Int2D(use,di,1) = docInst->GetClusterInst()->id; } else { Int2D(use,di,0) = -1; Int2D(use,di,1) = -1; } Int2D(use,di,2) = docInst->RefCount(); docInst = docInst->Next(); } PyObject_SetAttrString(toDoc,"use",(PyObject*)use); Py_DECREF(use); PyObject * conc = PyFloat_FromDouble(fromDoc.Body().conc); PyObject_SetAttrString(toDoc,"conc",conc); Py_DECREF(conc); // Update samples DP assignments... { PyArrayObject * samples = (PyArrayObject*)PyObject_GetAttrString(toDoc,"samples"); for (int s=0;s<fromDoc.SampleCount();s++) { Sample & sam = fromDoc.GetSample(s); if (sam.GetDocInst()) Int2D(samples,s,0) = sam.GetDocInst()->id; else Int2D(samples,s,0) = -1; } Py_DECREF(samples); } // Update behaviour counts... { PyArrayObject * behCounts = (PyArrayObject*)PyObject_GetAttrString(toDoc,"behCounts"); for (int b=0;b<from->behCount;b++) { Int1D(behCounts,b) = fromDoc.GetBehCounts()[b]; } Py_DECREF(behCounts); } } Py_DECREF(docList); } """ class TestDSLink(unittest.TestCase): """Test code for the data structure.""" def test_compile(self): code = start_cpp(dual_hdp_ds_link) + """ """ weave.inline(code, support_code=dual_hdp_ds_link) # If this file is run do the unit tests... if __name__ == '__main__': unittest.main()
[ [ 1, 0, 0.0285, 0.0016, 0, 0.66, 0, 265, 0, 1, 0, 0, 265, 0, 0 ], [ 1, 0, 0.0301, 0.0016, 0, 0.66, 0.1667, 88, 0, 1, 0, 0, 88, 0, 0 ], [ 1, 0, 0.0316, 0.0016, 0, 0....
[ "from scipy import weave", "import unittest", "from utils.start_cpp import start_cpp", "from ds_cpp import ds_code", "ds_link_code = ds_code + start_cpp() + \"\"\"\n\n// Helper for extracting a boolean from a Python object...\nbool GetObjectBool(PyObject * obj, const char * name)\n{\n PyObject * boolObj = P...
# Copyright 2011 Tom SF Haines # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Loads solvers.... # Load the most basic solver, but also load a mp one if possible... try: from solve_weave import gibbs_all, gibbs_doc, leftRightNegLogProbWord __fitter = 'weave' except: raise Exception('Could not load basic weave solver') try: from solve_weave_mp import gibbs_all_mp, gibbs_doc_mp __fitter = 'multiprocess weave' except: pass # Function to get the best fitter avaliable... def getAlgorithm(): """Returns a text string indicating which implimentation of the fitting algorithm is being used by default, which will be the best avaliable.""" global __fitter return __fitter
[ [ 7, 0, 0.5897, 0.1282, 0, 0.66, 0, 0, 0, 1, 0, 0, 0, 0, 1 ], [ 1, 1, 0.5641, 0.0256, 1, 0.94, 0, 97, 0, 3, 0, 0, 97, 0, 0 ], [ 14, 1, 0.5897, 0.0256, 1, 0.94, ...
[ "try:\n from solve_weave import gibbs_all, gibbs_doc, leftRightNegLogProbWord\n __fitter = 'weave'\nexcept:\n raise Exception('Could not load basic weave solver')", " from solve_weave import gibbs_all, gibbs_doc, leftRightNegLogProbWord", " __fitter = 'weave'", "try:\n from solve_weave_mp import gibbs_a...
# Copyright 2011 Tom SF Haines # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import math import numpy from dp_conc import PriorConcDP from params import Params from smp.smp import FlagIndexArray class DocState: """Helper class to contain the State of Gibbs sampling for a specific document.""" def __init__(self, doc, alphaConc = None, abnormDict = None): if isinstance(doc, DocState): self.cluster = doc.cluster self.use = doc.use.copy() self.conc = doc.conc self.samples = doc.samples.copy() self.behFlags = doc.behFlags.copy() self.behFlagsIndex = doc.behFlagsIndex self.behCounts = doc.behCounts.copy() self.ident = doc.ident else: # Index of the cluster its assigned to, initialised to -1 to indicate it is not currently assigned... self.cluster = -1 # Definition of the documents DP, initialised to be empty, which contains instances of cluster instances. The use array is, as typical, indexed by instance in the first dimension and {0,1,2} in the second, where 0 gives the behaviour, 1 the index of the cluster instance it is instancing and 2 gives the number of users, which at this level will be the number of words. conc provides a sample of the concentration value for the DP... self.use = numpy.empty((0,3), dtype=numpy.int32) self.conc = alphaConc.conc # Contains the documents samples - a 2D array where the first dimension indexes each sample. There are then two columns - the first contains the instance index, which indexes the use array, and the second the word index, which indexes the multinomial assigned to each topic. We default to -1 in the instance index column to indicate that it is unassigned... self.samples = numpy.empty((doc.getSampleCount(),2), dtype=numpy.int32) self.samples[:,0] = -1 si = 0 for word, count in map(lambda i: doc.getWord(i), xrange(doc.getWordCount())): for _ in xrange(count): self.samples[si,1] = word si += 1 assert(si==doc.getSampleCount()) # Create the documents behaviour flags, which are an array of {0,1} values indicating if the given behaviour is in the document or not - entry 0 is reserved for normal behaviour, whilst the rest are reserved for abnormalities... self.behFlags = numpy.zeros(1+len(abnormDict), dtype=numpy.uint8) self.behFlags[0] = 1 # Normal behaviour always exists. for abnorm in doc.getAbnorms(): self.behFlags[abnormDict[abnorm]] = 1 # Index associated with the above behFlags - set on initialisation to match the corpus's FlagIndexArray... self.behFlagsIndex = -1 # We also need the behaviour counts - how many samples have been assigned to each behaviour... self.behCounts = numpy.zeros(1+len(abnormDict), dtype=numpy.int32) self.ident = doc.getIdent() class State: """State object, as manipulated by a Gibbs sampler to get samples of the unknown parameters of the model.""" def __init__(self, obj, params = None): """Constructs a state object given either another State object (clone), or a Corpus and a Params object. If the Params object is omitted it uses the default. Also supports construction from a single Document, where it uses lots of defaults but is basically identical to a Corpus with a single Document in - used as a shortcut when fitting a Document to an already learnt model.""" if isinstance(obj, State): # Cloning time... self.dnrDocInsts = obj.dnrDocInsts self.dnrCluInsts = obj.dnrCluInsts self.seperateClusterConc = obj.seperateClusterConc self.seperateDocumentConc = obj.seperateDocumentConc self.oneCluster = obj.oneCluster self.calcBeta = obj.calcBeta self.calcCluBmn = obj.calcCluBmn self.calcPhi = obj.calcPhi self.resampleConcs = obj.resampleConcs self.behSamples = obj.behSamples self.alpha = PriorConcDP(obj.alpha) self.beta = obj.beta.copy() self.gamma = PriorConcDP(obj.gamma) self.rho = PriorConcDP(obj.rho) self.mu = PriorConcDP(obj.mu) self.phi = obj.phi.copy() self.topicWord = obj.topicWord.copy() self.topicUse = obj.topicUse.copy() self.topicConc = obj.topicConc self.abnormTopicWord = obj.abnormTopicWord.copy() self.cluster = map(lambda t: (t[0].copy(),t[1],t[2].copy()),obj.cluster) self.clusterUse = obj.clusterUse.copy() self.clusterConc = obj.clusterConc self.doc = map(lambda d: DocState(d), obj.doc) self.abnorms = dict(obj.abnorms) self.fia = FlagIndexArray(obj.fia) self.params = Params(obj.params) self.model = Model(obj.model) elif isinstance(obj, Document): # Construct from a single document... self.dnrDocInsts = False self.dnrCluInsts = False self.seperateClusterConc = False self.seperateDocumentConc = False self.oneCluster = False self.calcBeta = False self.calcCluBmn = False self.calcPhi = False self.resampleConcs = False self.behSamples = 1024 wordCount = obj.getWord(obj.getWordCount()-1)[0] self.alpha = PriorConcDP() self.beta = numpy.ones(wordCount, dtype=numpy.float32) self.gamma = PriorConcDP() self.rho = PriorConcDP() self.mu = PriorConcDP() self.phi = numpy.ones(1+len(obj.getAbnorms()), dtype=numpy.float32) self.phi[0] *= 10.0 self.phi /= self.phi.sum() self.topicWord = numpy.zeros((0,wordCount), dtype=numpy.int32) self.topicUse = numpy.zeros(0,dtype=numpy.int32) self.topicConc = self.gamma.conc self.abnormTopicWord = numpy.zeros((1+len(obj.getAbnorms()), wordCount), dtype=numpy.int32) self.cluster = [] self.clusterUse = numpy.zeros(0,dtype=numpy.int32) self.clusterConc = self.mu.conc abnormDict = dict() for i, abnorm in enumerate(obj.getAbnorms()): abnormDict[abnorm] = i+1 self.doc = [DocState(obj,self.alpha,abnormDict)] self.abnorms = dict() for num, abnorm in enumerate(obj.getAbnorms()): self.abnorms[abnorm] = num+1 self.fia = FlagIndexArray(len(self.abnorms)+1) self.fia.addSingles() for doc in self.doc: doc.behFlagsIndex = self.fia.flagIndex(doc.behFlags) if params!=None: self.params = params else: self.params = Params() self.model = Model() else: # Construct from a corpus, as that is the only remaining option... # Behaviour flags... self.dnrDocInsts = obj.getDocInstsDNR() self.dnrCluInsts = obj.getCluInstsDNR() self.seperateClusterConc = obj.getSeperateClusterConc() self.seperateDocumentConc = obj.getSeperateDocumentConc() self.oneCluster = obj.getOneCluster() self.calcBeta = obj.getCalcBeta() self.calcCluBmn = obj.getCalcClusterBMN() self.calcPhi = obj.getCalcPhi() self.resampleConcs = obj.getResampleConcs() self.behSamples = obj.getBehSamples() # Concentration parameters - these are all constant... self.alpha = PriorConcDP(obj.getAlpha()) self.beta = numpy.ones(obj.getWordCount(),dtype=numpy.float32) self.beta *= obj.getBeta() self.gamma = PriorConcDP(obj.getGamma()) self.rho = PriorConcDP(obj.getRho()) self.mu = PriorConcDP(obj.getMu()) self.phi = numpy.ones(1+len(obj.getAbnormDict()), dtype=numpy.float32) self.phi[0] *= obj.getPhiRatio() self.phi *= obj.getPhiConc()*self.phi.shape[0] / self.phi.sum() # The topics in the model - consists of three parts - first an array indexed by [topic,word] which gives how many times each word has been drawn from the given topic - this alongside beta allows the relevant Dirichlet posterior to be determined. Additionally we have topicUse, which counts how many times each topic has been instanced in a cluster - this alongside topicConc, which is the sampled concentration, defines the DP from which topics are drawn for inclusion in clusters... self.topicWord = numpy.zeros((0,obj.getWordCount()),dtype=numpy.int32) self.topicUse = numpy.zeros(0,dtype=numpy.int32) self.topicConc = self.gamma.conc # A second topicWord-style matrix, indexed by behaviour and containing the abnormal topics. Entry 0, which is normal, is again an empty dummy... self.abnormTopicWord = numpy.zeros((1+len(obj.getAbnormDict()), obj.getWordCount()), dtype=numpy.int32) # Defines the clusters, as a list of (inst, conc, bmn, bmnPrior). inst is a 2D array, containing all the topic instances that make up the cluster - whilst the first dimension of the array indexes each instance the second has two entrys only, the first the index number for the topic, the second the number of using document instances. conc is the sampled concentration that completes the definition of the DP defined for each cluster. bmn is the multinomial on behaviours associated with the cluster - a 1D array of floats. bmnPrior is the flagSet aligned integer array that is the prior on bmn. Additionally we have the DDP from which the specific clusters are drawn - this is defined by clusterUse and clusterConc, just as for the topics... self.cluster = [] self.clusterUse = numpy.zeros(0, dtype=numpy.int32) self.clusterConc = self.mu.conc # List of document objects, to contain the documents - whilst declared immediatly below as an empty list we then proceed to fill it in with the information from the given Corpus... self.doc = [] for doc in obj.documentList(): self.doc.append(DocState(doc, self.alpha, obj.getAbnormDict())) # The abnormality dictionary - need a copy so we can convert from flags to the user provided codes after fitting the model... self.abnorms = dict(obj.getAbnormDict()) # The flag index array - converts each flag combination to an index - required for learning the per-cluster behaviour multinomials... self.fia = FlagIndexArray(len(self.abnorms)+1) self.fia.addSingles() for doc in self.doc: doc.behFlagsIndex = self.fia.flagIndex(doc.behFlags) # Store the parameters... if params!=None: self.params = params else: self.params = Params() # Create a model object, for storing samples into... self.model = Model() def setGlobalParams(self, sample): """Sets a number of parameters for the State after initialisation, taking them from the given Sample object. Designed for use with the addPrior method this allows you to extract all relevant parameters from a Sample. Must be called before any Gibbs sampling takes place.""" self.alpha = PriorConcDP(sample.alpha) self.beta = sample.beta.copy() self.gamma = PriorConcDP(sample.gamma) self.rho = PriorConcDP(sample.rho) self.mu = PriorConcDP(sample.mu) # No correct way of combining - the below seems reasonable enough however, and is correct if they have the same entrys... for key,fromIndex in sample.abnorms.iteritems(): if key in self.abnorms: toIndex = self.abnorms[key] self.phi[toIndex] = sample.phi[fromIndex] self.phi /= self.phi.sum() self.topicConc = sample.topicConc self.clusterConc = sample.clusterConc for doc in self.doc: doc.conc = self.alpha.conc def addPrior(self, sample): """Given a Sample object this uses it as a prior - this is primarilly used to sample a single or small number of documents using a model already trainned on another set of documents. It basically works by adding the topics, clusters and behaviours from the sample into this corpus, with the counts all intact so they have the relevant weight and can't be deleted. Note that you could in principle add multiple priors, though that would be quite a strange scenario. If only called once then the topic indices will line up. Note that all the prior parameters are not transfered, though often you would want to - setGlobalParams is provided to do this. Must be called before any Gibbs sampling takes place.""" # Below code has evolved into spagetti, via several other tasty culinary dishes, and needs a rewrite. Or to never be looked at or edited ever again. ################### # Do the topics... offset = self.topicWord.shape[0] if self.topicWord.shape[0]!=0: self.topicWord = numpy.vstack((self.topicWord,sample.topicWord)) else: self.topicWord = sample.topicWord.copy() self.topicUse = numpy.hstack((self.topicUse,sample.topicUse)) # Calculate the new abnormalities dictionary... newAbnorms = dict(sample.abnorms) for key,_ in self.abnorms.iteritems(): if key not in newAbnorms: val = len(newAbnorms)+1 newAbnorms[key] = val # Transfer over the abnormal word counts... newAbnormTopicWord = numpy.zeros((1+len(newAbnorms), max((self.abnormTopicWord.shape[1], sample.abnormTopicWord.shape[1]))), dtype=numpy.int32) for abnorm,origin in self.abnorms.iteritems(): dest = newAbnorms[abnorm] limit = self.abnormTopicWord.shape[1] newAbnormTopicWord[dest,:limit] += self.abnormTopicWord[origin,:limit] for abnorm,origin in sample.abnorms.iteritems(): dest = newAbnorms[abnorm] limit = sample.abnormTopicWord.shape[1] newAbnormTopicWord[dest,:limit] += sample.abnormTopicWord[origin,:limit] # Update the document flags/counts for behaviours... for doc in self.doc: newFlags = numpy.zeros(1+len(newAbnorms), dtype=numpy.uint8) newCounts = numpy.zeros(1+len(newAbnorms), dtype=numpy.int32) newFlags[0] = doc.behFlags[0] newCounts[0] = doc.behCounts[0] for abnorm,origin in self.abnorms.iteritems(): dest = newAbnorms[abnorm] newFlags[dest] = doc.behFlags[origin] newCounts[dest] = doc.behCounts[origin] doc.behFlags = newFlags doc.behCounts = newCounts # Update the old clusters behaviour arrays... def mapOldCluster(c): c2 = numpy.ones(1+len(newAbnorms), dtype=numpy.float32) c2 /= c2.sum() c2[0] *= c[2][0] for abnorm,origin in self.abnorms.iteritems(): dest = newAbnorms[abnorm] c2[dest] *= c[2][origin] c2 /= c2.sum() return (c[0],c[1],c2,c[3]) self.cluster = map(mapOldCluster ,self.cluster) origCluCount = len(self.cluster) # Add the new clusters, updating their behaviour arrays and topic indices, plus getting their priors updated with their associated documents... def mapCluster(pair): ci, c = pair c0 = c[0].copy() c0[:,0] += offset c2 = numpy.ones(1+len(newAbnorms), dtype=numpy.float32) c2 /= c2.sum() c2[0] *= c[2][0] for abnorm,origin in sample.abnorms.iteritems(): dest = newAbnorms[abnorm] c2[dest] *= c[2][origin] c2 /= c2.sum() c3 = c[3].copy() for doc in filter(lambda doc: doc.cluster==ci, sample.doc): fi = sample.fia.flagIndex(doc.behFlags, False) if fi>=len(doc.behFlags): # Only bother if the document has abnormalities, of which this is a valid test. total = 0 for i in xrange(doc.dp.shape[0]): c3[doc.dp[i,0]] += doc.dp[i,2] total += doc.dp[i,2] c3[fi] -= total + 1 return (c0,c[1],c2,c3) self.cluster += map(mapCluster, enumerate(sample.cluster)) self.clusterUse = numpy.hstack((self.clusterUse, sample.clusterUse)) # Update phi... newPhi = numpy.ones(len(newAbnorms)+1,dtype=numpy.float32) newPhi[0] = 0.5*(self.phi[0]+sample.phi[0]) for abnorm,origin in self.abnorms.iteritems(): dest = newAbnorms[abnorm] newPhi[dest] = self.phi[origin] for abnorm,origin in sample.abnorms.iteritems(): dest = newAbnorms[abnorm] if abnorm not in self.abnorms: newPhi[dest] = sample.phi[origin] else: newPhi[dest] = 0.5*(newPhi[dest] + sample.phi[origin]) self.phi = newPhi self.phi /= self.phi.sum() # Recreate the flag index array... remapOrig = dict() # Old flag positions to new flag positions. remapOrig[0] = 0 for abnorm,origin in self.abnorms.iteritems(): remapOrig[origin] = newAbnorms[abnorm] remapSam = dict() # sample flag positions to new flag positions. remapSam[0] = 0 for abnorm,origin in sample.abnorms.iteritems(): remapSam[origin] = newAbnorms[abnorm] newFia = FlagIndexArray(len(newAbnorms)+1) newFia.addSingles() behIndAdjOrig = newFia.addFlagIndexArray(self.fia,remapOrig) behIndAdjSam = newFia.addFlagIndexArray(sample.fia,remapSam) for doc in self.doc: doc.behFlagsIndex = behIndAdjOrig[doc.behFlagsIndex] # Update cluster priors on bmn arrays... for c in xrange(len(self.cluster)): clu = self.cluster[c] newBmn = numpy.zeros(newFia.flagCount(),dtype=numpy.int32) oldBmn = clu[3].copy() # Transilate from old set... for b in xrange(oldBmn.shape[0]): index = behIndAdjOrig[b] if c<origCluCount else behIndAdjSam[b] newBmn[index] += oldBmn[b] self.cluster[c] = (clu[0], clu[1], clu[2], newBmn) # Replace the old abnormality and fia stuff... self.abnormTopicWord = newAbnormTopicWord self.abnorms = newAbnorms self.fia = newFia def sample(self): """Samples the current state, storing the current estimate of the model parameters.""" self.model.sampleState(self) def absorbClone(self,clone): """Given a clone absorb all its samples - used for multiprocessing.""" self.model.absorbModel(clone.model) def getParams(self): """Returns the parameters object.""" return self.params def getModel(self): """Returns the model constructed from all the calls to sample().""" return self.model # Includes at tail of file to resolve circular dependencies... from document import Document from model import Model
[ [ 1, 0, 0.0425, 0.0024, 0, 0.66, 0, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 1, 0, 0.0448, 0.0024, 0, 0.66, 0.125, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0495, 0.0024, 0, 0...
[ "import math", "import numpy", "from dp_conc import PriorConcDP", "from params import Params", "from smp.smp import FlagIndexArray", "class DocState:\n \"\"\"Helper class to contain the State of Gibbs sampling for a specific document.\"\"\"\n def __init__(self, doc, alphaConc = None, abnormDict = None):...
# Copyright 2011 Tom SF Haines # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # This loads in the entire library and provides the interface - only import needed by a user... # Load in the solvers (Done fist to avoid include loop issues.)... from solvers import * # Load in all the data structure types... from params import Params from solve_shared import State from model import Model, Sample, DocSample, DocModel from dp_conc import PriorConcDP from corpus import Corpus from document import Document
[ [ 1, 0, 0.7241, 0.0345, 0, 0.66, 0, 305, 0, 1, 0, 0, 305, 0, 0 ], [ 1, 0, 0.8276, 0.0345, 0, 0.66, 0.1667, 206, 0, 1, 0, 0, 206, 0, 0 ], [ 1, 0, 0.8621, 0.0345, 0, ...
[ "from solvers import *", "from params import Params", "from solve_shared import State", "from model import Model, Sample, DocSample, DocModel", "from dp_conc import PriorConcDP", "from corpus import Corpus", "from document import Document" ]
# Copyright 2011 Tom SF Haines # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import math import numpy import scipy.special import collections import solvers from smp.smp import FlagIndexArray from utils.mp_map import * class DocSample: """Stores the sample information for a given document - the DP from which topics are drawn and which cluster it is a member of. Also calculates and stores the negative log liklihood of the document.""" def __init__(self, doc): """Given the specific DocState object this copies the relevant information. Note that it doesn't calculate the nll - another method will do that. It also supports cloning.""" if isinstance(doc, DocSample): # Code for clonning self.cluster = doc.cluster self.dp = doc.dp.copy() self.conc = doc.conc self.samples = doc.samples.copy() self.behFlags = doc.behFlags.copy() self.nll = doc.nll self.ident = doc.ident else: # Extract the model information... self.cluster = doc.cluster self.dp = doc.use.copy() self.conc = doc.conc self.samples = doc.samples.copy() self.behFlags = doc.behFlags.copy() self.nll = 0.0 self.ident = doc.ident def calcNLL(self, doc, state): """Calculates the negative log likelihood of the document, given the relevant information. This is the DocState object again, but this time with the entire state object as well. Probability (Expressed as negative log likelihood.) is specificly calculated using all terms that contain a variable in the document, but none that would be identical for all documents. That is, it contains the probability of the cluster, the probability of the dp given the cluster, and the probability of the samples, which factors in both the drawing of the topic and the drawing of the word. The ordering of the samples is considered irrelevant, with both the topic and word defining uniqueness. Some subtle approximation is made - see if you can spot it in the code!""" self.nll = 0.0 # Probability of drawing the cluster... self.nll -= math.log(state.clusterUse[doc.cluster]) self.nll += math.log(state.clusterUse.sum()+state.clusterConc) # Probability of drawing the documents dp from its cluster, taking into account the abnormal entrys... cl = state.cluster[doc.cluster] logBMN = numpy.log(cl[2] / (cl[2]*numpy.asfarray(doc.behFlags)).sum()) behInstCounts = numpy.zeros(doc.behFlags.shape[0], dtype=numpy.int32) instCounts = numpy.zeros(cl[0].shape[0], dtype=numpy.int32) for ii in xrange(doc.use.shape[0]): behInstCounts[doc.use[ii,0]] += 1 if doc.use[ii,0]==0: instCounts[doc.use[ii,1]] += 1 self.nll -= (logBMN * behInstCounts).sum() self.nll -= scipy.special.gammaln(behInstCounts.sum() + 1.0) self.nll += scipy.special.gammaln(behInstCounts + 1.0).sum() norm = cl[0][:,1].sum() + cl[1] self.nll -= (numpy.log(numpy.asfarray(cl[0][:,1])/norm)*instCounts).sum() self.nll -= scipy.special.gammaln(instCounts.sum() + 1.0) # Cancels with a term from the above - can optimise, but would rather have neat code. self.nll += scipy.special.gammaln(instCounts + 1.0).sum() # Count the numbers of word/topic instance pairs in the data structure - sum using a dictionary... samp_count = collections.defaultdict(int) # [instance,word] for s in xrange(doc.samples.shape[0]): samp_count[doc.samples[s,0],doc.samples[s,1]] += 1 # Calculate the probability distribution of drawing each topic instance and the probability of drawing each word/topic assignment... inst = numpy.asfarray(doc.use[:,2]) inst /= inst.sum() + doc.conc topicWord = numpy.asfarray(state.topicWord) + state.beta topicWord = (topicWord.T/topicWord.sum(axis=1)).T abnormTopicWord = numpy.asfarray(state.abnormTopicWord) + state.beta abnormTopicWord = (abnormTopicWord.T/abnormTopicWord.sum(axis=1)).T instLog = numpy.log(inst) wordLog = numpy.log(topicWord) abnormLog = numpy.log(abnormTopicWord) # Now sum into nll the probability of drawing the samples that have been drawn - gets a tad complex as includes the probability of drawing the topic from the documents dp and then the probability of drawing the word from the topic, except I've merged them such that it doesn't look like that is what is happening... self.nll -= scipy.special.gammaln(doc.samples.shape[0]+1.0) for pair, count in samp_count.iteritems(): inst, word = pair beh = doc.use[inst,0] if beh==0: topic = cl[0][doc.use[inst,1],0] self.nll -= count * (wordLog[topic,word] + instLog[inst]) else: self.nll -= count * (abnormLog[beh,word] + instLog[inst]) self.nll += scipy.special.gammaln(count+1.0) def getCluster(self): """Returns the sampled cluster assignment.""" return self.cluster def getInstCount(self): """Returns the number of cluster instances in the documents model.""" return self.dp.shape[0] def getInstBeh(self, i): """Returns the behaviour index for the given instance.""" return self.dp[i,0] def getInstTopic(self, i): """Returns the topic index for the given instance.""" return self.dp[i,1] def getInstWeight(self, i): """Returns the number of samples that have been assigned to the given topic instance.""" return self.dp[i,2] def getInstAll(self): """Returns a 2D numpy array of integers where the first dimension indexes the topic instances for the document and the the second dimension has three entries, the first (0) the behaviour index, the second (1) the topic index and the third (2) the number of samples assigned to the given topic instance. Do not edit the return value for this method - copy it first.""" return self.dp def getInstConc(self): """Returns the sampled concentration parameter.""" return self.conc def getBehFlags(self): """Returns the behavioural flags - a 1D array of {0,1} as type unsigned char where 1 indicates that it has the behaviour with that index, 0 that it does not. Entry 0 will map to normal behaviour, and will always be 1. Do not edit - copy first.""" return self.behFlags def getNLL(self): """Returns the negative log liklihood of the document given the model.""" return self.nll def getIdent(self): """Returns the ident of the document, as passed through from the input document so they may be matched up.""" return self.ident class Sample: """Stores a single sample drawn from the model - the topics, clusters and each document being sampled over. Stores counts and parameters required to make them into distributions, rather than final distributions. Has clonning capability.""" def __init__(self, state, calcNLL = True, priorsOnly = False): """Given a state this draws a sample from it, as a specific parametrisation of the model. Also a copy constructor, with a slight modification - if the priorsOnly flag is set it will only copy across the priors, and initialise to an empty model.""" if isinstance(state, Sample): # Code for clonning. self.alpha = state.alpha self.beta = state.beta.copy() self.gamma = state.gamma self.rho = state.rho self.mu = state.mu self.phi = state.phi.copy() if not priorsOnly: self.topicWord = state.topicWord.copy() self.topicUse = state.topicUse.copy() else: self.topicWord = numpy.zeros((0,state.topicWord.shape[1]), dtype=numpy.int32) self.topicUse = numpy.zeros(0,dtype=numpy.int32) self.topicConc = state.topicConc self.abnormTopicWord = state.abnormTopicWord.copy() self.abnorms = dict(state.abnorms) self.fia = FlagIndexArray(state.fia) if not priorsOnly: self.cluster = map(lambda t: (t[0].copy(),t[1],t[2].copy(),t[3].copy()), state.cluster) self.clusterUse = state.clusterUse.copy() else: self.cluster = [] self.clusterUse = numpy.zeros(0,dtype=numpy.int32) self.clusterConc = state.clusterConc if not priorsOnly: self.doc = map(lambda ds: DocSample(ds), state.doc) else: self.doc = [] else: # Normal initialisation code. self.alpha = state.alpha self.beta = state.beta.copy() self.gamma = state.gamma self.rho = state.rho self.mu = state.mu self.phi = state.phi.copy() # Topic stuff... self.topicWord = state.topicWord.copy() self.topicUse = state.topicUse.copy() self.topicConc = state.topicConc # Abnormality stuff... self.abnormTopicWord = state.abnormTopicWord.copy() self.abnorms = dict(state.abnorms) self.fia = FlagIndexArray(state.fia) # Cluster stuff... self.cluster = map(lambda t: (t[0].copy(),t[1],t[2].copy(),t[3].copy()), state.cluster) self.clusterUse = state.clusterUse.copy() self.clusterConc = state.clusterConc # The details for each document... self.doc = [] for d in xrange(len(state.doc)): self.doc.append(DocSample(state.doc[d])) # Second pass through documents to fill in the negative log liklihoods - need some data structures for this... if calcNLL: for d in xrange(len(state.doc)): self.doc[d].calcNLL(state.doc[d],state) def merge(self, other): """Given a sample this merges it into this sample. Works under the assumption that the new sample was learnt with this sample as its only prior, and ends up as though both the prior and the sample were drawn whilst simultaneously being modeled. Trashes the given sample - do not continue to use.""" # Update the old documents - there are potentially more behaviours in the new sample, which means adjusting the behaviour flags... if self.fia.getLength()!=other.fia.getLength(): for doc in self.doc: newBehFlags = numpy.zeros(other.fia.getLength(), dtype=numpy.uint8) newBehFlags[0] = doc.behFlags[0] for abnorm, index in self.abnorms: newIndex = other.abnorms[abnorm] newBehFlags[newIndex] = doc.behFlags[index] doc.behFlags = newBehFlags # Replace the basic parameters... self.alpha = other.alpha self.beta = other.beta self.gamma = other.gamma self.rho = other.rho self.mu = other.mu self.phi = other.phi self.topicWord = other.topicWord self.topicUse = other.topicUse self.topicConc = other.topicConc self.abnormTopicWord = other.abnormTopicWord self.abnorms = other.abnorms self.fia = other.fia self.cluster = other.cluster self.clusterUse = other.clusterUse self.clusterConc = other.clusterConc # Add in the (presumably) new documents... for doc in other.doc: self.doc.append(doc) def getAlphaPrior(self): """Returns the PriorConcDP that was used for the alpha parameter, which is the concentration parameter for the DP in each document.""" return self.alpha def getBeta(self): """Returns the beta prior, which is a vector representing a Dirichlet distribution from which the multinomials for each topic are drawn, from which words are drawn.""" return self.beta def getGammaPrior(self): """Returns the PriorConcDP that was used for the gamma parameter, which is the concentration parameter for the global DP from which topics are drawn.""" return self.gamma def getRhoPrior(self): """Returns the PriorConcDP that was used for the rho parameter, which is the concentration parameter for each specific clusters DP.""" return self.rho def getMuPrior(self): """Returns the PriorConcDP that was used for the mu parameter, which is the concentration parameter for the DP from which clusters are drawn.""" return self.mu def getPhi(self): """Returns the phi Dirichlet distribution prior on the behavioural multinomial for each cluster.""" return self.phi def getTopicCount(self): """Returns the number of topics in the sample.""" return self.topicWord.shape[0] def getWordCount(self): """Returns the number of words in the topic multinomial.""" return self.topicWord.shape[1] def getTopicUseWeight(self, t): """Returns how many times the given topic has been instanced in a cluster.""" return self.topicUse[t] def getTopicUseWeights(self): """Returns an array, indexed by topic id, that contains how many times each topic has been instanciated in a cluster. Do not edit the return value - copy it first.""" return self.topicUse def getTopicConc(self): """Returns the sampled concentration parameter for drawing topic instances from the global DP.""" return self.topicConc def getTopicWordCount(self, t): """Returns the number of samples assigned to each word for the given topic, as an integer numpy array. Do not edit the return value - make a copy first.""" return self.topicWord[t,:] def getTopicWordCounts(self, t): """Returns the number of samples assigned to each word for all topics, indexed [topic, word], as an integer numpy array. Do not edit the return value - make a copy first.""" return self.topicWord def getTopicMultinomial(self, t): """Returns the calculated multinomial for a given topic ident.""" ret = self.beta.copy() ret += self.topicWord[t,:] ret /= ret.sum() return ret def getTopicMultinomials(self): """Returns the multinomials for all topics, in a single array - indexed by [topic, word] to give P(word|topic).""" ret = numpy.vstack([self.beta]*self.topicWord.shape[0]) ret += self.topicWord ret = (ret.T / ret.sum(axis=1)).T return ret def getBehCount(self): """Returns the number of behaviours, which is the number of abnormalities plus 1, and the entry count for the indexing variable for abnormals in the relevant methods.""" return self.abnormTopicWord.shape[0] def getAbnormWordCount(self, b): """Returns the number of samples assigned to each word for the given abnormal topic. Note that entry 0 equates to normal behaviour and is a dummy that should be ignored.""" return self.abnormTopicWord[b,:] def getAbnormWordCounts(self): """Returns the number of samples assigned to each word in each abnormal behaviour. An integer 2D array indexed with [behaviour, word], noting that behaviour 0 is a dummy for normal behaviour. Do not edit the return value - make a copy first.""" return self.abnormTopicWord def getAbnormMultinomial(self, b): """Returns the calculated multinomial for a given abnormal behaviour.""" ret = self.beta.copy() ret += self.abnormTopicWord[b,:] ret /= ret.sum() return ret def getAbnormMultinomials(self): """Returns the multinomials for all abnormalities, in a single array - indexed by [behaviour, word] to give P(word|topic associated with behaviour). Entry 0 is a dummy to fill in for normal behaviour, and should be ignored.""" ret = numpy.vstack([self.beta]*self.abnormTopicWord.shape[0]) ret += self.abnormTopicWord ret = (ret.T / ret.sum(axis=1)).T return ret def getAbnormDict(self): """Returns a dictionary that takes each abnormalities user provided token to the behaviour index used for it. Allows the use of the getAbnorm* methods, amung other things.""" return self.abnorms def getClusterCount(self): """Returns how many clusters there are.""" return len(self.cluster) def getClusterDrawWeight(self, c): """Returns how many times the given cluster has been instanced by a document.""" return self.clusterUse[c] def getClusterDrawWeights(self): """Returns an array, indexed by cluster id, that contains how many times each cluster has been instanciated by a document. Do not edit the return value - copy it first.""" return self.clusterUse def getClusterDrawConc(self): """Returns the sampled concentration parameter for drawing cluster instances for documents.""" return self.clusterConc def getClusterInstCount(self, c): """Returns how many instances of topics exist in the given cluster.""" return self.cluster[c][0].shape[0] def getClusterInstWeight(self, c, ti): """Returns how many times the given cluster topic instance has been instanced by a documents DP.""" return self.cluster[c][0][ti,1] def getClusterInstTopic(self, c, ti): """Returns which topic the given cluster topic instance is an instance of.""" return self.cluster[c][0][ti,0] def getClusterInstDual(self, c): """Returns a 2D array, where the first dimension is indexed by the topic instance, and the second contains two columns - the first the topic index, the second the weight. Do not edit return value - copy before use.""" return self.cluster[c][0] def getClusterInstConc(self, c): """Returns the sampled concentration that goes with the DP from which the members of each documents DP are drawn.""" return self.cluster[c][1] def getClusterInstBehMN(self, c): """Returns the multinomial on drawing behaviours for the given cluster.""" return self.cluster[c][2] def getClusterInstPriorBehMN(self, c): """Returns the prior on the behaviour multinomial, as an array of integer counts aligned with the flag set.""" return self.cluster[c][3] def docCount(self): """Returns the number of documents stored within. Should be the same as the corpus from which the sample was drawn.""" return len(self.doc) def getDoc(self,d): """Given a document index this returns the appropriate DocSample object. These indices should align up with the document indices in the Corpus from which this Sample was drawn, assuming no documents have been deleted.""" return self.doc[d] def delDoc(self, ident): """Given a document ident this finds the document with the ident and removes it from the model, completly - i.e. all the variables in the sample are also updated. Primarilly used to remove documents for resampling prior to using the model as a prior. Note that this can potentially leave entities with no users - they get culled when the model is loaded into the C++ data structure so as to not cause problems.""" # Find and remove it from the document list... index = None for i in xrange(len(self.doc)): if self.doc[i].getIdent()==ident: index = i break if index==None: return victim = self.doc[index] self.doc = self.doc[:index] + self.doc[index+1:] # Update all the variables left behind by subtracting the relevant terms... cluster = self.cluster[victim.cluster] self.clusterUse[victim.cluster] -= 1 ## First pass through the dp and remove its influence; at the same time note the arrays that need to be updated by each user when looping through... dp_ext = [] for i in xrange(victim.dp.shape[0]): beh = victim.dp[i,0] #count = victim.dp[i,2] if beh==0: # Normal behaviour cluInst = victim.dp[i,1] # Update the instance, and topic use counts if necessary... topic = cluster[0][cluInst,0] cluster[0][cluInst,1] -= 1 if cluster[0][cluInst,1]==0: self.topicUse[topic] -= 1 # Store the entity that needs updating in correspondence with this dp instance in the next step... dp_ext.append((self.topicWord, topic)) else: # Abnormal behaviour. # Store the entity that needs updating in correspondence with the dp... dp_ext.append((self.abnormTopicWord, beh)) ## Go through the samples array and remove their influnce - the hard part was done by the preceding step... for si in xrange(victim.samples.shape[0]): inst = victim.samples[si,0] word = victim.samples[si,1] mat, topic = dp_ext[inst] mat[topic,word] -= 1 # Clean up all zeroed items... self.cleanZeros() def cleanZeros(self): """Goes through and removes anything that has a zero reference count, adjusting all indices accordingly.""" # Remove the zeros from this object, noting the changes... ## Topics... newTopicCount = 0 topicMap = dict() for t in xrange(self.topicUse.shape[0]): if self.topicUse[t]!=0: topicMap[t] = newTopicCount newTopicCount += 1 if newTopicCount!=self.topicUse.shape[0]: newTopicWord = numpy.zeros((newTopicCount, self.topicWord.shape[1]), dtype=numpy.int32) newTopicUse = numpy.zeros(newTopicCount,dtype=numpy.int32) for origin, dest in topicMap.iteritems(): newTopicWord[dest,:] = self.topicWord[origin,:] newTopicUse[dest] = self.topicUse[origin] self.topicWord = newTopicWord self.topicUse = newTopicUse ## Clusters... newClusterCount = 0 clusterMap = dict() for c in xrange(self.clusterUse.shape[0]): if self.clusterUse[c]!=0: clusterMap[c] = newClusterCount newClusterCount += 1 if newClusterCount!=self.clusterUse.shape[0]: newCluster = [None]*newClusterCount newClusterUse = numpy.zeros(newClusterCount, dtype=numpy.int32) for origin, dest in clusterMap.iteritems(): newCluster[dest] = self.cluster[origin] newClusterUse[dest] = self.clusterUse[origin] self.cluster = newCluster self.clusterUse = newClusterUse ## Cluster instances... # (Change is noted by a 2-tuple of (new length, dict) where new length is the new length and dict goes from old indices to new indices.) cluInstAdj = [] for ci in xrange(len(self.cluster)): newInstCount = 0 instMap = dict() for i in xrange(self.cluster[ci][0].shape[0]): if self.cluster[ci][0][i,1]!=0: instMap[i] = newInstCount newInstCount += 1 cluInstAdj.append((newInstCount, instMap)) if newInstCount!=self.cluster[ci][0].shape[0]: newInst = numpy.zeros((newInstCount,2), dtype=numpy.int32) for origin, dest in instMap.iteritems(): newInst[dest,:] = self.cluster[ci][0][origin,:] self.cluster[ci] = (newInst, self.cluster[ci][1], self.cluster[ci][2], self.cluster[ci][3]) # Iterate and update the topic indices of the cluster instances... for ci in xrange(len(self.cluster)): for i in xrange(self.cluster[ci][0].shape[0]): self.cluster[ci][0][i,0] = topicMap[self.cluster[ci][0][i,0]] # Now iterate the documents and update their cluster and cluster instance indices... for doc in self.doc: doc.cluster = clusterMap[doc.cluster] _, instMap = cluInstAdj[doc.cluster] for di in xrange(doc.dp.shape[0]): if doc.dp[di,0]==0: doc.dp[di,1] = instMap[doc.dp[di,1]] def nllAllDocs(self): """Returns the negative log likelihood of all the documents in the sample - a reasonable value to compare various samples with.""" return sum(map(lambda d: d.getNLL(),self.doc)) def logNegProbWordsGivenClusterAbnorm(self, doc, cluster, particles = 16, cap = -1): """Uses wallach's 'left to right' method to calculate the negative log probability of the words in the document given the rest of the model. Both the cluster (provided as an index) and the documents abnormalities vector are fixed for this calculation. Returns the average of the results for each sample contained within model. particles is the number of particles to use in the left to right estimation algorithm. This is implimented using scipy.weave.""" return solvers.leftRightNegLogProbWord(self, doc, cluster, particles, cap) def logNegProbWordsGivenAbnorm(self, doc, particles = 16, cap = -1): """Uses logNegProbWordsGivenClusterAbnorm and simply sums out the cluster variable.""" # Get the probability of each with the dependence with clusters... cluScores = map(lambda c: solvers.leftRightNegLogProbWord(self, doc, c, particles, cap), xrange(self.getClusterCount())) # Multiply each by the probability of the cluster, so it can be summed out... cluNorm = float(self.clusterUse.sum()) + self.clusterConc cluScores = map(lambda c,s: s - math.log(float(self.clusterUse[c])/cluNorm), xrange(len(cluScores)), cluScores) # Also need to include the probability of a new cluster, even though it is likelly to be a neglible contribution... newVal = solvers.leftRightNegLogProbWord(self, doc, -1, particles, cap) newVal -= math.log(self.clusterConc/cluNorm) cluScores.append(newVal) # Sum out the cluster variable, in a numerically stable way given that we are dealing with negative log likelihood values that will map to extremelly low probabilities... minScore = min(cluScores) cluPropProb = map(lambda s: math.exp(minScore-s), cluScores) return minScore - math.log(sum(cluPropProb)) class Model: """Simply contains a list of samples taken from the state during Gibbs iterations. Has clonning capability.""" def __init__(self, obj=None, priorsOnly = False): """If provided with a Model will clone it.""" self.sample = [] if isinstance(obj, Model): for sample in obj.sample: self.sample.append(Sample(sample, priorsOnly)) def add(self, sample): """Adds a sample to the model.""" self.sample.append(sample) def sampleState(self, state): """Samples the state, storing the sampled model within.""" self.sample.append(Sample(state)) def absorbModel(self, model): """Given another model this absorbs all its samples, leaving then given model baren.""" self.sample += model.sample model.sample = [] def sampleCount(self): """Returns the number of samples.""" return len(self.sample) def getSample(self, s): """Returns the sample associated with the given index.""" return self.sample[s] def sampleList(self): """Returns a list of samples, for iterating.""" return self.sample def delDoc(self, ident): """Calls the delDoc method for the given ident on all samples contained within.""" for sample in self.sample: sample.delDoc(ident) def bestSampleOnly(self): """Calculates the document nll for each sample and prunes all but the one with the highest - very simple way of 'merging' multiple samples together.""" score = map(lambda s: s.nllAllDocs(),self.sample) best = 0 for i in xrange(1,len(self.sample)): if score[i]>score[best]: best = i self.sample = [self.sample[best]] def fitDoc(self, doc, params = None, callback=None, mp = True): """Given a document this returns a DocModel calculated by Gibbs sampling the document with the samples in the model as priors. Returns a DocModel. Note that it samples using params for *each* sample in the Model, so you typically want to use less than the defaults in Params, typically only a single run and sample, which is the default. mp can be set to False to force it to avoid multi-processing behaviour""" if mp and len(self.sample)>1 and hasattr(solvers,'gibbs_doc_mp'): return solvers.gibbs_doc_mp(self, doc, params, callback) else: return solvers.gibbs_doc(self, doc, params, callback) def logNegProbWordsGivenAbnorm(self, doc, particles = 16, cap = -1, mp = True): """Calls the function of the same name for each sample and returns the average of the various return values.""" if mp and len(self.sample)>1: sampNLL = mp_map(lambda s,d,p,c: s.logNegProbWordsGivenAbnorm(d,p,c), self.sample, repeat(doc), repeat(particles), repeat(cap)) else: sampNLL = map(lambda s: s.logNegProbWordsGivenAbnorm(doc,particles,cap), self.sample) ret = 0.0 # Negative log prob retCount = 0.0 for nll in sampNLL: retCount += 1.0 if retCount < 1.5: ret = nll else: ret -= math.log(1.0 + (math.exp(ret-nll) - 1.0)/retCount) return ret def logNegProbAbnormGivenWords(self, doc, epsilon = 0.1, particles = 16, cap = -1): """Returns the probability of the documents current abnormality flags - uses Bayes rule on logNegProbAbnormGivenWords. Does not attempt to calculate the normalising constant, so everything is with proportionality - you can compare flags for a document, but can't compare between different documents. You actually provide epsilon to the function, as its not calculated anywhere. You can either provide a number, in which case that is the probability of each abnormality, or you can provide a numpy vector of probabilities, noting that the first entry must correspond to normal and be set to 1.0""" # Handle the conveniance input of providing a single floating point value for epsilon rather than a numpy array... if not isinstance(epsilon,numpy.ndarray): # Assume its a floating point number and build epsilon as an array... value = epsilon epsilon = numpy.ones(self.sample[0].phi.shape[0], dtype=numpy.float32) epsilon *= value epsilon[0] = 1.0 # Generate flags for the document... flags = numpy.zeros(self.sample[0].phi.shape[0], dtype=numpy.uint8) flags[0] = 1 for abnorm in doc.getAbnorms(): flags[self.sample[0].abnorms[abnorm]] = 1 # Apply Bayes - hardly hard!.. ret = self.logNegProbWordsGivenAbnorm(doc, particles, cap) for i in xrange(1,epsilon.shape[0]): if flags[i]!=0: ret -= math.log(epsilon[i]) else: ret -= math.log(1.0-epsilon[i]) return ret def mlDocAbnorm(self, doc, lone = False, epsilon = 0.1, particles = 16, cap = -1): """Decides which abnormalities most likelly exist in the document, using the logNegProbAbnormGivenWords method. Returns the list of abnormalities that are most likelly to exist. It does a greedy search of the state space - by default it considers all states, but setting the lone flag to true it will only consider states with one abnormality.""" # A dictionary that contains True to indicate that the indexed tuple of abnormalities has already been tried (And, effectivly, rejected.)... tried = dict() # Starting state... best = [] doc.setAbnorms(best) bestNLL = self.logNegProbAbnormGivenWords(doc, epsilon, particles, cap) tried[tuple(best)] = True # Iterate until no change... while True: newBest = best newBestNLL = bestNLL for abnorm in self.sample[0].abnorms.iterkeys(): test = best[:] if abnorm in test: test = filter(lambda a:a!=abnorm, test) else: test.append(abnorm) if lone and len(test)>1: continue doc.setAbnorms(test) if tuple(test) not in tried: tried[tuple(test)] = True doc.setAbnorms(test) testNLL = self.logNegProbAbnormGivenWords(doc, epsilon, particles, cap) if testNLL<newBestNLL: newBest = test newBestNLL = testNLL if best==newBest: doc.setAbnorms(best) return best else: best = newBest bestNLL = newBestNLL class DocModel: """A Model that just contains DocSample-s for a single document. Obviously incomplete without a full Model, this is typically used when sampling a document relative to an already trained Model, such that the topic/cluster indices will match up with the original Model. Note that if the document has enough data to justify the creation of an extra topic/cluster then that could exist with an index above the indices of the topics/clusters in the source Model.""" def __init__(self, obj=None): """Supports cloning.""" self.sample = [] if isinstance(obj, DocModel): for sample in obj.sample: self.sample.append(DocSample(sample)) def addFrom(self, model, index=0): """Given a model and a document index number extracts all the relevant DocSample-s, adding them to this DocModel. It does not edit the Model but the DocSample-s transfered over are the same instances.""" for s in xrange(model.sampleCount()): self.sample.append(model.getSample(s).getDoc(index)) def absorbModel(self, dModel): """Absorbs samples from the given DocModel, leaving it baren.""" self.sample += dModel.sample dModel.sample = [] def sampleCount(self): """Returns the number of samples contained within.""" return len(self.sample) def getSample(self, s): """Returns the sample with the given index, in the range 0..sampleCount()-1""" return self.sample[s] def sampleList(self): """Returns a list of samples, for iterating.""" return self.sample def hasAbnormal(self, name, abnormDict): """Given the key for an abnormality (Typically a string - as provided to the Document object orginally.) returns the probability this document has it, by looking through the samples contained within. Requires an abnorm dictionary, as obtained from the getAbnormDict method of a sample.""" if name not in abnormDict: return 0.0 index = abnormDict[name] count = 0 for s in self.sample: if s.getBehFlags()[index]!=0: count += 1 return float(count)/float(len(self.sample)) def getNLL(self): """Returns the average nll of all the contained samples - does a proper mean of the probability of the samples.""" minSam = min(map(lambda s:s.getNLL(),self.sample)) probMean = sum(map(lambda s:math.exp(minSam-s.getNLL()),self.sample)) probMean /= float(len(self.sample)) return minSam - math.log(probMean)
[ [ 1, 0, 0.0233, 0.0013, 0, 0.66, 0, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 1, 0, 0.0245, 0.0013, 0, 0.66, 0.1, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.0258, 0.0013, 0, 0.6...
[ "import math", "import numpy", "import scipy.special", "import collections", "import solvers", "from smp.smp import FlagIndexArray", "from utils.mp_map import *", "class DocSample:\n \"\"\"Stores the sample information for a given document - the DP from which topics are drawn and which cluster it is ...
# Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. class Params: """Parameters for running the fitter that are universal to all fitters - basically the parameters you would typically associate with Gibbs sampling.""" def __init__(self, toClone = None): """Sets the parameters to reasonable defaults. Will act as a copy constructor if given an instance of this object.""" if toClone!=None: self.__runs = toClone.runs self.__samples = toClone.samples self.__burnIn = toClone.burnIn self.__lag = toClone.lag else: self.__runs = 8 self.__samples = 10 self.__burnIn = 1000 self.__lag = 100 def setRuns(self, runs): """Sets the number of runs, i.e. how many seperate chains are run.""" assert(isinstance(runs, int)) assert(runs>0) self.__runs = runs def setSamples(self, samples): """Number of samples to extract from each chain - total number of samples extracted will hence be samples*runs.""" assert(isinstance(samples, int)) assert(samples>0) self.__samples = samples def setBurnIn(self, burnIn): """Number of Gibbs iterations to do for burn in before sampling starts.""" assert(isinstance(burnIn, int)) assert(burnIn>=0) self.__burnIn = burnIn def setLag(self, lag): """Number of Gibbs iterations to do between samples.""" assert(isinstance(lag, int)) assert(lag>0) self.__lag = lag def getRuns(self): """Returns the number of runs.""" return self.__runs def getSamples(self): """Returns the number of samples.""" return self.__samples def getBurnIn(self): """Returns the burn in length.""" return self.__burnIn def getLag(self): """Returns the lag length.""" return self.__lag runs = property(getRuns, setRuns, None, "Number of seperate chains to run.") samples = property(getSamples, setSamples, None, "Number of samples to extract from each chain") burnIn = property(getBurnIn, setBurnIn, None, "Number of iterations to do before taking the first sample of a chain.") lag = property(getLag, setLag, None, "Number of iterations to do between samples.") def fromArgs(self, args, prefix = ''): """Extracts from an arg string, typically sys.argv[1:], the parameters, leaving them untouched if not given. Uses --runs, --samples, --burnIn and --lag. Can optionally provide a prefix which is inserted after the '--'""" try: ind = args[:-1].index('--'+prefix+'runs') self.runs = int(args[ind+1]) except ValueError: pass try: ind = args[:-1].index('--'+prefix+'samples') self.samples = int(args[ind+1]) except ValueError: pass try: ind = args[:-1].index('--'+prefix+'burnIn') self.burnIn = int(args[ind+1]) except ValueError: pass try: ind = args[:-1].index('--'+prefix+'lag') self.lag = int(args[ind+1]) except ValueError: pass
[ [ 3, 0, 0.5556, 0.899, 0, 0.66, 0, 219, 0, 10, 0, 0, 0, 0, 16 ], [ 8, 1, 0.1212, 0.0101, 1, 0.15, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 2, 1, 0.1869, 0.1212, 1, 0.15, ...
[ "class Params:\n \"\"\"Parameters for running the fitter that are universal to all fitters - basically the parameters you would typically associate with Gibbs sampling.\"\"\"\n def __init__(self, toClone = None):\n \"\"\"Sets the parameters to reasonable defaults. Will act as a copy constructor if given an ins...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]