code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
# 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)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| Python |
#! /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)
| 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 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()
| 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.
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
"""
| Python |
#! /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)
| Python |
# 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()
| 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.
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)
| Python |
# 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)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| Python |
#! /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)
| 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 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()
| 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.
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
"""
| Python |
#! /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)
| Python |
# 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()
| 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.
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)
| Python |
# 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)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| Python |
#! /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)
| 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 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()
| 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.
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
"""
| Python |
#! /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)
| Python |
# 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()
| 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.
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)
| Python |
# 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)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| Python |
#! /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)
| 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 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()
| 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.
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
"""
| Python |
#! /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)
| Python |
# 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()
| 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.
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)
| Python |
# 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)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| Python |
#! /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)
| 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 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()
| 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.
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
"""
| Python |
#! /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)
| Python |
# 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()
| 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.
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)
| Python |
# 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)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| Python |
#! /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)
| 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 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()
| 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.
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
"""
| Python |
#! /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)
| Python |
# 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()
| 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.
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)
| Python |
# 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)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| Python |
#! /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)
| 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 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()
| 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.
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
"""
| Python |
#! /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)
| Python |
# 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()
| 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.
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)
| Python |
# 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)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| Python |
#! /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)
| 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 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()
| 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.
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
"""
| Python |
#! /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)
| Python |
# 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()
| 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.
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)
| Python |
# 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)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| Python |
#! /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)
| 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 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()
| 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.
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
"""
| Python |
#! /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)
| Python |
# 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()
| 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.
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)
| Python |
# 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)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| Python |
#! /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)
| 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 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()
| 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.
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
"""
| Python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# 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 dp_al
from utils import doc_gen
# Setup...
doc = doc_gen.DocGen('dp_al', 'Dirichlet Process Active Learning', 'Active learning, includes Dirichlet process derived method')
doc.addFile('readme.txt', 'Overview')
# Classes...
doc.addClass(dp_al.Pool)
doc.addClass(dp_al.Entity)
doc.addClass(dp_al.ConcentrationDP)
| Python |
# Copyright 2012 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
import numpy
from df.df import *
from kde_inc.kde_inc import KDE_INC
from prob_cat import ProbCat
class ClassifyDF_KDE(ProbCat):
"""A classifier that uses decision forests. Includes the use of a density estimate decision forest as a psuedo-prior. The incrimental method used is rather simple, but still works reasonably well. Provides default parameters for the decision forests, but allows access to them for if you want to mess around. Internally the decision forests have two channels - the first is the data, the second the class."""
def __init__(self, prec, cap, treeCount, incAdd = 1, testDims = 3, dimCount = 4, rotCount = 32):
"""prec is the precision matrix for the density estimate done with kernel density estimation; cap is the component cap for said kernel density estimate. treeCount is how many trees to use for the classifying decision forest whilst incAdd is how many to train for each new sample. testDims is the number of dimensions to use for each test, dimCount the number of combinations of dimensions to try for generating each nodes decision and rotCount the number of orientations to try for each nodes test generation."""
# Support structures...
self.cats = dict() # Dictionary from cat to internal indexing number.
self.treeCount = treeCount
self.incAdd = incAdd
# Setup the classification forest...
self.classify = DF()
self.classify.setInc(True)
self.classify.setGoal(Classification(None, 1))
self.classify.setGen(LinearClassifyGen(0, 1, testDims, dimCount, rotCount))
self.classifyData = MatrixGrow()
self.classifyTrain = self.treeCount
# Setup the density estimation kde...
self.density = KDE_INC(prec, cap)
def getClassifier(self):
"""Returns the decision forest used for classification."""
return self.classify
def getDensityEstimate(self):
"""Returns the KDE_INC used for density estimation, as a psuedo-prior."""
return self.density
def priorAdd(self, sample):
self.density.add(sample)
def add(self, sample, cat):
if cat in self.cats:
c = self.cats[cat]
else:
c = len(self.cats)
self.cats[cat] = c
self.classifyData.append(numpy.asarray(sample, dtype=numpy.float32), numpy.asarray(c, dtype=numpy.int32).reshape((1,)))
self.classifyTrain += self.incAdd
def getSampleTotal(self):
return self.classifyData.exemplars()
def getCatTotal(self):
return len(self.cats)
def getCatList(self):
return self.cats.keys()
def getCatCounts(self):
if len(self.cats)==0: return dict()
counts = numpy.bincount(self.classifyData[1,:,0])
ret = dict()
for cat, c in self.cats.iteritems():
ret[cat] = counts[c] if c<counts.shape[0] else 0
return ret
def listMode(self):
return True
def getDataProb(self, sample, state = None):
# Update the model as needed - this will potentially take some time...
if self.classifyTrain!=0 and self.classifyData.exemplars()!=0:
self.classify.learn(min(self.classifyTrain, self.treeCount), self.classifyData, clamp = self.treeCount, mp=False)
self.classifyTrain = 0
# Generate the result and create and return the right output structure...
ret = dict()
if self.classify.size()!=0:
eval_c = self.classify.evaluate(MatrixES(sample), which = 'gen')[0]
for cat, c in self.cats.iteritems():
ret[cat] = eval_c[c] if c<eval_c.shape[0] else 0.0
ret[None] = self.density.prob(sample)
return ret
def getDataProbList(self, sample, state = None):
# Update the models as needed - this will potentially take some time...
if self.classifyTrain!=0 and self.classifyData.exemplars()!=0:
self.classify.learn(min(self.classifyTrain, self.treeCount), self.classifyData, clamp = self.treeCount, mp=False)
self.classifyTrain = 0
# Fetch the required information...
if self.classify.size()!=0:
eval_c = self.classify.evaluate(MatrixES(sample), which = 'gen_list')[0]
else:
return [{None:1.0}]
eval_d = self.density.prob(sample)
# Construct and return the output...
ret = []
for ec in eval_c:
r = {None:eval_d}
for cat, c in self.cats.iteritems():
r[cat] = ec[c] if c<ec.shape[0] else 0.0
ret.append(r)
return ret
| Python |
# Copyright 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
from dpgmm.dpgmm import DPGMM
from prob_cat import ProbCat
class ClassifyDPGMM(ProbCat):
"""A classifier that uses a Dirichlet process Gaussian mixture model (DPGMM) for each category. Also includes a psuedo-prior in the form of an extra DPGMM that you can feed. Trains them incrimentally, increasing the mixture component cap when that results in an improvement in model performance. Be aware that whilst this is awesome its memory consumption can be fierce, and its a computational hog. Includes the ability to switch off incrimental learning, which can save some time if your not using the model between trainning samples."""
def __init__(self, dims, runs = 1):
"""dims is the number of dimensions the input vectors have, whilst runs is how many starting points to converge from for each variational run. Increasing runs helps to avoid local minima at the expense of computation, but as it often converges well enough with the first attempt, so this is only for the paranoid."""
self.dims = dims
self.runs = runs
self.inc = True
self.prior = DPGMM(self.dims)
self.cats = dict() # Dictionary indexed by category going to the associated DPGMM object.
self.counts = None
def priorAdd(self, sample):
self.prior.add(sample)
if self.inc and self.prior.setPrior():
self.prior = self.prior.multiGrowSolve(self.runs)
def add(self, sample, cat):
if cat not in self.cats: self.cats[cat] = DPGMM(self.dims)
self.cats[cat].add(sample)
if self.inc and self.cats[cat].setPrior():
self.cats[cat] = self.cats[cat].multiGrowSolve(self.runs)
self.counts = None
def setInc(self, state):
"""With a state of False it disables incrimental learning until further notice, with a state of True it reenables it, and makes sure that it is fully up to date by updating everything. Note that when reenabled it assumes that enough data is avaliable, and will crash if not, unlike the incrimental approach that just twiddles its thumbs - in a sense this is safer if you want to avoid bad results."""
self.inc = state
if self.inc:
self.prior.setPrior()
self.prior = self.prior.multiGrowSolve(self.runs)
for cat in self.cats.iterkeys():
self.cats[cat].setPrior()
self.cats[cat] = self.cats[cat].multiGrowSolve(self.runs)
def getSampleTotal(self):
sum(map(lambda mm: mm.size(), self.cats.itervalues()))
def getCatTotal(self):
return len(self.cats)
def getCatList(self):
return self.cats.keys()
def getCatCounts(self):
if self.counts==None:
self.counts = dict()
for cat, mm in self.cats.iteritems():
self.counts[cat] = mm.size()
return self.counts
def getDataProb(self, sample, state = None):
ret = dict()
for cat, mm in self.cats.iteritems(): ret[cat] = mm.prob(sample)
return ret
| Python |
# Copyright 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
from gcp import gcp
from prob_cat import ProbCat
class ClassifyGaussian(ProbCat):
"""A simplistic Gaussian classifier, that uses a single Gaussian to represent each category/the prior. It is of course fully Bayesian. It keeps a prior that is worth the number of dimensions with the mean and covariance of all the samples provided for its construction. Implimentation is not very efficient, though includes some caching to stop things being too slow."""
def __init__(self, dims):
"""dims is the number of dimensions."""
self.dims = dims
self.prior = gcp.GaussianPrior(self.dims)
self.cats = dict() # Dictionary indexed by categories with a value of the associated GaussianPrior object, without the current prior included - it is merged in as needed.
self.counts = None # Dictionary going to sample counts for each category.
self.cst = None # Dictionary indexed as above, but going to student-t distributions representing the current state. A caching layer that gets invalidated as needed.
def priorAdd(self, sample):
self.prior.addSample(sample)
self.cst = None
def add(self, sample, cat):
if cat not in self.cats: self.cats[cat] = gcp.GaussianPrior(self.dims)
self.cats[cat].addSample(sample)
self.counts = None
self.cst = None
def getSampleTotal(self):
return sum(map(lambda gp: int(gp.getN()), self.cats.itervalues()))
def getCatTotal(self):
return len(self.cats)
def getCatList(self):
return self.cats.keys()
def getCatCounts(self):
if self.counts==None:
self.counts = dict()
for cat, gp in self.cats.iteritems():
self.counts[cat] = int(gp.getN())
return self.counts
def getStudentT(self):
"""Returns a dictionary with categories as keys and StudentT distributions as values, these being the probabilities of samples belonging to each class with the actual draw from the posterior integrated out. Also stores the prior, under a key of None."""
if self.cst==None:
self.cst = dict()
# First prep the prior...
prior = gcp.GaussianPrior(self.prior)
prior.make_safe()
prior.reweight()
self.cst[None] = prior.intProb()
# Then iterate the categories and extract their student-t's, after updating with the prior...
for cat, gp in self.cats.iteritems():
ngp = gcp.GaussianPrior(gp)
ngp.addGP(prior)
self.cst[cat] = ngp.intProb()
return self.cst
def getDataProb(self, sample, state = None):
ret = dict()
for cat, st in self.getStudentT().iteritems(): ret[cat] = st.prob(sample)
return ret
| Python |
# Copyright 2012 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
import numpy
from df.df import *
from prob_cat import ProbCat
class ClassifyDF(ProbCat):
"""A classifier that uses decision forests. Includes the use of a density estimate decision forest as a psuedo-prior. The incrimental method used is rather simple, but still works reasonably well. Provides default parameters for the decision forests, but allows access to them for if you want to mess around. Internally the decision forests have two channels - the first is the data, the second the class."""
def __init__(self, dims, treeCount, incAdd = 1, testDims = 3, dimCount = 4, rotCount = 32):
"""dims is the number of dimensions in each sample. treeCount is how many trees to use whilst incAdd is how many to train for each new sample. testDims is the number of dimensions to use for each test, dimCount the number of combinations of dimensions to try for generating each nodes decision and rotCount the number of orientations to try for each nodes test generation."""
# Support structures...
self.cats = dict() # Dictionary from cat to internal indexing number.
self.treeCount = treeCount
self.incAdd = incAdd
# Setup the classification forest...
self.classify = DF()
self.classify.setInc(True)
self.classify.setGoal(Classification(None, 1))
self.classify.setGen(LinearClassifyGen(0, 1, testDims, dimCount, rotCount))
self.classifyData = MatrixGrow()
self.classifyTrain = self.treeCount
# Setup the density estimation forest...
self.density = DF()
self.density.setInc(True)
self.density.setGoal(DensityGaussian(dims))
self.density.setGen(LinearMedianGen(0, testDims, dimCount, rotCount))
self.density.getPruner().setMinTrain(48)
self.densityData = MatrixGrow()
self.densityTrain = self.treeCount
def getClassifier(self):
"""Returns the decision forest used for classification."""
return self.classify
def getDensityEstimate(self):
"""Returns the decision forest used for density estimation, as a psuedo-prior."""
return self.density
def setDensityMinTrain(self, count):
self.density.getPruner().setMinTrain(count)
def priorAdd(self, sample):
self.densityData.append(numpy.asarray(sample, dtype=numpy.float32))
self.densityTrain += self.incAdd
def add(self, sample, cat):
if cat in self.cats:
c = self.cats[cat]
else:
c = len(self.cats)
self.cats[cat] = c
self.classifyData.append(numpy.asarray(sample, dtype=numpy.float32), numpy.asarray(c, dtype=numpy.int32).reshape((1,)))
self.classifyTrain += self.incAdd
def getSampleTotal(self):
return self.classifyData.exemplars()
def getCatTotal(self):
return len(self.cats)
def getCatList(self):
return self.cats.keys()
def getCatCounts(self):
if len(self.cats)==0: return dict()
counts = numpy.bincount(self.classifyData[1,:,0])
ret = dict()
for cat, c in self.cats.iteritems():
ret[cat] = counts[c] if c<counts.shape[0] else 0
return ret
def listMode(self):
return True
def getDataProb(self, sample, state = None):
# Update the models as needed - this will potentially take some time...
if self.classifyTrain!=0 and self.classifyData.exemplars()!=0:
self.classify.learn(min(self.classifyTrain, self.treeCount), self.classifyData, clamp = self.treeCount, mp=False)
self.classifyTrain = 0
if self.densityTrain!=0 and self.densityData.exemplars()!=0:
self.density.learn(min(self.densityTrain, self.treeCount), self.densityData, clamp = self.treeCount, mp=False)
self.densityTrain = 0
# Generate the result and create and return the right output structure...
ret = dict()
if self.classify.size()!=0:
eval_c = self.classify.evaluate(MatrixES(sample), which = 'gen')[0]
for cat, c in self.cats.iteritems():
ret[cat] = eval_c[c] if c<eval_c.shape[0] else 0.0
if self.density.size()!=0:
eval_d = self.density.evaluate(MatrixES(sample), which = 'best')[0]
ret[None] = eval_d
else:
ret[None] = 1.0
return ret
def getDataProbList(self, sample, state = None):
# Update the models as needed - this will potentially take some time...
if self.classifyTrain!=0 and self.classifyData.exemplars()!=0:
self.classify.learn(min(self.classifyTrain, self.treeCount), self.classifyData, clamp = self.treeCount, mp=False)
self.classifyTrain = 0
if self.densityTrain!=0 and self.densityData.exemplars()!=0:
self.density.learn(min(self.densityTrain, self.treeCount), self.densityData, clamp = self.treeCount, mp=False)
self.densityTrain = 0
# Fetch the required information...
if self.classify.size()!=0:
eval_c = self.classify.evaluate(MatrixES(sample), which = 'gen_list')[0]
else:
return [{None:1.0}]
if self.density.size()!=0:
eval_d = self.density.evaluate(MatrixES(sample), which = 'best')[0]
else:
eval_d = 1.0
# Construct and return the output...
ret = []
for ec in eval_c:
r = {None:eval_d}
for cat, c in self.cats.iteritems():
r[cat] = ec[c] if c<ec.shape[0] else 0.0
ret.append(r)
return ret
| Python |
# Copyright 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
from prob_cat import ProbCat
try: from classify_gaussian import ClassifyGaussian
except: pass
try: from classify_kde import ClassifyKDE
except: pass
try: from classify_bag_kde import ClassifyBagKDE
except: pass
try: from classify_dpgmm import ClassifyDPGMM
except: pass
try: from classify_df import ClassifyDF
except: pass
try: from classify_df_kde import ClassifyDF_KDE
except: pass
| Python |
# Copyright 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
import math
import numpy
from scipy import weave
from utils.start_cpp import start_cpp
from utils.matrix_cpp import matrix_code
from loo_cov import PrecisionLOO, SubsetPrecisionLOO # Not used below, just for conveniance.
from gmm import GMM
class KDE_INC:
"""Provides an incrimental kernel density estimate system that uses Gaussians. A kernel density estimate system with Gaussian kernels that, on reaching a cap, starts merging kernels to limit the number of kernels to a constant - done in such a way as to minimise error whilst capping computation. (Computation is quite high however - this is not a very efficient implimentation.)"""
def __init__(self, prec, cap = 32):
"""Initialise with the precision matrix to use for the kernels, which implicitly provides the number of dimensions, and the cap on the number of kernels to allow."""
self.prec = numpy.asarray(prec, dtype=numpy.float32)
self.gmm = GMM(prec.shape[0], cap) # Current mixture model.
self.count = 0 # Number of samples provided so far.
self.merge = numpy.empty((cap,cap), dtype=numpy.float32) # [i,j]; cost of merging two entrys, only valid when j<i, other values set high to avoid issues.
self.merge[:,:] = 1e64
# For holding the temporary merge costs calculated when adding a sample...
self.mergeT = numpy.empty(cap, dtype=numpy.float32)
# For the C code...
self.temp = numpy.empty((2, prec.shape[0], prec.shape[0]), dtype=numpy.float32)
def setPrec(self, prec):
"""Changes the precision matrix - must be called before any samples are added, and must have the same dimensions as the current one."""
self.prec = numpy.asarray(prec, dtype=numpy.float32)
def samples(self):
"""Returns how many samples have been added to the object."""
return self.count
def prob(self, sample):
"""Returns the probability of the given sample - must not be called until at least one sample has been added, though it will return a positive constant if called with no samples provided."""
if self.count!=0: return self.gmm.prob(sample)
else: return 1.0
def nll(self, sample):
"""Returns the negative log liklihood of the given sample - must not be called until at least one sample has been added, though it will return a positive constant if called with no samples provided."""
if self.count!=0: return self.gmm.nll(sample)
else: return 0.0
def __merge(self, weightA, meanA, precA, weightB, meanB, precB):
"""Merges two Gaussians and returns the merged result, as (weight, mean, prec)"""
newWeight = weightA + weightB
newMean = weightA/newWeight * meanA + weightB/newWeight * meanB
deltaA = meanA - newMean
covA = numpy.linalg.inv(precA) + numpy.outer(deltaA, deltaA)
deltaB = meanB - newMean
covB = numpy.linalg.inv(precB) + numpy.outer(deltaB, deltaB)
newCov = weightA/newWeight * covA + weightB/newWeight * covB
newPrec = numpy.linalg.inv(newCov)
return (newWeight, newMean, newPrec)
def __calcMergeCost(self, weightA, meanA, precA, weightB, meanB, precB):
"""Calculates and returns the cost of merging two Gaussians."""
# (For anyone wondering about the fact we are comparing them against each other rather than against the result of merging them that is because this way tends to get better results.)
# The log determinants and delta...
logDetA = math.log(numpy.linalg.det(precA))
logDetB = math.log(numpy.linalg.det(precB))
delta = meanA - meanB
# Kullback-Leibler of representing A using B...
klA = logDetB - logDetA
klA += numpy.trace(numpy.dot(precB, numpy.linalg.inv(precA)))
klA += numpy.dot(numpy.dot(delta, precB), delta)
klA -= precA.shape[0]
klA *= 0.5
# Kullback-Leibler of representing B using A...
klB = logDetA - logDetB
klB += numpy.trace(numpy.dot(precA, numpy.linalg.inv(precB)))
klB += numpy.dot(numpy.dot(delta, precA), delta)
klB -= precB.shape[0]
klB *= 0.5
# Return a weighted average...
return weightA * klA + weightB * klB
def add(self, sample):
"""Adds a sample, updating the kde accordingly."""
global weave
try:
weave = None # Below code is actually slowing things down. Am disabling for now.
if weave==None: raise Exception()
support = matrix_code + start_cpp() + """
// Note - designed so that A and Out pointers can be the same.
void doMerge(int size, float weightA, float * meanA, float * precA, float weightB, float * meanB, float * precB, float & weightOut, float * meanOut, float * precOut, float * tVec, float * tMat1, float * tMat2)
{
// Handle the weight, recording the ratios needed next...
float wOut = weightA + weightB;
float ratioA = weightA/wOut;
float ratioB = weightB/wOut;
weightOut = wOut;
// Do the mean - simply a weighted average - store in a temporary for now...
for (int i=0; i<size; i++)
{
tVec[i] = ratioA * meanA[i] + ratioB * meanB[i];
}
// Put the covariance of precision A into tMat1...
for (int i=0; i<size*size; i++) tMat2[i] = precA[i];
Inverse(tMat2, tMat1, size);
// Add the outer product of the A delta into tMat1...
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
tMat1[r*size + c] += (meanA[c] - tVec[c]) * (meanA[r] - tVec[r]);
}
}
// Put the covariance of precision B into tMat2...
for (int i=0; i<size*size; i++) precOut[i] = precB[i];
Inverse(precOut, tMat2, size);
// Add the outer product of the B delta into tMat2...
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
tMat2[r*size + c] += (meanB[c] - tVec[c]) * (meanB[r] - tVec[r]);
}
}
// Get the weighted average of the covariance matrices into tMat1...
for (int i=0; i<size*size; i++)
{
tMat1[i] = ratioA * tMat1[i] + ratioB * tMat2[i];
}
// Dump the inverse of tMat1 into the output precision...
Inverse(tMat1, precOut, size);
// Copy from the temporary mean into the output mean...
for (int i=0; i<size; i++) meanOut[i] = tVec[i];
}
float mergeCost(int size, float weightA, float * meanA, float * precA, float weightB, float * meanB, float * precB, float * tVec1, float * tVec2, float * tMat1, float * tMat2)
{
// Calculate some shared values...
float logDetA = log(Determinant(precA, size));
float logDetB = log(Determinant(precB, size));
for (int i=0; i<size; i++)
{
tVec1[i] = meanA[i] - meanB[i];
} // tVec1 now contains the delta.
// Calculate the Kullback-Leibler divergance of substituting B for A...
float klA = logDetB - logDetA;
for (int i=0; i<size*size; i++) tMat1[i] = precA[i];
if (Inverse(tMat1, tMat2, size)==false) return 0.0;
for (int i=0; i<size; i++)
{
for (int j=0; j<size; j++)
{
klA += precB[i*size + j] * tMat2[j*size + i];
}
}
for (int i=0; i<size; i++)
{
tVec2[i] = 0.0;
for (int j=0; j<size; j++)
{
tVec2[i] += precB[i*size + j] * tVec1[j];
}
}
for (int i=0; i<size; i++) klA += tVec1[i] * tVec2[i];
klA -= size;
klA *= 0.5;
// Calculate the Kullback-Leibler divergance of substituting A for B...
float klB = logDetA - logDetB;
for (int i=0; i<size*size; i++) tMat1[i] = precB[i];
if (Inverse(tMat1, tMat2, size)==false) return 0.0;
for (int i=0; i<size; i++)
{
for (int j=0; j<size; j++)
{
klB += precA[i*size + j] * tMat2[j*size + i];
}
}
for (int i=0; i<size; i++)
{
tVec2[i] = 0.0;
for (int j=0; j<size; j++)
{
tVec2[i] += precA[i*size + j] * tVec1[j];
}
}
for (int i=0; i<size; i++) klB += tVec1[i] * tVec2[i];
klB -= size;
klB *= 0.5;
// Return a weighted average of the divergances...
return weightA * klA + weightB * klB;
}
"""
code = start_cpp(support) + """
if (count < Nweight[0])
{
// Pure KDE mode - just add the kernel...
for (int i=0; i<Nsample[0]; i++)
{
MEAN2(count, i) = sample[i];
}
for (int i=0; i<Nsample[0]; i++)
{
for (int j=0; j<Nsample[0]; j++)
{
PREC3(count, i, j) = BASEPREC2(i, j);
}
}
assert(Sprec[0]==sizeof(float));
assert(Sprec[1]==sizeof(float)*Nsample[0]);
log_norm[count] = 0.5 * log(Determinant(&PREC3(count, 0, 0), Nsample[0]));
log_norm[count] -= 0.5 * Nsample[0] * log(2.0*M_PI);
float w = 1.0 / (count+1);
for (int i=0; i<=count; i++)
{
weight[i] = w;
}
// If the next sample will involve merging then we need to fill in the merging costs cache in preperation...
if (count+1==Nweight[0])
{
for (int i=0; i<Nweight[0]; i++)
{
for (int j=0; j<i; j++)
{
MERGE2(i, j) = mergeCost(Nsample[0], weight[i], &MEAN2(i,0), &PREC3(i,0,0), weight[j], &MEAN2(j,0), &PREC3(j,0,0), &TEMP2(0,0), &TEMP2(1,0), &TEMPPREC3(0,0,0), &TEMPPREC3(1,0,0));
}
}
}
}
else
{
// We have the maximum number of kernels - need to either merge the new kernel with an existing one, or merge two existing kernels and use the freed up slot for the new kernel...
// Update the weights, and calculate the weight of the new kernel...
float adjust = float(count) / float(count+1);
for (int i=0; i<Nweight[0]; i++) weight[i] *= adjust;
for (int i=0; i<Nweight[0]; i++)
{
for (int j=0; j<i; j++) MERGE2(i, j) *= adjust;
}
float w = 1.0 / float(count + 1.0);
// Calculate the costs of merging the new kernel with each of the old kernels...
for (int i=0; i<Nweight[0]; i++)
{
mergeT[i] = mergeCost(Nsample[0], w, sample, basePrec, weight[i], &MEAN2(i,0), &PREC3(i,0,0), &TEMP2(0,0), &TEMP2(1,0), &TEMPPREC3(0,0,0), &TEMPPREC3(1,0,0));
}
// Find the lowest merge cost and act accordingly - either we are merging the new kernel with an old one or merging two existing kernels and putting the new kernel in on its own...
int lowI = 1;
int lowJ = 0;
for (int i=0; i<Nweight[0]; i++)
{
for (int j=0; j<i; j++)
{
if (MERGE2(i, j) < MERGE2(lowI, lowJ))
{
lowI = i;
lowJ = j;
}
}
}
int lowN = 0;
for (int i=1; i<Nweight[0]; i++)
{
if (mergeT[i] < mergeT[lowN]) lowN = i;
}
if (mergeT[lowN] < MERGE2(lowI, lowJ))
{
// We are merging the new kernel with an existing kernel...
// Do the merge...
doMerge(Nsample[0], weight[lowN], &MEAN2(lowN,0), &PREC3(lowN,0,0), w, sample, basePrec, weight[lowN], &MEAN2(lowN,0), &PREC3(lowN,0,0), &TEMP2(0,0), &TEMPPREC3(0,0,0), &TEMPPREC3(1,0,0));
// Update the normalising constant...
log_norm[lowN] = 0.5 * log(Determinant(&PREC3(lowN, 0, 0), Nsample[0]));
log_norm[lowN] -= 0.5 * Nsample[0] * log(2.0*M_PI);
// Update the array of merge costs...
for (int i=0; i<Nweight[0]; i++)
{
if (i!=lowN)
{
float mc = mergeCost(Nsample[0], weight[i], &MEAN2(i,0), &PREC3(i,0,0), weight[lowN], &MEAN2(lowN,0), &PREC3(lowN,0,0), &TEMP2(0,0), &TEMP2(1,0), &TEMPPREC3(0,0,0), &TEMPPREC3(1,0,0));
if (i<lowN) MERGE2(lowN, i) = mc;
else MERGE2(i, lowN) = mc;
}
}
}
else
{
// We are merging two existing kernels then putting the new kernel into the freed up spot...
// Do the merge...
doMerge(Nsample[0], weight[lowI], &MEAN2(lowI,0), &PREC3(lowI,0,0), weight[lowJ], &MEAN2(lowJ,0), &PREC3(lowJ,0,0), weight[lowI], &MEAN2(lowI,0), &PREC3(lowI,0,0), &TEMP2(0,0), &TEMPPREC3(0,0,0), &TEMPPREC3(1,0,0));
// Copy in the new kernel...
weight[lowJ] = w;
for (int i=0; i<Nsample[0]; i++) MEAN2(lowJ,i) = sample[i];
for (int i=0; i<Nsample[0];i++)
{
for (int j=0; j<Nsample[0]; j++)
{
PREC3(lowJ,i,j) = basePrec[i*Nsample[0] + j];
}
}
// Update both normalising constants...
log_norm[lowI] = 0.5 * log(Determinant(&PREC3(lowI, 0, 0), Nsample[0]));
log_norm[lowI] -= 0.5 * Nsample[0] * log(2.0*M_PI);
log_norm[lowJ] = 0.5 * log(Determinant(&PREC3(lowJ, 0, 0), Nsample[0]));
log_norm[lowJ] -= 0.5 * Nsample[0] * log(2.0*M_PI);
// Update the array of merge costs...
for (int i=0; i<Nweight[0]; i++)
{
if (i!=lowI)
{
float mc = mergeCost(Nsample[0], weight[i], &MEAN2(i,0), &PREC3(i,0,0), weight[lowI], &MEAN2(lowI,0), &PREC3(lowI,0,0), &TEMP2(0,0), &TEMP2(1,0), &TEMPPREC3(0,0,0), &TEMPPREC3(1,0,0));
if (i<lowI) MERGE2(lowI, i) = mc;
else MERGE2(i, lowI) = mc;
}
}
for (int i=0; i<Nweight[0]; i++)
{
if ((i!=lowI)&&(i!=lowJ))
{
float mc = mergeCost(Nsample[0], weight[i], &MEAN2(i,0), &PREC3(i,0,0), weight[lowJ], &MEAN2(lowJ,0), &PREC3(lowJ,0,0), &TEMP2(0,0), &TEMP2(1,0), &TEMPPREC3(0,0,0), &TEMPPREC3(1,0,0));
if (i<lowJ) MERGE2(lowJ, i) = mc;
else MERGE2(i, lowJ) = mc;
}
}
}
}
"""
sample = numpy.asarray(sample, dtype=numpy.float32).flatten()
basePrec = self.prec
count = self.count
merge = self.merge
mergeT = self.mergeT
tempPrec = self.temp
weight = self.gmm.weight
mean = self.gmm.mean
prec = self.gmm.prec
log_norm = self.gmm.log_norm
temp = self.gmm.temp
weave.inline(code, ['sample', 'basePrec', 'count', 'merge', 'mergeT', 'tempPrec', 'weight', 'mean', 'prec', 'log_norm', 'temp'], support_code = support)
self.count += 1
except Exception, e:
if weave!=None:
print e
weave = None
if self.count<self.gmm.weight.shape[0]:
# Pure kde phase...
self.gmm.mean[self.count,:] = numpy.asarray(sample, dtype=numpy.float32)
self.gmm.prec[self.count,:,:] = self.prec
self.gmm.calcNorm(self.count)
self.count += 1
self.gmm.weight[:self.count] = 1.0 / float(self.count)
if self.count==self.gmm.weight.shape[0]:
# Next sample starts merging - need to prepare by filling in the kl array...
# (Below is grossly inefficient - calculates the same things more times than is possibly funny. I'll optimise it if I ever decide that I care enough to do so.)
for i in xrange(self.merge.shape[0]):
for j in xrange(i):
self.merge[i,j] = self.__calcMergeCost(self.gmm.weight[i], self.gmm.mean[i,:], self.gmm.prec[i,:,:], self.gmm.weight[j], self.gmm.mean[j,:], self.gmm.prec[j,:,:])
else:
# Merging phase...
sample = numpy.asarray(sample, dtype=numpy.float32)
# Adjust weights...
adjust = float(self.count) / float(self.count+1)
self.gmm.weight *= adjust
for i in xrange(self.merge.shape[0]): self.merge[i,:i] *= adjust
self.count += 1
weight = 1.0 / float(self.count)
# Calculate the merging costs for the new kernel versus the old kernels...
for i in xrange(self.merge.shape[0]):
self.mergeT[i] = self.__calcMergeCost(weight, sample, self.prec, self.gmm.weight[i], self.gmm.mean[i,:], self.gmm.prec[i,:,:])
# Select the best merge - it either involves the new sample or it does not...
bestOld = numpy.unravel_index(numpy.argmin(self.merge), self.merge.shape)
bestNew = numpy.argmin(self.mergeT)
if self.mergeT[bestNew] < self.merge[bestOld]:
# Easy scenario - new kernel is being merged with an existing kernel - not too much fiddling involved...
# Do the merge...
newWeight, newMean, newPrec = self.__merge(weight, sample, self.prec, self.gmm.weight[bestNew], self.gmm.mean[bestNew,:], self.gmm.prec[bestNew,:,:])
# Store the result...
self.gmm.weight[bestNew] = newWeight
self.gmm.mean[bestNew,:] = newMean
self.gmm.prec[bestNew,:,:] = newPrec
self.gmm.calcNorm(bestNew)
# Update the merge weights...
for i in xrange(self.merge.shape[0]):
if i!=bestNew:
cost = self.__calcMergeCost(self.gmm.weight[i], self.gmm.mean[i,:], self.gmm.prec[i,:,:], self.gmm.weight[bestNew], self.gmm.mean[bestNew,:], self.gmm.prec[bestNew,:,:])
if i<bestNew: self.merge[bestNew,i] = cost
else: self.merge[i,bestNew] = cost
else:
# We are merging two old kernels, and then putting the new kernel into the slot freed up - this is extra fiddly...
# Do the merge...
newWeight, newMean, newPrec = self.__merge(self.gmm.weight[bestOld[0]], self.gmm.mean[bestOld[0],:], self.gmm.prec[bestOld[0],:,:], self.gmm.weight[bestOld[1]], self.gmm.mean[bestOld[1],:], self.gmm.prec[bestOld[1],:,:])
# Store the result, put the new component in the other slot...
self.gmm.weight[bestOld[0]] = newWeight
self.gmm.mean[bestOld[0],:] = newMean
self.gmm.prec[bestOld[0],:,:] = newPrec
self.gmm.calcNorm(bestOld[0])
self.gmm.weight[bestOld[1]] = weight
self.gmm.mean[bestOld[1],:] = sample
self.gmm.prec[bestOld[1],:,:] = self.prec
self.gmm.calcNorm(bestOld[1])
# Update the merge weights for both the merged and new kernels...
for i in xrange(self.merge.shape[0]):
if i!=bestOld[0]:
cost = self.__calcMergeCost(self.gmm.weight[i], self.gmm.mean[i,:], self.gmm.prec[i,:,:], self.gmm.weight[bestOld[0]], self.gmm.mean[bestOld[0],:], self.gmm.prec[bestOld[0],:,:])
if i<bestOld[0]: self.merge[bestOld[0],i] = cost
else: self.merge[i,bestOld[0]] = cost
for i in xrange(self.merge.shape[0]):
if i!=bestOld[0] and i!=bestOld[1]:
cost = self.__calcMergeCost(self.gmm.weight[i], self.gmm.mean[i,:], self.gmm.prec[i,:,:], self.gmm.weight[bestOld[1]], self.gmm.mean[bestOld[1],:], self.gmm.prec[bestOld[1],:,:])
if i<bestOld[1]: self.merge[bestOld[1],i] = cost
else: self.merge[i,bestOld[1]] = cost
def marginalise(self, dims):
"""Returns an object on which you can call prob(), but with only a subset of the dimensions. The set of dimensions is given as something that can be interpreted as a numpy array of integers - it is the dimensions to keep, it marginalises away everything else. The indexing of the returned object will match up with that in dims. Note that you must not have any repetitions in dims - that would create absurdity."""
ret = self.gmm.clone()
ret.marginalise(dims)
return ret
| 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.
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
| Python |
# -*- 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
| Python |
# 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
"""
| 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.
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
"""
| 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.
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
| Python |
# -*- 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
| Python |
# 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
"""
| 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.
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
"""
| 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.
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
| Python |
# -*- 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
| Python |
# 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
"""
| 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.
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
"""
| 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.
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
| Python |
# -*- 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
| Python |
# 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
"""
| 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.
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
"""
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.