code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
#! /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 (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
# 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 swood
from utils import doc_gen
# Setup...
doc = doc_gen.DocGen('swood', 'Stochastic Woodland (Depreciated)', 'Basic random forest implimentation (Depreciated)')
doc.addFile('readme.txt', 'Overview')
# Classes...
doc.addClass(swood.SWood)
doc.addClass(swood.DecTree)
| 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 collections import defaultdict
import cPickle as pickle
import bz2
import numpy
import numpy.random
from dec_tree import DecTree
class SWood:
"""A stochastic woodland implimentation (Usually called a random forest:-P). Nothing that fancy - does classification and calculates/provides the out-of-bag error estimate so you can tune the parameters."""
def __init__(self, int_dm, real_dm, cat, tree_count = 128, option_count = 3, minimum_size = 1, weight = None, index = None, callback = None, compress = False):
"""Constructs and trains the stochastic wood - basically all its doing is constructing lots of trees, each with a different bootstrap sample of the input and calculating the out-of-bound error estimates. The parameters are as follows: int_dm & real_dm - the data matrices, one for discrete attributes and one for continuous; you can set one to None if there are none of that kind. cat - The category vector, aligned with the data matrices, where each category is represented by an integer. tree_count - The number of decision trees to create. option_count - The number of attributes to consider at each level of the decision trees - maps to the rand parameter of the DecTree class. minimum_size - Nodes in the trees do not suffer further splits once they are this size or smaller. weight - Optionally allows you to weight the trainning examples, aligned with data matrices. index - Using this you can optionally tell it which examples to use from the other matrices/vectors, and/or duplicate examples. callback - An optional function of the form (steps done,steps overall) used to report progress during construction. compress - if True trees are stored pickled and compressed, in a bid to make them consume less memory - this will obviously destroy classification performance unless multi_classify is used with suitably large blocks. Allows the algorithm to be run with larger quantities of data, but only use as a last resort."""
# Generate weight/index vectors if not provided, and also put in a dummy callback if needed to avoid if statements...
if weight==None: weight = numpy.ones(cat.shape[0], dtype=numpy.float32)
if index==None: index = numpy.arange(cat.shape[0], dtype=numpy.int32)
if callback==None: callback = lambda a, b: None
# Create data structure to calculate the oob error rate...
oob_success = numpy.zeros(cat.shape[0], dtype=numpy.float32)
oob_total = numpy.zeros(cat.shape[0], dtype=numpy.int32)
# Iterate and create all the trees...
self.trees = []
for itr in xrange(tree_count):
callback(itr, tree_count)
# Select the bootstrap sample...
b_ind = numpy.random.randint(index.shape[0], size=index.shape[0])
b_ind.sort() # Should improve cache coherance slightly.
bootstrap = index[b_ind]
# Train the classifier...
dt = DecTree(int_dm, real_dm, cat, weight, bootstrap, option_count, minimum_size)
if compress: self.trees.append(bz2.compress(pickle.dumps(dt)))
else: self.trees.append(dt)
# Get the indices of the oob set...
oob_set = numpy.ones(index.shape[0], dtype=numpy.bool_)
oob_set[b_ind] = False
oob_set = index[oob_set]
# Store the oob info...
for ind in oob_set:
dist = dt.classify(int_dm[ind,:], real_dm[ind,:])
if cat[ind] in dist:
oob_success[ind] += float(dist[cat[ind]]) / float(sum(dist.itervalues()))
oob_total[ind] += 1
# Combine the oob info to calculate the error rate, include being robust to a smaple never being a member of the oob set...
oob_total[oob_total==0] = 1
self.success = (oob_success[index] / oob_total[index]).mean()
del callback # Should not need this, but apparently I do.
def classify(self, int_vec, real_vec):
"""Classifies an example, given the discrete and continuous feature vectors. Returns a dictionary indexed by categories that goes to the probability of that category being assigned; categories can be excluded, implying they have a value of one, but the returned value is actually a default dict setup to return 0.0 when you request an unrecognised key. The probabilities will of course sum to 1."""
ret = defaultdict(float)
for dt in self.trees:
if isinstance(dt,str): dt = pickle.loads(bz2.decompress(dt))
dist = dt.classify(int_vec, real_vec)
distTotal = float(sum(dist.itervalues()))
for cat, weight in dist.iteritems():
w = weight / distTotal
ret[cat] += w
tWeight = len(self.trees)
for cat in ret.iterkeys():
ret[cat] /= tWeight
return ret
def multi_classify(self, int_dm, real_dm, callback = None):
"""Identical to classify, except you give it a data matrix and it classifies each entry in turn, returning a list of distributions. Note that in the cass of using the compressed version of this class using this is essential to be computationally reasonable."""
# Create the output...
if int_dm!=None: size = int_dm.shape[0]
else: size = real_dm.shape[0]
ret = map(lambda _: defaultdict(float), xrange(size))
# Iterate and sum in the effect of each tree in turn, for all samples...
for i,dt in enumerate(self.trees):
if callback: callback(i, len(self.trees))
if isinstance(dt,str): dt = pickle.loads(bz2.decompress(dt))
for ii, prob in enumerate(ret):
dist = dt.classify(int_dm[ii,:] if int_dm!=None else None, real_dm[ii,:] if real_dm!=None else None)
distTotal = float(sum(dist.itervalues()))
for cat, weight in dist.iteritems():
w = weight / distTotal
prob[cat] += w
# Normalise...
tWeight = len(self.trees)
for prob in ret:
for cat in prob.iterkeys():
prob[cat] /= tWeight
# Return...
return ret
def oob_success(self):
"""Returns the success rate ([0.0,1.0], more is better.) for the tree that has been trained. Calculated using the out-of-bag techneque, and primarilly exists so you can run with multiple values of option_count to find the best parameter, or see the effect of tree_count."""
return self.success
def tree_list(self):
"""Returns a list of all the decision trees in the woodland. Note that when in compressed mode these will be strings of bzip2 compressed and pickled trees, which can be resurected using pickle.loads(bz2.decompress(<>))."""
return self.trees
| Python |
# Copyright 2011 Tom SF Haines
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import math
import random
class ConcentrationDP:
"""Represents the concentration parameter of a Dirichlet process - contains the parameters of its prior and updates its estimate as things change. The estimate is actually the mean of many Gibbs samples of the parameter."""
def __init__(self):
"""Initialises with both parameters of the prior set to 1 - i.e. both alpha and beta of the gamma distribution."""
self.conc = 10.0
self.alpha = 1.0
self.beta = 1.0
self.burnIn = 128
self.samples = 128
def setPrior(self, alpha, beta):
"""Sets the alpha and beta parameters of the concentrations gamma prior. They both default to 1."""
self.alpha = alpha
self.beta = beta
def setParms(self, burnIn, samples):
"""Sets the Gibbs sampling parameters for updating the estimate. They both default to 128."""
self.burnIn = burnIn
self.samples = samples
def __resample(self, conc, k, n):
"""Internal method - does a single resampling."""
nn = random.betavariate(conc + 1.0, n)
fAlpha = self.alpha + k
fBeta = self.beta - math.log(nn)
pi_n_mod = (fAlpha - 1.0) / (n * fBeta)
r = random.random()
r_mod = r / (1.0 - r)
if r_mod>=pi_n_mod: fAlpha -= 1.0
return random.gammavariate(fAlpha,fBeta)
def update(self, k, n):
"""Given k, the number of dp instances, and n, the number of samples drawn from the dp, updates and returns the concentration parameter."""
assert(n>=k)
if k>1:
conc = self.conc
for _ in xrange(self.burnIn): conc = self.__resample(conc, k, n)
self.conc = 0.0
for count in xrange(self.samples):
conc = self.__resample(conc, k, n)
self.conc += (conc-self.conc) / float(count+1)
return self.conc
def getConcentration(self):
"""Returns the most recent estimate of the concentration."""
return self.conc
| Python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2012 Tom SF Haines
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from concentration_dp import ConcentrationDP
from pool import Pool, Entity | Python |
# Copyright 2011 Tom SF Haines
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import math
import random
import numpy
import scipy.spatial
import collections
from p_cat.p_cat import ProbCat
from concentration_dp import ConcentrationDP
Entity = collections.namedtuple('Entity', ['sample', 'nll', 'ident'])
class Pool:
"""Represents a pool of entities that can be used for trainning with active learning. Simply contains the entities, their category probabilities and some arbitary identifier (For testing the identifier is often set to be the true category.). Provides active learning methods to extract the entities via various techneques based on the category probabilites. The category probabilites are a dictionary, indexed by category names, and includes 'None' as the probability of it being draw from the prior. Each term consists of P(data|category,model). The many select methods remove an item from the pool based on an active learning approach - the user is then responsible for querying the oracle for its category and updating the model accordingly. Before calling a select method you need to call update to update the probabilities associated with each entity, providing it with the current model, though you can batch things by calling update once before several select calls. The select methods return the named tuple Entity, which is (sample, prob, ident)."""
def __init__(self):
self.entities = [] # Each entity is a 5-list, where the first entry is the thing being stored, the second the associated category nll dictionary, and the third the identifier of the thing, which for testing is often the true category. These are basically Entity objects, but left editable as lists. The 4th item is then the state, used to optimise repeated calls to update, and the 5th is a list of nll dictionaries, for if the classifier supports that.
self.prior = collections.defaultdict(lambda: 1.0)
self.count = None
self.conc = ConcentrationDP()
self.cats = None
def store(self, sample, ident=None):
"""Stores the provided sample into the pool, for later extraction. An arbitary identifier can optionally be provided for testing purposes. The probability distribution is left empty at this time - a call to update will fix that for all objects currently in the pool."""
self.entities.append([sample, None, ident, dict(), None])
def update(self, classifier, dp_ready = True, qbc = False):
"""This is given an object that impliments the ProbCat interface from the p_cat module - it then uses that object to update the probabilities for all entities in the pool. Assumes the sample provided to store can be passed into the getProb method of the classifier. dp_ready should be left True if one of the select methods that involves dp's is going to be called, so it can update the concentration. qbc needs to be set True if methods based on query by comittee are to be used."""
for entity in self.entities:
entity[1] = classifier.getDataNLL(entity[0], entity[3])
if classifier.listMode() and qbc:
entity[4] = classifier.getDataNLLList(entity[0], entity[3])
self.count = dict(classifier.getCatCounts())
if dp_ready: self.conc.update(len(self.count), sum(self.count.itervalues()))
self.cats = classifier.getCatList()
def empty(self):
"""For testing if the pool is empty."""
return len(self.entities)==0
def size(self):
"""Returns how many entities are currently stored."""
return len(self.entities)
def data(self):
"""Returns the Entity objects representing the current pool, as a list. Safe to edit."""
return map(lambda r: Entity._make(r[:3]), self.entities)
def getConcentration(self):
"""Pass through to get the DP concentration."""
return self.conc.getConcentration()
def setPrior(self, prior=None):
"""Sets the prior used to swap P(data|class) by some select methods - if not provided a uniform prior is used. Automatically normalised."""
if prior!=None:
self.prior = dict(prior)
div = float(sum(self.prior.values()))
for key in self.prior.iterkeys(): self.prior[key] /= div
else:
self.prior = collections.defaultdict(lambda: 1.0)
def selectRandom(self):
"""Returns an Entity randomly - effectivly the dumbest possible algorithm, though it has a nasty habit of doing quite well."""
pos = random.randrange(len(self.entities))
ret = self.entities[pos]
self.entities = self.entities[:pos] + self.entities[pos+1:]
return Entity._make(ret[:3])
def selectRandomIdent(self, ident):
"""Selects randomly from all entities in the pool with the given identifier. It is typically used when the identifiers are the true categories, to compare with algorithms that are not capable of making a first choice, where the authors of the test have fixed the first item to be drawn. Obviously this is cheating, but it is sometimes required to do a fair comparison."""
selFrom = []
for i,entity in enumerate(self.entities):
if entity[2]==ident:
selFrom.append(i)
pos = random.randrange(len(selFrom))
pos = selFrom[pos]
ret = self.entities[pos]
self.entities = self.entities[:pos] + self.entities[pos+1:]
return Entity._make(ret[:3])
def selectOutlier(self, beta = None):
"""Returns the least likelly member. You can also make it probalistic by providing a beta value - it then weights the samples by exp(-beta * outlier) for random selection."""
if len(self.cats)==0: return self.selectRandom()
ll = numpy.empty(len(self.entities), dtype=numpy.float32)
ll[:] = -1e64
for i, entity in enumerate(self.entities):
llbc = numpy.array([numpy.log(self.prior[x[0]])-x[1] for x in entity[1].iteritems() if x[0]!=None], dtype=numpy.float32)
high = llbc.max()
ll[i] = high + numpy.log(numpy.exp(llbc-high).sum())
if beta==None:
pos = numpy.argmin(ll)
else:
prob = numpy.exp(ll)
prob *= -beta
prob = numpy.exp(prob)
r = random.random() * prob.sum()
pos = 0
while pos<(prob.shape[0]-1):
r -= prob[pos]
if r<0.0: break
pos += 1
ret = self.entities[pos]
self.entities = self.entities[:pos] + self.entities[pos+1:]
return Entity._make(ret[:3])
def selectEntropy(self, beta = None):
"""Selects the sample with the greatest entropy - the most common uncertainty-based sampling method. If beta is provided instead of selecting the maximum it makes a random selection by weighting each sample by exp(-beta * entropy)."""
if len(self.cats)==0: return self.selectRandom()
ent = numpy.empty(len(self.entities), dtype=numpy.float32)
for i, entity in enumerate(self.entities):
llbc = numpy.array([numpy.log(self.prior[x[0]])-x[1] for x in entity[1].iteritems() if x[0]!=None], dtype=numpy.float32)
high = llbc.max()
log_div = high + numpy.log(numpy.exp(llbc-high).sum())
ent[i] = -(numpy.exp(llbc - log_div) * (llbc - log_div)).sum()
if beta==None:
pos = numpy.argmax(ent)
else:
ent *= -beta
ent = numpy.exp(ent)
r = random.random() * ent.sum()
pos = 0
while pos<(ent.shape[0]-1):
r -= ent[pos]
if r<0.0: break
pos += 1
ret = self.entities[pos]
self.entities = self.entities[:pos] + self.entities[pos+1:]
return Entity._make(ret[:3])
def selectDP(self, hardChoice = False):
"""Selects the entity, that, according to the DP assumption, is most likelly to be an instance of a new class. Can be made to select randomly, using the probabilities as weights, or to simply select the entry with the highest probability of being new."""
# Calculate the P(new) probabilities...
prob = numpy.empty(len(self.entities))
for i, entity in enumerate(self.entities):
new = numpy.log(self.conc.getConcentration()) - entity[1][None]
lla = numpy.array([new] + [numpy.log(self.prior[x[0]])-x[1] for x in entity[1].iteritems() if x[0]!=None], dtype=numpy.float32)
high = llbc.max()
lla_sum = high + numpy.log(numpy.exp(llbc-high).sum())
prob[i] = new - div
# Select an entry...
if hardChoice: pos = numpy.argmax(prob)
else:
prob -= prob.max()
prob = numpy.exp(prob)
r = random.random() * prob.sum()
pos = 0
while pos<(prob.shape[0]-1):
r -= prob[pos]
if r<0.0: break
pos += 1
# Remove it from the pool, package it up and return it...
ret = self.entities[pos]
self.entities = self.entities[:pos] + self.entities[pos+1:]
return Entity._make(ret[:3])
def selectWrong(self, softSelect = False, hardChoice = False, dp = True, dw = False, sd = None):
"""24 different selection strategies, all rolled into one. Bite me! All work on the basis of selecting the entity in the pool with the greatest chance of being misclassified by the current classifier. There are four binary flags that control the behaviour, and their defaults match up with the algorithm presented in the paper 'Active Learning using Dirichlet Processes for Rare Class Discovery and Classification'. softSelect indicates if the classifier selects the category with the highest probability (False) or selects the category probalistically from P(class|data) (True). hardChoice comes into play once P(wrong) has been calculated for each entity in the pool - when True the entity with the highest P(wrong) is selected, otherwise the P(wrong) are used as weights for a probabilistic selection. dp indicates if the Dirichlet process assumption is to be used, such that we consider the probability that the entity belongs to a new category in addition to the existing categories. Note that the classifier cannot select an unknown class, so an entity with a high probability of belonging to a new class has a high P(wrong) score when the dp assumption is True. dw indicates if it should weight the metric by a density estimate over the data set, and hence bias selection towards areas with lots of samples. Appendum: Also supports expected hinge loss, if you set softSelect to None (False is equivalent to expected 0-1 loss, True to something without a name.). If sd is not None then the wrong score for each entity is boosted by neighbours, on the grounds that knowing about an entity will affect its neighbours classification - its uses the unnormalised weighting of a Gaussian (The centre carries a weight of 1.) with the given sd."""
if len(self.cats)==0 and dp==False: return self.selectRandom()
wrong = numpy.ones(len(self.entities))
for i, entity in enumerate(self.entities):
# Calculate the probability of selecting each of the known classes...
llSel = dict()
for cat, p in entity[1].iteritems():
if cat!=None:
llSel[cat] = numpy.log(self.prior[cat]) - p
if len(llSel)>0:
vals = numpy.array(llSel.values())
high = vals.max()
div = high + numpy.log(numpy.exp(vals-high).sum())
for cat in llSel.iterkeys(): llSel[cat] -= div
# Calculate the probability of it being each of the options...
llIs = dict()
for cat, p in entity[1].iteritems():
if cat!=None or dp:
w = self.count[cat] if cat!=None else self.conc.getConcentration()
llIs[cat] = numpy.log(w) - p
vals = numpy.array(llIs.values())
high = vals.max()
div = high + numpy.log(numpy.exp(vals-high).sum())
for cat in llIs.iterkeys(): llIs[cat] -= div
# Calculate the probability of getting it wrong...
if softSelect==None: # 1 - Expected hinge loss, sort of.
if len(llSel)>0: maxSel = max(llSel.itervalues())
else: maxSel = 0.0
wrong[i] -= numpy.exp(maxSel + llIs[None])
for cat, p in llSel.iteritems():
wrong[i] -= numpy.exp(maxSel + llIs[cat]) - numpy.exp(p + llIs[cat])
elif softSelect:
for cat, p in probSel.iteritems():
wrong[i] -= numpy.exp(p + llIs[cat])
else:
best = -1.0
for cat, p in llSel.iteritems():
if p>best:
best = p
wrong[i] = 1.0 - numpy.exp(llIs[cat])
# If requested include a weighting by density...
if dw: wrong[i] *= numpy.log(-entity[1][None])
# If requested weight nodes by their neighbours...
if sd!=None:
feats = numpy.array(map(lambda e: e[0], self.entities), dtype=numpy.float32)
dm = scipy.spatial.distance.squareform(scipy.spatial.distance.pdist(feats))
dm = numpy.exp((-0.5/(sd*sd))*numpy.square(dm))
dm *= wrong.reshape((1,-1))
wrong[:] = dm.sum(axis=1)
# Choose which entitiy from the pool is to be the choosen one...
if hardChoice:
pos = numpy.argmax(wrong)
else:
r = random.random() * wrong.sum()
pos = 0
while pos<(wrong.shape[0]-1):
r -= wrong[pos]
if r<0.0: break
pos += 1
# Return the choosen one...
ret = self.entities[pos]
self.entities = self.entities[:pos] + self.entities[pos+1:]
return Entity._make(ret[:3])
def selectWrongQBC(self, softSelect = False, hardChoice = False, dp = True, dw = False):
"""A query by comittee version of selectWrong - its parameters are equivalent. Requires that update is called with qbc set to True."""
if len(self.cats)==0 and dp==False: return self.selectRandom()
wrong = numpy.zeros(len(self.entities))
for i, entity in enumerate(self.entities):
# Calculate a list of estimates of the probability of selecting each of the known classes...
llSelList = []
for ll in entity[4]:
llSel = dict()
for cat, p in ll.iteritems():
if cat!=None:
llSel[cat] = numpy.log(self.prior[cat]) - p
if len(llSel)>0:
vals = numpy.array(llSel.values())
high = vals.max()
div = high + numpy.log(numpy.exp(vals-high).sum())
for cat in llSel.iterkeys(): llSel[cat] -= div
llSelList.append(llSel)
# Calculate a list of estimates of the probability of it being each of the options...
llIsList = []
for ll in entity[4]:
llIs = dict()
for cat, p in ll.iteritems():
if cat!=None or dp:
w = self.count[cat] if cat!=None else self.conc.getConcentration()
llIs[cat] = numpy.log(w) - p
vals = numpy.array(llIs.values())
high = vals.max()
div = high + numpy.log(numpy.exp(vals-high).sum())
for cat in llIs.iterkeys(): llIs[cat] -= div
llIsList.append(llIs)
# Now do the combinatorics of the two lists to generate a P(wrong) estimate for each pair, for which the average is taken...
for llSel in llSelList:
for llIs in llIsList:
if softSelect==None: # 1 - Expected hinge loss, sort of.
if len(llSel)>0: maxSel = max(llSel.itervalues())
else: maxSel = 0.0
w = 1.0 - numpy.exp(maxSel + llIs[None])
for cat, p in llSel.iteritems():
w -= numpy.exp(maxSel + llIs[cat]) - numpy.exp(p + llIs[cat])
elif softSelect:
w = 1.0
for cat, p in probSel.iteritems():
w -= numpy.exp(p + llIs[cat])
else:
best = -1.0
w = 0.0
for cat, p in llSel.iteritems():
if p>best:
best = p
w = 1.0 - numpy.exp(llIs[cat])
wrong[i] += w
wrong[i] /= len(llSelList) * len(llIsList)
# If requested include a weighting by density...
if dw: wrong[i] *= numpy.log(-entity[1][None])
if hardChoice:
pos = numpy.argmax(wrong)
else:
r = random.random() * wrong.sum()
pos = 0
while pos<(wrong.shape[0]-1):
r -= wrong[pos]
if r<0.0: break
pos += 1
ret = self.entities[pos]
self.entities = self.entities[:pos] + self.entities[pos+1:]
return Entity._make(ret[:3])
@staticmethod
def methods(incQBC = False):
"""Returns a list of the method names that can be passed to the select method. Read the select method to work out which they each are. p_wrong_soft is the published techneque. By default it does not include the query by comittee versions, which can be switched on using the relevent flag."""
return ['random', 'outlier', 'entropy', 'p_new_hard', 'p_new_soft', 'p_wrong_hard', 'p_wrong_soft', 'p_wrong_hard_pcat', 'p_wrong_soft_pcat', 'p_wrong_hard_naive', 'p_wrong_soft_naive', 'p_wrong_hard_pcat_naive', 'p_wrong_soft_pcat_naive', 'dxp_wrong_hard', 'dxp_wrong_soft', 'dxp_wrong_hard_pcat', 'dxp_wrong_soft_pcat', 'dxp_wrong_hard_naive', 'dxp_wrong_soft_naive', 'dxp_wrong_hard_pcat_naive', 'dxp_wrong_soft_pcat_naive', 'p_wrong_hard_hinge', 'p_wrong_soft_hinge', 'p_wrong_hard_hinge_naive', 'p_wrong_soft_hinge_naive', 'dxp_wrong_hard_hinge', 'dxp_wrong_soft_hinge', 'dxp_wrong_hard_hinge_naive', 'dxp_wrong_soft_hinge_naive'] + ([] if incQBC==False else ['qbc_p_wrong_hard', 'qbc_p_wrong_soft', 'qbc_p_wrong_hard_pcat', 'qbc_p_wrong_soft_pcat', 'qbc_p_wrong_hard_naive', 'qbc_p_wrong_soft_naive', 'qbc_p_wrong_hard_pcat_naive', 'qbc_p_wrong_soft_pcat_naive', 'qbc_dxp_wrong_hard', 'qbc_dxp_wrong_soft', 'qbc_dxp_wrong_hard_pcat', 'qbc_dxp_wrong_soft_pcat', 'qbc_dxp_wrong_hard_naive', 'qbc_dxp_wrong_soft_naive', 'qbc_dxp_wrong_hard_pcat_naive', 'qbc_dxp_wrong_soft_pcat_naive', 'qbc_p_wrong_hard_hinge', 'qbc_p_wrong_soft_hinge', 'qbc_p_wrong_hard_hinge_naive', 'qbc_p_wrong_soft_hinge_naive', 'qbc_dxp_wrong_hard_hinge', 'qbc_dxp_wrong_soft_hinge', 'qbc_dxp_wrong_hard_hinge_naive', 'qbc_dxp_wrong_soft_hinge_naive'])
def select(self, method, sd = None):
"""Pass through for all of the select methods that have no problamatic parameters - allows you to select the method using a string. You can get a list of all method strings from the methods() method. Actually, allows you to provide a sd parameter for the P(wrong) methods that support it."""
if method=='random': return self.selectRandom()
elif method=='outlier': return self.selectOutlier()
elif method=='entropy': return self.selectEntropy()
elif method=='p_new_hard': return self.selectDP(True)
elif method=='p_new_soft': return self.selectDP(False)
elif method=='p_wrong_hard': return self.selectWrong(False,True,True,False,sd)
elif method=='p_wrong_soft': return self.selectWrong(False,False,True,False,sd)
elif method=='p_wrong_hard_pcat': return self.selectWrong(True,True,True,False,sd)
elif method=='p_wrong_soft_pcat': return self.selectWrong(True,False,True,False,sd)
elif method=='p_wrong_hard_naive': return self.selectWrong(False,True,False,False,sd)
elif method=='p_wrong_soft_naive': return self.selectWrong(False,False,False,False,sd)
elif method=='p_wrong_hard_pcat_naive': return self.selectWrong(True,True,False,False,sd)
elif method=='p_wrong_soft_pcat_naive': return self.selectWrong(True,False,False,False,sd)
elif method=='dxp_wrong_hard': return self.selectWrong(False,True,True,True,sd)
elif method=='dxp_wrong_soft': return self.selectWrong(False,False,True,True,sd)
elif method=='dxp_wrong_hard_pcat': return self.selectWrong(True,True,True,True,sd)
elif method=='dxp_wrong_soft_pcat': return self.selectWrong(True,False,True,True,sd)
elif method=='dxp_wrong_hard_naive': return self.selectWrong(False,True,False,True,sd)
elif method=='dxp_wrong_soft_naive': return self.selectWrong(False,False,False,True,sd)
elif method=='dxp_wrong_hard_pcat_naive': return self.selectWrong(True,True,False,True,sd)
elif method=='dxp_wrong_soft_pcat_naive': return self.selectWrong(True,False,False,True,sd)
elif method=='p_wrong_hard_hinge': return self.selectWrong(None,True,True,False,sd)
elif method=='p_wrong_soft_hinge': return self.selectWrong(None,False,True,False,sd)
elif method=='p_wrong_hard_hinge_naive': return self.selectWrong(None,True,False,False,sd)
elif method=='p_wrong_soft_hinge_naive': return self.selectWrong(None,False,False,False,sd)
elif method=='dxp_wrong_hard_hinge': return self.selectWrong(None,True,True,True,sd)
elif method=='dxp_wrong_soft_hinge': return self.selectWrong(None,False,True,True,sd)
elif method=='dxp_wrong_hard_hinge_naive': return self.selectWrong(None,True,False,True,sd)
elif method=='dxp_wrong_soft_hinge_naive': return self.selectWrong(None,False,False,True,sd)
elif method=='qbc_p_wrong_hard': return self.selectWrongQBC(False,True,True,False)
elif method=='qbc_p_wrong_soft': return self.selectWrongQBC(False,False,True,False)
elif method=='qbc_p_wrong_hard_pcat': return self.selectWrongQBC(True,True,True,False)
elif method=='qbc_p_wrong_soft_pcat': return self.selectWrongQBC(True,False,True,False)
elif method=='qbc_p_wrong_hard_naive': return self.selectWrongQBC(False,True,False,False)
elif method=='qbc_p_wrong_soft_naive': return self.selectWrongQBC(False,False,False,False)
elif method=='qbc_p_wrong_hard_pcat_naive': return self.selectWrongQBC(True,True,False,False)
elif method=='qbc_p_wrong_soft_pcat_naive': return self.selectWrongQBC(True,False,False,False)
elif method=='qbc_dxp_wrong_hard': return self.selectWrongQBC(False,True,True,True)
elif method=='qbc_dxp_wrong_soft': return self.selectWrongQBC(False,False,True,True)
elif method=='qbc_dxp_wrong_hard_pcat': return self.selectWrongQBC(True,True,True,True)
elif method=='qbc_dxp_wrong_soft_pcat': return self.selectWrongQBC(True,False,True,True)
elif method=='qbc_dxp_wrong_hard_naive': return self.selectWrongQBC(False,True,False,True)
elif method=='qbc_dxp_wrong_soft_naive': return self.selectWrongQBC(False,False,False,True)
elif method=='qbc_dxp_wrong_hard_pcat_naive': return self.selectWrongQBC(True,True,False,True)
elif method=='qbc_dxp_wrong_soft_pcat_naive': return self.selectWrongQBC(True,False,False,True)
elif method=='qbc_p_wrong_hard_hinge': return self.selectWrongQBC(None,True,True,False)
elif method=='qbc_p_wrong_soft_hinge': return self.selectWrongQBC(None,False,True,False)
elif method=='qbc_p_wrong_hard_hinge_naive': return self.selectWrongQBC(None,True,False,False)
elif method=='qbc_p_wrong_soft_hinge_naive': return self.selectWrongQBC(None,False,False,False)
elif method=='qbc_dxp_wrong_hard_hinge': return self.selectWrongQBC(None,True,True,True)
elif method=='qbc_dxp_wrong_soft_hinge': return self.selectWrongQBC(None,False,True,True)
elif method=='qbc_dxp_wrong_hard_hinge_naive': return self.selectWrongQBC(None,True,False,True)
elif method=='qbc_dxp_wrong_soft_hinge_naive': return self.selectWrongQBC(None,False,False,True)
else: raise Exception('Unknown selection method')
| 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 os.path
import pickle
import numpy
class Iris1D:
"""1D interface to the iris data set - uses pca to make it a 1D problem that is good for extremelly simple tests/demonstrations."""
def __init__(self):
# First load the data from the file...
directory = os.path.dirname(os.path.abspath(__file__))
filename = os.path.join(directory, 'iris.data')
lines = open(filename, 'r').readlines()
lines = lines[:-1] # Last line is empty
data_mat = numpy.empty((len(lines),4), dtype=numpy.float32)
str_to_int = dict()
self.ans = numpy.empty(len(lines), dtype=numpy.uint8)
for i, line in enumerate(lines):
parts = line.split(',')
data_mat[i,:] = map(float, parts[:4])
cat = parts[-1]
if cat not in str_to_int: str_to_int[cat] = len(str_to_int)
self.ans[i] = str_to_int[cat]
# Normalise it...
data_mat -= data_mat.mean(axis=0)
data_mat /= numpy.abs(data_mat).mean(axis=0)
# Calculate the pca matrix...
u, _, _ = numpy.linalg.svd(data_mat, full_matrices=False)
pca_mat = u[0,:]
# Apply the 'matrix' to all the instances, to create the final data structure...
self.vec = numpy.empty(len(lines), dtype=numpy.float32)
for i in xrange(len(lines)):
self.vec[i] = numpy.dot(pca_mat, data_mat[i,:])
def getVectors(self):
"""Returns a numpy vector of float32 that contains the single parameter extracted from PCA for each entry."""
return self.vec
def getClasses(self):
"""Returns the class represented by each parameter - a numpy array of uint8, containing {0,1,2}."""
return self.ans
| 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 |
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.