code stringlengths 1 1.49M | vector listlengths 0 7.38k | snippet listlengths 0 7.38k |
|---|---|---|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from ctypes import *
def setProcName(name):
"""Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases."""
# Call the process control function...
libc = cdll.LoadLibrary('libc.so.6')
libc.prctl(15, c_char_p(name), 0, 0, 0)
# Update argv...
charPP = POINTER(POINTER(c_char))
argv = charPP.in_dll(libc,'_dl_argv')
size = libc.strlen(argv[0])
libc.strncpy(argv[0],c_char_p(name),size)
if __name__=='__main__':
# Quick test that it works...
import os
ps1 = 'ps'
ps2 = 'ps -f'
os.system(ps1)
os.system(ps2)
setProcName('wibble_wobble')
os.system(ps1)
os.system(ps2)
| [
[
1,
0,
0.3636,
0.0227,
0,
0.66,
0,
182,
0,
1,
0,
0,
182,
0,
0
],
[
2,
0,
0.5682,
0.25,
0,
0.66,
0.5,
903,
0,
1,
0,
0,
0,
0,
9
],
[
8,
1,
0.4773,
0.0227,
1,
0.84,
... | [
"from ctypes import *",
"def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import multiprocessing as mp
import multiprocessing.synchronize # To make sure we have all the functionality.
import types
import marshal
import unittest
def repeat(x):
"""A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant."""
while True: yield x
def run_code(code,args):
"""Internal use function that does the work in each process."""
code = marshal.loads(code)
func = types.FunctionType(code, globals(), '_')
return func(*args)
def mp_map(func, *iters, **keywords):
"""A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity."""
if 'pool' in keywords: pool = keywords['pool']
else: pool = mp.Pool()
code = marshal.dumps(func.func_code)
jobs = []
for args in zip(*iters):
jobs.append(pool.apply_async(run_code,(code,args)))
for i in xrange(len(jobs)):
jobs[i] = jobs[i].get()
return jobs
class TestMpMap(unittest.TestCase):
def test_simple1(self):
data = ['a','b','c','d']
def noop(data):
return data
data_noop = mp_map(noop, data)
self.assertEqual(data, data_noop)
def test_simple2(self):
data = [x for x in xrange(1000)]
data_double = mp_map(lambda a: a*2, data)
self.assertEqual(map(lambda a: a*2,data), data_double)
def test_gen(self):
def gen():
for i in xrange(100): yield i
data_double = mp_map(lambda a: a*2, gen())
self.assertEqual(map(lambda a: a*2,gen()), data_double)
def test_repeat(self):
def mult(a,b):
return a*b
data = [x for x in xrange(50,5000,5)]
data_triple = mp_map(mult, data, repeat(3))
self.assertEqual(map(lambda a: a*3,data),data_triple)
def test_none(self):
data = []
data_sqr = mp_map(lambda x: x*x, data)
self.assertEqual([],data_sqr)
if __name__ == '__main__':
unittest.main()
| [
[
1,
0,
0.1456,
0.0097,
0,
0.66,
0,
901,
0,
1,
0,
0,
901,
0,
0
],
[
1,
0,
0.1553,
0.0097,
0,
0.66,
0.1111,
99,
0,
1,
0,
0,
99,
0,
0
],
[
1,
0,
0.1748,
0.0097,
0,
0.... | [
"import multiprocessing as mp",
"import multiprocessing.synchronize # To make sure we have all the functionality.",
"import types",
"import marshal",
"import unittest",
"def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Defines helper functions for accessing numpy arrays...
numpy_util_code = start_cpp() + """
#ifndef NUMPY_UTIL_CODE
#define NUMPY_UTIL_CODE
float & Float1D(PyArrayObject * arr, int index = 0)
{
return *(float*)(arr->data + index*arr->strides[0]);
}
float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
unsigned char & Byte1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index*arr->strides[0]);
}
unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
int & Int1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index*arr->strides[0]);
}
int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
#endif
"""
| [
[
1,
0,
0.1923,
0.0128,
0,
0.66,
0,
972,
0,
1,
0,
0,
972,
0,
0
],
[
14,
0,
0.6282,
0.7564,
0,
0.66,
1,
799,
4,
0,
0,
0,
0,
0,
1
]
] | [
"from utils.start_cpp import start_cpp",
"numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}"
] |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import cvarray
import mp_map
import prog_bar
import numpy_help_cpp
import python_obj_cpp
import matrix_cpp
import gamma_cpp
import setProcName
import start_cpp
import make
import doc_gen
# Setup...
doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.')
doc.addFile('readme.txt', 'Overview')
# Variables...
doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.')
doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.')
doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++')
doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++')
# Functions...
doc.addFunction(make.make_mod)
doc.addFunction(cvarray.cv2array)
doc.addFunction(cvarray.array2cv)
doc.addFunction(mp_map.repeat)
doc.addFunction(mp_map.mp_map)
doc.addFunction(setProcName.setProcName)
doc.addFunction(start_cpp.start_cpp)
doc.addFunction(make.make_mod)
# Classes...
doc.addClass(prog_bar.ProgBar)
doc.addClass(doc_gen.DocGen)
| [
[
1,
0,
0.2857,
0.0179,
0,
0.66,
0,
192,
0,
1,
0,
0,
192,
0,
0
],
[
1,
0,
0.3036,
0.0179,
0,
0.66,
0.0385,
905,
0,
1,
0,
0,
905,
0,
0
],
[
1,
0,
0.3214,
0.0179,
0,
... | [
"import cvarray",
"import mp_map",
"import prog_bar",
"import numpy_help_cpp",
"import python_obj_cpp",
"import matrix_cpp",
"import gamma_cpp",
"import setProcName",
"import start_cpp",
"import make",
"import doc_gen",
"doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc... |
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest
import random
import math
from scipy.special import gammaln, psi, polygamma
from scipy import weave
from utils.start_cpp import start_cpp
# Provides various gamma-related functions...
gamma_code = start_cpp() + """
#ifndef GAMMA_CODE
#define GAMMA_CODE
#include <cmath>
// Returns the natural logarithm of the Gamma function...
// (Uses Lanczos's approximation.)
double lnGamma(double z)
{
static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};
if (z<0.5)
{
// Use reflection formula, as approximation doesn't work down here...
return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z);
}
else
{
double x = coeff[0];
for (int i=1;i<9;i++) x += coeff[i]/(z+i-1);
double t = z + 6.5;
return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x);
}
}
// Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values...
double digamma(double z)
{
static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point.
double ret = 0.0;
while (z<highVal)
{
ret -= 1.0/z;
z += 1.0;
}
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz4 = iz2*iz2;
double iz6 = iz4*iz2;
ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0;
return ret;
}
// Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically...
double trigamma(double z)
{
static const double highVal = 8.0;
double ret = 0.0;
while (z<highVal)
{
ret += 1.0/(z*z);
z += 1.0;
}
z -= 1.0;
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz3 = iz1*iz2;
double iz5 = iz3*iz2;
double iz7 = iz5*iz2;
double iz9 = iz7*iz2;
ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0;
return ret;
}
#endif
"""
def lnGamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function"""
code = start_cpp(gamma_code) + """
return_val = lnGamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def digamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function"""
code = start_cpp(gamma_code) + """
return_val = digamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def trigamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function"""
code = start_cpp(gamma_code) + """
return_val = trigamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
class TestFuncs(unittest.TestCase):
"""Test code for the assorted gamma-related functions."""
def test_compile(self):
code = start_cpp(gamma_code) + """
"""
weave.inline(code, support_code=gamma_code)
def test_error_lngamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = lnGamma(z)
good = gammaln(z)
assert(math.fabs(own-good)<1e-12)
def test_error_digamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = digamma(z)
good = psi(z)
assert(math.fabs(own-good)<1e-9)
def test_error_trigamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = trigamma(z)
good = polygamma(1,z)
assert(math.fabs(own-good)<1e-9)
# If this file is run do the unit tests...
if __name__ == '__main__':
unittest.main()
| [
[
1,
0,
0.0818,
0.0063,
0,
0.66,
0,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.0881,
0.0063,
0,
0.66,
0.0909,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0943,
0.0063,
0,
0.... | [
"import unittest",
"import random",
"import math",
"from scipy.special import gammaln, psi, polygamma",
"from scipy import weave",
"from utils.start_cpp import start_cpp",
"gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o... |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import inspect
import hashlib
def start_cpp(hash_str = None):
"""This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>"""
frame = inspect.currentframe().f_back
info = inspect.getframeinfo(frame)
if hash_str==None:
return '#line %i "%s"\n'%(info[1],info[0])
else:
h = hashlib.md5()
h.update(hash_str)
hash_val = h.hexdigest()
return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
| [
[
1,
0,
0.5,
0.0333,
0,
0.66,
0,
878,
0,
1,
0,
0,
878,
0,
0
],
[
1,
0,
0.5333,
0.0333,
0,
0.66,
0.5,
154,
0,
1,
0,
0,
154,
0,
0
],
[
2,
0,
0.8333,
0.3667,
0,
0.66,
... | [
"import inspect",
"import hashlib",
"def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work... |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os.path
import tempfile
import shutil
from distutils.core import setup, Extension
import distutils.ccompiler
import distutils.dep_util
try:
__default_compiler = distutils.ccompiler.new_compiler()
except:
__default_compiler = None
def make_mod(name, base, source, openCL = False):
"""Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place."""
if __default_compiler==None: raise Exception('No compiler!')
# Work out the various file names - check if we actually need to do anything...
if not isinstance(source, list): source = [source]
source_path = map(lambda s: os.path.join(base, s), source)
library_path = os.path.join(base, __default_compiler.shared_object_filename(name))
if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)):
try:
print 'b'
# Backup the argv variable and create a temporary directory to do all work in...
old_argv = sys.argv[:]
temp_dir = tempfile.mkdtemp()
# Prepare the extension...
sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir]
comp_path = filter(lambda s: not s.endswith('.h'), source_path)
depends = filter(lambda s: s.endswith('.h'), source_path)
if openCL:
ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends)
else:
ext = Extension(name, comp_path, depends=depends)
# Compile...
setup(name=name, version='1.0.0', ext_modules=[ext])
finally:
# Cleanup the argv variable and the temporary directory...
sys.argv = old_argv
shutil.rmtree(temp_dir, True)
| [
[
1,
0,
0.2031,
0.0156,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.2188,
0.0156,
0,
0.66,
0.125,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.2344,
0.0156,
0,
0.6... | [
"import sys",
"import os.path",
"import tempfile",
"import shutil",
"from distutils.core import setup, Extension",
"import distutils.ccompiler",
"import distutils.dep_util",
"try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None",
" __default_compiler... |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| [
[
1,
0,
0.0634,
0.0049,
0,
0.66,
0,
291,
0,
1,
0,
0,
291,
0,
0
],
[
1,
0,
0.0683,
0.0049,
0,
0.66,
0.5,
878,
0,
1,
0,
0,
878,
0,
0
],
[
3,
0,
0.5439,
0.9171,
0,
0.6... | [
"import pydoc",
"import inspect",
"class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from ctypes import *
def setProcName(name):
"""Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases."""
# Call the process control function...
libc = cdll.LoadLibrary('libc.so.6')
libc.prctl(15, c_char_p(name), 0, 0, 0)
# Update argv...
charPP = POINTER(POINTER(c_char))
argv = charPP.in_dll(libc,'_dl_argv')
size = libc.strlen(argv[0])
libc.strncpy(argv[0],c_char_p(name),size)
if __name__=='__main__':
# Quick test that it works...
import os
ps1 = 'ps'
ps2 = 'ps -f'
os.system(ps1)
os.system(ps2)
setProcName('wibble_wobble')
os.system(ps1)
os.system(ps2)
| [
[
1,
0,
0.3636,
0.0227,
0,
0.66,
0,
182,
0,
1,
0,
0,
182,
0,
0
],
[
2,
0,
0.5682,
0.25,
0,
0.66,
0.5,
903,
0,
1,
0,
0,
0,
0,
9
],
[
8,
1,
0.4773,
0.0227,
1,
0.94,
... | [
"from ctypes import *",
"def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import multiprocessing as mp
import multiprocessing.synchronize # To make sure we have all the functionality.
import types
import marshal
import unittest
def repeat(x):
"""A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant."""
while True: yield x
def run_code(code,args):
"""Internal use function that does the work in each process."""
code = marshal.loads(code)
func = types.FunctionType(code, globals(), '_')
return func(*args)
def mp_map(func, *iters, **keywords):
"""A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity."""
if 'pool' in keywords: pool = keywords['pool']
else: pool = mp.Pool()
code = marshal.dumps(func.func_code)
jobs = []
for args in zip(*iters):
jobs.append(pool.apply_async(run_code,(code,args)))
for i in xrange(len(jobs)):
jobs[i] = jobs[i].get()
return jobs
class TestMpMap(unittest.TestCase):
def test_simple1(self):
data = ['a','b','c','d']
def noop(data):
return data
data_noop = mp_map(noop, data)
self.assertEqual(data, data_noop)
def test_simple2(self):
data = [x for x in xrange(1000)]
data_double = mp_map(lambda a: a*2, data)
self.assertEqual(map(lambda a: a*2,data), data_double)
def test_gen(self):
def gen():
for i in xrange(100): yield i
data_double = mp_map(lambda a: a*2, gen())
self.assertEqual(map(lambda a: a*2,gen()), data_double)
def test_repeat(self):
def mult(a,b):
return a*b
data = [x for x in xrange(50,5000,5)]
data_triple = mp_map(mult, data, repeat(3))
self.assertEqual(map(lambda a: a*3,data),data_triple)
def test_none(self):
data = []
data_sqr = mp_map(lambda x: x*x, data)
self.assertEqual([],data_sqr)
if __name__ == '__main__':
unittest.main()
| [
[
1,
0,
0.1456,
0.0097,
0,
0.66,
0,
901,
0,
1,
0,
0,
901,
0,
0
],
[
1,
0,
0.1553,
0.0097,
0,
0.66,
0.1111,
99,
0,
1,
0,
0,
99,
0,
0
],
[
1,
0,
0.1748,
0.0097,
0,
0.... | [
"import multiprocessing as mp",
"import multiprocessing.synchronize # To make sure we have all the functionality.",
"import types",
"import marshal",
"import unittest",
"def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Defines helper functions for accessing numpy arrays...
numpy_util_code = start_cpp() + """
#ifndef NUMPY_UTIL_CODE
#define NUMPY_UTIL_CODE
float & Float1D(PyArrayObject * arr, int index = 0)
{
return *(float*)(arr->data + index*arr->strides[0]);
}
float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
unsigned char & Byte1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index*arr->strides[0]);
}
unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
int & Int1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index*arr->strides[0]);
}
int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
#endif
"""
| [
[
1,
0,
0.1923,
0.0128,
0,
0.66,
0,
972,
0,
1,
0,
0,
972,
0,
0
],
[
14,
0,
0.6282,
0.7564,
0,
0.66,
1,
799,
4,
0,
0,
0,
0,
0,
1
]
] | [
"from utils.start_cpp import start_cpp",
"numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}"
] |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import cvarray
import mp_map
import prog_bar
import numpy_help_cpp
import python_obj_cpp
import matrix_cpp
import gamma_cpp
import setProcName
import start_cpp
import make
import doc_gen
# Setup...
doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.')
doc.addFile('readme.txt', 'Overview')
# Variables...
doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.')
doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.')
doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++')
doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++')
# Functions...
doc.addFunction(make.make_mod)
doc.addFunction(cvarray.cv2array)
doc.addFunction(cvarray.array2cv)
doc.addFunction(mp_map.repeat)
doc.addFunction(mp_map.mp_map)
doc.addFunction(setProcName.setProcName)
doc.addFunction(start_cpp.start_cpp)
doc.addFunction(make.make_mod)
# Classes...
doc.addClass(prog_bar.ProgBar)
doc.addClass(doc_gen.DocGen)
| [
[
1,
0,
0.2857,
0.0179,
0,
0.66,
0,
192,
0,
1,
0,
0,
192,
0,
0
],
[
1,
0,
0.3036,
0.0179,
0,
0.66,
0.0385,
905,
0,
1,
0,
0,
905,
0,
0
],
[
1,
0,
0.3214,
0.0179,
0,
... | [
"import cvarray",
"import mp_map",
"import prog_bar",
"import numpy_help_cpp",
"import python_obj_cpp",
"import matrix_cpp",
"import gamma_cpp",
"import setProcName",
"import start_cpp",
"import make",
"import doc_gen",
"doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc... |
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest
import random
import math
from scipy.special import gammaln, psi, polygamma
from scipy import weave
from utils.start_cpp import start_cpp
# Provides various gamma-related functions...
gamma_code = start_cpp() + """
#ifndef GAMMA_CODE
#define GAMMA_CODE
#include <cmath>
// Returns the natural logarithm of the Gamma function...
// (Uses Lanczos's approximation.)
double lnGamma(double z)
{
static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};
if (z<0.5)
{
// Use reflection formula, as approximation doesn't work down here...
return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z);
}
else
{
double x = coeff[0];
for (int i=1;i<9;i++) x += coeff[i]/(z+i-1);
double t = z + 6.5;
return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x);
}
}
// Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values...
double digamma(double z)
{
static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point.
double ret = 0.0;
while (z<highVal)
{
ret -= 1.0/z;
z += 1.0;
}
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz4 = iz2*iz2;
double iz6 = iz4*iz2;
ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0;
return ret;
}
// Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically...
double trigamma(double z)
{
static const double highVal = 8.0;
double ret = 0.0;
while (z<highVal)
{
ret += 1.0/(z*z);
z += 1.0;
}
z -= 1.0;
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz3 = iz1*iz2;
double iz5 = iz3*iz2;
double iz7 = iz5*iz2;
double iz9 = iz7*iz2;
ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0;
return ret;
}
#endif
"""
def lnGamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function"""
code = start_cpp(gamma_code) + """
return_val = lnGamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def digamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function"""
code = start_cpp(gamma_code) + """
return_val = digamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def trigamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function"""
code = start_cpp(gamma_code) + """
return_val = trigamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
class TestFuncs(unittest.TestCase):
"""Test code for the assorted gamma-related functions."""
def test_compile(self):
code = start_cpp(gamma_code) + """
"""
weave.inline(code, support_code=gamma_code)
def test_error_lngamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = lnGamma(z)
good = gammaln(z)
assert(math.fabs(own-good)<1e-12)
def test_error_digamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = digamma(z)
good = psi(z)
assert(math.fabs(own-good)<1e-9)
def test_error_trigamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = trigamma(z)
good = polygamma(1,z)
assert(math.fabs(own-good)<1e-9)
# If this file is run do the unit tests...
if __name__ == '__main__':
unittest.main()
| [
[
1,
0,
0.0818,
0.0063,
0,
0.66,
0,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.0881,
0.0063,
0,
0.66,
0.0909,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0943,
0.0063,
0,
0.... | [
"import unittest",
"import random",
"import math",
"from scipy.special import gammaln, psi, polygamma",
"from scipy import weave",
"from utils.start_cpp import start_cpp",
"gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o... |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import inspect
import hashlib
def start_cpp(hash_str = None):
"""This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>"""
frame = inspect.currentframe().f_back
info = inspect.getframeinfo(frame)
if hash_str==None:
return '#line %i "%s"\n'%(info[1],info[0])
else:
h = hashlib.md5()
h.update(hash_str)
hash_val = h.hexdigest()
return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
| [
[
1,
0,
0.5,
0.0333,
0,
0.66,
0,
878,
0,
1,
0,
0,
878,
0,
0
],
[
1,
0,
0.5333,
0.0333,
0,
0.66,
0.5,
154,
0,
1,
0,
0,
154,
0,
0
],
[
2,
0,
0.8333,
0.3667,
0,
0.66,
... | [
"import inspect",
"import hashlib",
"def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work... |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os.path
import tempfile
import shutil
from distutils.core import setup, Extension
import distutils.ccompiler
import distutils.dep_util
try:
__default_compiler = distutils.ccompiler.new_compiler()
except:
__default_compiler = None
def make_mod(name, base, source, openCL = False):
"""Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place."""
if __default_compiler==None: raise Exception('No compiler!')
# Work out the various file names - check if we actually need to do anything...
if not isinstance(source, list): source = [source]
source_path = map(lambda s: os.path.join(base, s), source)
library_path = os.path.join(base, __default_compiler.shared_object_filename(name))
if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)):
try:
print 'b'
# Backup the argv variable and create a temporary directory to do all work in...
old_argv = sys.argv[:]
temp_dir = tempfile.mkdtemp()
# Prepare the extension...
sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir]
comp_path = filter(lambda s: not s.endswith('.h'), source_path)
depends = filter(lambda s: s.endswith('.h'), source_path)
if openCL:
ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends)
else:
ext = Extension(name, comp_path, depends=depends)
# Compile...
setup(name=name, version='1.0.0', ext_modules=[ext])
finally:
# Cleanup the argv variable and the temporary directory...
sys.argv = old_argv
shutil.rmtree(temp_dir, True)
| [
[
1,
0,
0.2031,
0.0156,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.2188,
0.0156,
0,
0.66,
0.125,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.2344,
0.0156,
0,
0.6... | [
"import sys",
"import os.path",
"import tempfile",
"import shutil",
"from distutils.core import setup, Extension",
"import distutils.ccompiler",
"import distutils.dep_util",
"try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None",
" __default_compiler... |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| [
[
1,
0,
0.0634,
0.0049,
0,
0.66,
0,
291,
0,
1,
0,
0,
291,
0,
0
],
[
1,
0,
0.0683,
0.0049,
0,
0.66,
0.5,
878,
0,
1,
0,
0,
878,
0,
0
],
[
3,
0,
0.5439,
0.9171,
0,
0.6... | [
"import pydoc",
"import inspect",
"class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from ctypes import *
def setProcName(name):
"""Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases."""
# Call the process control function...
libc = cdll.LoadLibrary('libc.so.6')
libc.prctl(15, c_char_p(name), 0, 0, 0)
# Update argv...
charPP = POINTER(POINTER(c_char))
argv = charPP.in_dll(libc,'_dl_argv')
size = libc.strlen(argv[0])
libc.strncpy(argv[0],c_char_p(name),size)
if __name__=='__main__':
# Quick test that it works...
import os
ps1 = 'ps'
ps2 = 'ps -f'
os.system(ps1)
os.system(ps2)
setProcName('wibble_wobble')
os.system(ps1)
os.system(ps2)
| [
[
1,
0,
0.3636,
0.0227,
0,
0.66,
0,
182,
0,
1,
0,
0,
182,
0,
0
],
[
2,
0,
0.5682,
0.25,
0,
0.66,
0.5,
903,
0,
1,
0,
0,
0,
0,
9
],
[
8,
1,
0.4773,
0.0227,
1,
0.22,
... | [
"from ctypes import *",
"def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import multiprocessing as mp
import multiprocessing.synchronize # To make sure we have all the functionality.
import types
import marshal
import unittest
def repeat(x):
"""A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant."""
while True: yield x
def run_code(code,args):
"""Internal use function that does the work in each process."""
code = marshal.loads(code)
func = types.FunctionType(code, globals(), '_')
return func(*args)
def mp_map(func, *iters, **keywords):
"""A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity."""
if 'pool' in keywords: pool = keywords['pool']
else: pool = mp.Pool()
code = marshal.dumps(func.func_code)
jobs = []
for args in zip(*iters):
jobs.append(pool.apply_async(run_code,(code,args)))
for i in xrange(len(jobs)):
jobs[i] = jobs[i].get()
return jobs
class TestMpMap(unittest.TestCase):
def test_simple1(self):
data = ['a','b','c','d']
def noop(data):
return data
data_noop = mp_map(noop, data)
self.assertEqual(data, data_noop)
def test_simple2(self):
data = [x for x in xrange(1000)]
data_double = mp_map(lambda a: a*2, data)
self.assertEqual(map(lambda a: a*2,data), data_double)
def test_gen(self):
def gen():
for i in xrange(100): yield i
data_double = mp_map(lambda a: a*2, gen())
self.assertEqual(map(lambda a: a*2,gen()), data_double)
def test_repeat(self):
def mult(a,b):
return a*b
data = [x for x in xrange(50,5000,5)]
data_triple = mp_map(mult, data, repeat(3))
self.assertEqual(map(lambda a: a*3,data),data_triple)
def test_none(self):
data = []
data_sqr = mp_map(lambda x: x*x, data)
self.assertEqual([],data_sqr)
if __name__ == '__main__':
unittest.main()
| [
[
1,
0,
0.1456,
0.0097,
0,
0.66,
0,
901,
0,
1,
0,
0,
901,
0,
0
],
[
1,
0,
0.1553,
0.0097,
0,
0.66,
0.1111,
99,
0,
1,
0,
0,
99,
0,
0
],
[
1,
0,
0.1748,
0.0097,
0,
0.... | [
"import multiprocessing as mp",
"import multiprocessing.synchronize # To make sure we have all the functionality.",
"import types",
"import marshal",
"import unittest",
"def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Defines helper functions for accessing numpy arrays...
numpy_util_code = start_cpp() + """
#ifndef NUMPY_UTIL_CODE
#define NUMPY_UTIL_CODE
float & Float1D(PyArrayObject * arr, int index = 0)
{
return *(float*)(arr->data + index*arr->strides[0]);
}
float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
unsigned char & Byte1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index*arr->strides[0]);
}
unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
int & Int1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index*arr->strides[0]);
}
int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
#endif
"""
| [
[
1,
0,
0.1923,
0.0128,
0,
0.66,
0,
972,
0,
1,
0,
0,
972,
0,
0
],
[
14,
0,
0.6282,
0.7564,
0,
0.66,
1,
799,
4,
0,
0,
0,
0,
0,
1
]
] | [
"from utils.start_cpp import start_cpp",
"numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}"
] |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import cvarray
import mp_map
import prog_bar
import numpy_help_cpp
import python_obj_cpp
import matrix_cpp
import gamma_cpp
import setProcName
import start_cpp
import make
import doc_gen
# Setup...
doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.')
doc.addFile('readme.txt', 'Overview')
# Variables...
doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.')
doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.')
doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++')
doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++')
# Functions...
doc.addFunction(make.make_mod)
doc.addFunction(cvarray.cv2array)
doc.addFunction(cvarray.array2cv)
doc.addFunction(mp_map.repeat)
doc.addFunction(mp_map.mp_map)
doc.addFunction(setProcName.setProcName)
doc.addFunction(start_cpp.start_cpp)
doc.addFunction(make.make_mod)
# Classes...
doc.addClass(prog_bar.ProgBar)
doc.addClass(doc_gen.DocGen)
| [
[
1,
0,
0.2857,
0.0179,
0,
0.66,
0,
192,
0,
1,
0,
0,
192,
0,
0
],
[
1,
0,
0.3036,
0.0179,
0,
0.66,
0.0385,
905,
0,
1,
0,
0,
905,
0,
0
],
[
1,
0,
0.3214,
0.0179,
0,
... | [
"import cvarray",
"import mp_map",
"import prog_bar",
"import numpy_help_cpp",
"import python_obj_cpp",
"import matrix_cpp",
"import gamma_cpp",
"import setProcName",
"import start_cpp",
"import make",
"import doc_gen",
"doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc... |
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest
import random
import math
from scipy.special import gammaln, psi, polygamma
from scipy import weave
from utils.start_cpp import start_cpp
# Provides various gamma-related functions...
gamma_code = start_cpp() + """
#ifndef GAMMA_CODE
#define GAMMA_CODE
#include <cmath>
// Returns the natural logarithm of the Gamma function...
// (Uses Lanczos's approximation.)
double lnGamma(double z)
{
static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};
if (z<0.5)
{
// Use reflection formula, as approximation doesn't work down here...
return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z);
}
else
{
double x = coeff[0];
for (int i=1;i<9;i++) x += coeff[i]/(z+i-1);
double t = z + 6.5;
return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x);
}
}
// Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values...
double digamma(double z)
{
static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point.
double ret = 0.0;
while (z<highVal)
{
ret -= 1.0/z;
z += 1.0;
}
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz4 = iz2*iz2;
double iz6 = iz4*iz2;
ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0;
return ret;
}
// Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically...
double trigamma(double z)
{
static const double highVal = 8.0;
double ret = 0.0;
while (z<highVal)
{
ret += 1.0/(z*z);
z += 1.0;
}
z -= 1.0;
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz3 = iz1*iz2;
double iz5 = iz3*iz2;
double iz7 = iz5*iz2;
double iz9 = iz7*iz2;
ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0;
return ret;
}
#endif
"""
def lnGamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function"""
code = start_cpp(gamma_code) + """
return_val = lnGamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def digamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function"""
code = start_cpp(gamma_code) + """
return_val = digamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def trigamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function"""
code = start_cpp(gamma_code) + """
return_val = trigamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
class TestFuncs(unittest.TestCase):
"""Test code for the assorted gamma-related functions."""
def test_compile(self):
code = start_cpp(gamma_code) + """
"""
weave.inline(code, support_code=gamma_code)
def test_error_lngamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = lnGamma(z)
good = gammaln(z)
assert(math.fabs(own-good)<1e-12)
def test_error_digamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = digamma(z)
good = psi(z)
assert(math.fabs(own-good)<1e-9)
def test_error_trigamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = trigamma(z)
good = polygamma(1,z)
assert(math.fabs(own-good)<1e-9)
# If this file is run do the unit tests...
if __name__ == '__main__':
unittest.main()
| [
[
1,
0,
0.0818,
0.0063,
0,
0.66,
0,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.0881,
0.0063,
0,
0.66,
0.0909,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0943,
0.0063,
0,
0.... | [
"import unittest",
"import random",
"import math",
"from scipy.special import gammaln, psi, polygamma",
"from scipy import weave",
"from utils.start_cpp import start_cpp",
"gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o... |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import inspect
import hashlib
def start_cpp(hash_str = None):
"""This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>"""
frame = inspect.currentframe().f_back
info = inspect.getframeinfo(frame)
if hash_str==None:
return '#line %i "%s"\n'%(info[1],info[0])
else:
h = hashlib.md5()
h.update(hash_str)
hash_val = h.hexdigest()
return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
| [
[
1,
0,
0.5,
0.0333,
0,
0.66,
0,
878,
0,
1,
0,
0,
878,
0,
0
],
[
1,
0,
0.5333,
0.0333,
0,
0.66,
0.5,
154,
0,
1,
0,
0,
154,
0,
0
],
[
2,
0,
0.8333,
0.3667,
0,
0.66,
... | [
"import inspect",
"import hashlib",
"def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work... |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os.path
import tempfile
import shutil
from distutils.core import setup, Extension
import distutils.ccompiler
import distutils.dep_util
try:
__default_compiler = distutils.ccompiler.new_compiler()
except:
__default_compiler = None
def make_mod(name, base, source, openCL = False):
"""Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place."""
if __default_compiler==None: raise Exception('No compiler!')
# Work out the various file names - check if we actually need to do anything...
if not isinstance(source, list): source = [source]
source_path = map(lambda s: os.path.join(base, s), source)
library_path = os.path.join(base, __default_compiler.shared_object_filename(name))
if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)):
try:
print 'b'
# Backup the argv variable and create a temporary directory to do all work in...
old_argv = sys.argv[:]
temp_dir = tempfile.mkdtemp()
# Prepare the extension...
sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir]
comp_path = filter(lambda s: not s.endswith('.h'), source_path)
depends = filter(lambda s: s.endswith('.h'), source_path)
if openCL:
ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends)
else:
ext = Extension(name, comp_path, depends=depends)
# Compile...
setup(name=name, version='1.0.0', ext_modules=[ext])
finally:
# Cleanup the argv variable and the temporary directory...
sys.argv = old_argv
shutil.rmtree(temp_dir, True)
| [
[
1,
0,
0.2031,
0.0156,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.2188,
0.0156,
0,
0.66,
0.125,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.2344,
0.0156,
0,
0.6... | [
"import sys",
"import os.path",
"import tempfile",
"import shutil",
"from distutils.core import setup, Extension",
"import distutils.ccompiler",
"import distutils.dep_util",
"try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None",
" __default_compiler... |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| [
[
1,
0,
0.0634,
0.0049,
0,
0.66,
0,
291,
0,
1,
0,
0,
291,
0,
0
],
[
1,
0,
0.0683,
0.0049,
0,
0.66,
0.5,
878,
0,
1,
0,
0,
878,
0,
0
],
[
3,
0,
0.5439,
0.9171,
0,
0.6... | [
"import pydoc",
"import inspect",
"class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from ctypes import *
def setProcName(name):
"""Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases."""
# Call the process control function...
libc = cdll.LoadLibrary('libc.so.6')
libc.prctl(15, c_char_p(name), 0, 0, 0)
# Update argv...
charPP = POINTER(POINTER(c_char))
argv = charPP.in_dll(libc,'_dl_argv')
size = libc.strlen(argv[0])
libc.strncpy(argv[0],c_char_p(name),size)
if __name__=='__main__':
# Quick test that it works...
import os
ps1 = 'ps'
ps2 = 'ps -f'
os.system(ps1)
os.system(ps2)
setProcName('wibble_wobble')
os.system(ps1)
os.system(ps2)
| [
[
1,
0,
0.3636,
0.0227,
0,
0.66,
0,
182,
0,
1,
0,
0,
182,
0,
0
],
[
2,
0,
0.5682,
0.25,
0,
0.66,
0.5,
903,
0,
1,
0,
0,
0,
0,
9
],
[
8,
1,
0.4773,
0.0227,
1,
0.72,
... | [
"from ctypes import *",
"def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import multiprocessing as mp
import multiprocessing.synchronize # To make sure we have all the functionality.
import types
import marshal
import unittest
def repeat(x):
"""A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant."""
while True: yield x
def run_code(code,args):
"""Internal use function that does the work in each process."""
code = marshal.loads(code)
func = types.FunctionType(code, globals(), '_')
return func(*args)
def mp_map(func, *iters, **keywords):
"""A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity."""
if 'pool' in keywords: pool = keywords['pool']
else: pool = mp.Pool()
code = marshal.dumps(func.func_code)
jobs = []
for args in zip(*iters):
jobs.append(pool.apply_async(run_code,(code,args)))
for i in xrange(len(jobs)):
jobs[i] = jobs[i].get()
return jobs
class TestMpMap(unittest.TestCase):
def test_simple1(self):
data = ['a','b','c','d']
def noop(data):
return data
data_noop = mp_map(noop, data)
self.assertEqual(data, data_noop)
def test_simple2(self):
data = [x for x in xrange(1000)]
data_double = mp_map(lambda a: a*2, data)
self.assertEqual(map(lambda a: a*2,data), data_double)
def test_gen(self):
def gen():
for i in xrange(100): yield i
data_double = mp_map(lambda a: a*2, gen())
self.assertEqual(map(lambda a: a*2,gen()), data_double)
def test_repeat(self):
def mult(a,b):
return a*b
data = [x for x in xrange(50,5000,5)]
data_triple = mp_map(mult, data, repeat(3))
self.assertEqual(map(lambda a: a*3,data),data_triple)
def test_none(self):
data = []
data_sqr = mp_map(lambda x: x*x, data)
self.assertEqual([],data_sqr)
if __name__ == '__main__':
unittest.main()
| [
[
1,
0,
0.1456,
0.0097,
0,
0.66,
0,
901,
0,
1,
0,
0,
901,
0,
0
],
[
1,
0,
0.1553,
0.0097,
0,
0.66,
0.1111,
99,
0,
1,
0,
0,
99,
0,
0
],
[
1,
0,
0.1748,
0.0097,
0,
0.... | [
"import multiprocessing as mp",
"import multiprocessing.synchronize # To make sure we have all the functionality.",
"import types",
"import marshal",
"import unittest",
"def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Defines helper functions for accessing numpy arrays...
numpy_util_code = start_cpp() + """
#ifndef NUMPY_UTIL_CODE
#define NUMPY_UTIL_CODE
float & Float1D(PyArrayObject * arr, int index = 0)
{
return *(float*)(arr->data + index*arr->strides[0]);
}
float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
unsigned char & Byte1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index*arr->strides[0]);
}
unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
int & Int1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index*arr->strides[0]);
}
int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
#endif
"""
| [
[
1,
0,
0.1923,
0.0128,
0,
0.66,
0,
972,
0,
1,
0,
0,
972,
0,
0
],
[
14,
0,
0.6282,
0.7564,
0,
0.66,
1,
799,
4,
0,
0,
0,
0,
0,
1
]
] | [
"from utils.start_cpp import start_cpp",
"numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}"
] |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import cvarray
import mp_map
import prog_bar
import numpy_help_cpp
import python_obj_cpp
import matrix_cpp
import gamma_cpp
import setProcName
import start_cpp
import make
import doc_gen
# Setup...
doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.')
doc.addFile('readme.txt', 'Overview')
# Variables...
doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.')
doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.')
doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++')
doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++')
# Functions...
doc.addFunction(make.make_mod)
doc.addFunction(cvarray.cv2array)
doc.addFunction(cvarray.array2cv)
doc.addFunction(mp_map.repeat)
doc.addFunction(mp_map.mp_map)
doc.addFunction(setProcName.setProcName)
doc.addFunction(start_cpp.start_cpp)
doc.addFunction(make.make_mod)
# Classes...
doc.addClass(prog_bar.ProgBar)
doc.addClass(doc_gen.DocGen)
| [
[
1,
0,
0.2857,
0.0179,
0,
0.66,
0,
192,
0,
1,
0,
0,
192,
0,
0
],
[
1,
0,
0.3036,
0.0179,
0,
0.66,
0.0385,
905,
0,
1,
0,
0,
905,
0,
0
],
[
1,
0,
0.3214,
0.0179,
0,
... | [
"import cvarray",
"import mp_map",
"import prog_bar",
"import numpy_help_cpp",
"import python_obj_cpp",
"import matrix_cpp",
"import gamma_cpp",
"import setProcName",
"import start_cpp",
"import make",
"import doc_gen",
"doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc... |
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest
import random
import math
from scipy.special import gammaln, psi, polygamma
from scipy import weave
from utils.start_cpp import start_cpp
# Provides various gamma-related functions...
gamma_code = start_cpp() + """
#ifndef GAMMA_CODE
#define GAMMA_CODE
#include <cmath>
// Returns the natural logarithm of the Gamma function...
// (Uses Lanczos's approximation.)
double lnGamma(double z)
{
static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};
if (z<0.5)
{
// Use reflection formula, as approximation doesn't work down here...
return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z);
}
else
{
double x = coeff[0];
for (int i=1;i<9;i++) x += coeff[i]/(z+i-1);
double t = z + 6.5;
return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x);
}
}
// Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values...
double digamma(double z)
{
static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point.
double ret = 0.0;
while (z<highVal)
{
ret -= 1.0/z;
z += 1.0;
}
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz4 = iz2*iz2;
double iz6 = iz4*iz2;
ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0;
return ret;
}
// Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically...
double trigamma(double z)
{
static const double highVal = 8.0;
double ret = 0.0;
while (z<highVal)
{
ret += 1.0/(z*z);
z += 1.0;
}
z -= 1.0;
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz3 = iz1*iz2;
double iz5 = iz3*iz2;
double iz7 = iz5*iz2;
double iz9 = iz7*iz2;
ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0;
return ret;
}
#endif
"""
def lnGamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function"""
code = start_cpp(gamma_code) + """
return_val = lnGamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def digamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function"""
code = start_cpp(gamma_code) + """
return_val = digamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def trigamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function"""
code = start_cpp(gamma_code) + """
return_val = trigamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
class TestFuncs(unittest.TestCase):
"""Test code for the assorted gamma-related functions."""
def test_compile(self):
code = start_cpp(gamma_code) + """
"""
weave.inline(code, support_code=gamma_code)
def test_error_lngamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = lnGamma(z)
good = gammaln(z)
assert(math.fabs(own-good)<1e-12)
def test_error_digamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = digamma(z)
good = psi(z)
assert(math.fabs(own-good)<1e-9)
def test_error_trigamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = trigamma(z)
good = polygamma(1,z)
assert(math.fabs(own-good)<1e-9)
# If this file is run do the unit tests...
if __name__ == '__main__':
unittest.main()
| [
[
1,
0,
0.0818,
0.0063,
0,
0.66,
0,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.0881,
0.0063,
0,
0.66,
0.0909,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0943,
0.0063,
0,
0.... | [
"import unittest",
"import random",
"import math",
"from scipy.special import gammaln, psi, polygamma",
"from scipy import weave",
"from utils.start_cpp import start_cpp",
"gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o... |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import inspect
import hashlib
def start_cpp(hash_str = None):
"""This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>"""
frame = inspect.currentframe().f_back
info = inspect.getframeinfo(frame)
if hash_str==None:
return '#line %i "%s"\n'%(info[1],info[0])
else:
h = hashlib.md5()
h.update(hash_str)
hash_val = h.hexdigest()
return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
| [
[
1,
0,
0.5,
0.0333,
0,
0.66,
0,
878,
0,
1,
0,
0,
878,
0,
0
],
[
1,
0,
0.5333,
0.0333,
0,
0.66,
0.5,
154,
0,
1,
0,
0,
154,
0,
0
],
[
2,
0,
0.8333,
0.3667,
0,
0.66,
... | [
"import inspect",
"import hashlib",
"def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work... |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os.path
import tempfile
import shutil
from distutils.core import setup, Extension
import distutils.ccompiler
import distutils.dep_util
try:
__default_compiler = distutils.ccompiler.new_compiler()
except:
__default_compiler = None
def make_mod(name, base, source, openCL = False):
"""Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place."""
if __default_compiler==None: raise Exception('No compiler!')
# Work out the various file names - check if we actually need to do anything...
if not isinstance(source, list): source = [source]
source_path = map(lambda s: os.path.join(base, s), source)
library_path = os.path.join(base, __default_compiler.shared_object_filename(name))
if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)):
try:
print 'b'
# Backup the argv variable and create a temporary directory to do all work in...
old_argv = sys.argv[:]
temp_dir = tempfile.mkdtemp()
# Prepare the extension...
sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir]
comp_path = filter(lambda s: not s.endswith('.h'), source_path)
depends = filter(lambda s: s.endswith('.h'), source_path)
if openCL:
ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends)
else:
ext = Extension(name, comp_path, depends=depends)
# Compile...
setup(name=name, version='1.0.0', ext_modules=[ext])
finally:
# Cleanup the argv variable and the temporary directory...
sys.argv = old_argv
shutil.rmtree(temp_dir, True)
| [
[
1,
0,
0.2031,
0.0156,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.2188,
0.0156,
0,
0.66,
0.125,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.2344,
0.0156,
0,
0.6... | [
"import sys",
"import os.path",
"import tempfile",
"import shutil",
"from distutils.core import setup, Extension",
"import distutils.ccompiler",
"import distutils.dep_util",
"try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None",
" __default_compiler... |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| [
[
1,
0,
0.0634,
0.0049,
0,
0.66,
0,
291,
0,
1,
0,
0,
291,
0,
0
],
[
1,
0,
0.0683,
0.0049,
0,
0.66,
0.5,
878,
0,
1,
0,
0,
878,
0,
0
],
[
3,
0,
0.5439,
0.9171,
0,
0.6... | [
"import pydoc",
"import inspect",
"class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from ctypes import *
def setProcName(name):
"""Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases."""
# Call the process control function...
libc = cdll.LoadLibrary('libc.so.6')
libc.prctl(15, c_char_p(name), 0, 0, 0)
# Update argv...
charPP = POINTER(POINTER(c_char))
argv = charPP.in_dll(libc,'_dl_argv')
size = libc.strlen(argv[0])
libc.strncpy(argv[0],c_char_p(name),size)
if __name__=='__main__':
# Quick test that it works...
import os
ps1 = 'ps'
ps2 = 'ps -f'
os.system(ps1)
os.system(ps2)
setProcName('wibble_wobble')
os.system(ps1)
os.system(ps2)
| [
[
1,
0,
0.3636,
0.0227,
0,
0.66,
0,
182,
0,
1,
0,
0,
182,
0,
0
],
[
2,
0,
0.5682,
0.25,
0,
0.66,
0.5,
903,
0,
1,
0,
0,
0,
0,
9
],
[
8,
1,
0.4773,
0.0227,
1,
0.68,
... | [
"from ctypes import *",
"def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import multiprocessing as mp
import multiprocessing.synchronize # To make sure we have all the functionality.
import types
import marshal
import unittest
def repeat(x):
"""A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant."""
while True: yield x
def run_code(code,args):
"""Internal use function that does the work in each process."""
code = marshal.loads(code)
func = types.FunctionType(code, globals(), '_')
return func(*args)
def mp_map(func, *iters, **keywords):
"""A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity."""
if 'pool' in keywords: pool = keywords['pool']
else: pool = mp.Pool()
code = marshal.dumps(func.func_code)
jobs = []
for args in zip(*iters):
jobs.append(pool.apply_async(run_code,(code,args)))
for i in xrange(len(jobs)):
jobs[i] = jobs[i].get()
return jobs
class TestMpMap(unittest.TestCase):
def test_simple1(self):
data = ['a','b','c','d']
def noop(data):
return data
data_noop = mp_map(noop, data)
self.assertEqual(data, data_noop)
def test_simple2(self):
data = [x for x in xrange(1000)]
data_double = mp_map(lambda a: a*2, data)
self.assertEqual(map(lambda a: a*2,data), data_double)
def test_gen(self):
def gen():
for i in xrange(100): yield i
data_double = mp_map(lambda a: a*2, gen())
self.assertEqual(map(lambda a: a*2,gen()), data_double)
def test_repeat(self):
def mult(a,b):
return a*b
data = [x for x in xrange(50,5000,5)]
data_triple = mp_map(mult, data, repeat(3))
self.assertEqual(map(lambda a: a*3,data),data_triple)
def test_none(self):
data = []
data_sqr = mp_map(lambda x: x*x, data)
self.assertEqual([],data_sqr)
if __name__ == '__main__':
unittest.main()
| [
[
1,
0,
0.1456,
0.0097,
0,
0.66,
0,
901,
0,
1,
0,
0,
901,
0,
0
],
[
1,
0,
0.1553,
0.0097,
0,
0.66,
0.1111,
99,
0,
1,
0,
0,
99,
0,
0
],
[
1,
0,
0.1748,
0.0097,
0,
0.... | [
"import multiprocessing as mp",
"import multiprocessing.synchronize # To make sure we have all the functionality.",
"import types",
"import marshal",
"import unittest",
"def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Defines helper functions for accessing numpy arrays...
numpy_util_code = start_cpp() + """
#ifndef NUMPY_UTIL_CODE
#define NUMPY_UTIL_CODE
float & Float1D(PyArrayObject * arr, int index = 0)
{
return *(float*)(arr->data + index*arr->strides[0]);
}
float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
unsigned char & Byte1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index*arr->strides[0]);
}
unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
int & Int1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index*arr->strides[0]);
}
int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
#endif
"""
| [
[
1,
0,
0.1923,
0.0128,
0,
0.66,
0,
972,
0,
1,
0,
0,
972,
0,
0
],
[
14,
0,
0.6282,
0.7564,
0,
0.66,
1,
799,
4,
0,
0,
0,
0,
0,
1
]
] | [
"from utils.start_cpp import start_cpp",
"numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}"
] |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import cvarray
import mp_map
import prog_bar
import numpy_help_cpp
import python_obj_cpp
import matrix_cpp
import gamma_cpp
import setProcName
import start_cpp
import make
import doc_gen
# Setup...
doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.')
doc.addFile('readme.txt', 'Overview')
# Variables...
doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.')
doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.')
doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++')
doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++')
# Functions...
doc.addFunction(make.make_mod)
doc.addFunction(cvarray.cv2array)
doc.addFunction(cvarray.array2cv)
doc.addFunction(mp_map.repeat)
doc.addFunction(mp_map.mp_map)
doc.addFunction(setProcName.setProcName)
doc.addFunction(start_cpp.start_cpp)
doc.addFunction(make.make_mod)
# Classes...
doc.addClass(prog_bar.ProgBar)
doc.addClass(doc_gen.DocGen)
| [
[
1,
0,
0.2857,
0.0179,
0,
0.66,
0,
192,
0,
1,
0,
0,
192,
0,
0
],
[
1,
0,
0.3036,
0.0179,
0,
0.66,
0.0385,
905,
0,
1,
0,
0,
905,
0,
0
],
[
1,
0,
0.3214,
0.0179,
0,
... | [
"import cvarray",
"import mp_map",
"import prog_bar",
"import numpy_help_cpp",
"import python_obj_cpp",
"import matrix_cpp",
"import gamma_cpp",
"import setProcName",
"import start_cpp",
"import make",
"import doc_gen",
"doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc... |
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest
import random
import math
from scipy.special import gammaln, psi, polygamma
from scipy import weave
from utils.start_cpp import start_cpp
# Provides various gamma-related functions...
gamma_code = start_cpp() + """
#ifndef GAMMA_CODE
#define GAMMA_CODE
#include <cmath>
// Returns the natural logarithm of the Gamma function...
// (Uses Lanczos's approximation.)
double lnGamma(double z)
{
static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};
if (z<0.5)
{
// Use reflection formula, as approximation doesn't work down here...
return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z);
}
else
{
double x = coeff[0];
for (int i=1;i<9;i++) x += coeff[i]/(z+i-1);
double t = z + 6.5;
return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x);
}
}
// Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values...
double digamma(double z)
{
static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point.
double ret = 0.0;
while (z<highVal)
{
ret -= 1.0/z;
z += 1.0;
}
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz4 = iz2*iz2;
double iz6 = iz4*iz2;
ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0;
return ret;
}
// Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically...
double trigamma(double z)
{
static const double highVal = 8.0;
double ret = 0.0;
while (z<highVal)
{
ret += 1.0/(z*z);
z += 1.0;
}
z -= 1.0;
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz3 = iz1*iz2;
double iz5 = iz3*iz2;
double iz7 = iz5*iz2;
double iz9 = iz7*iz2;
ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0;
return ret;
}
#endif
"""
def lnGamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function"""
code = start_cpp(gamma_code) + """
return_val = lnGamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def digamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function"""
code = start_cpp(gamma_code) + """
return_val = digamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def trigamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function"""
code = start_cpp(gamma_code) + """
return_val = trigamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
class TestFuncs(unittest.TestCase):
"""Test code for the assorted gamma-related functions."""
def test_compile(self):
code = start_cpp(gamma_code) + """
"""
weave.inline(code, support_code=gamma_code)
def test_error_lngamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = lnGamma(z)
good = gammaln(z)
assert(math.fabs(own-good)<1e-12)
def test_error_digamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = digamma(z)
good = psi(z)
assert(math.fabs(own-good)<1e-9)
def test_error_trigamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = trigamma(z)
good = polygamma(1,z)
assert(math.fabs(own-good)<1e-9)
# If this file is run do the unit tests...
if __name__ == '__main__':
unittest.main()
| [
[
1,
0,
0.0818,
0.0063,
0,
0.66,
0,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.0881,
0.0063,
0,
0.66,
0.0909,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0943,
0.0063,
0,
0.... | [
"import unittest",
"import random",
"import math",
"from scipy.special import gammaln, psi, polygamma",
"from scipy import weave",
"from utils.start_cpp import start_cpp",
"gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o... |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import inspect
import hashlib
def start_cpp(hash_str = None):
"""This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>"""
frame = inspect.currentframe().f_back
info = inspect.getframeinfo(frame)
if hash_str==None:
return '#line %i "%s"\n'%(info[1],info[0])
else:
h = hashlib.md5()
h.update(hash_str)
hash_val = h.hexdigest()
return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
| [
[
1,
0,
0.5,
0.0333,
0,
0.66,
0,
878,
0,
1,
0,
0,
878,
0,
0
],
[
1,
0,
0.5333,
0.0333,
0,
0.66,
0.5,
154,
0,
1,
0,
0,
154,
0,
0
],
[
2,
0,
0.8333,
0.3667,
0,
0.66,
... | [
"import inspect",
"import hashlib",
"def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work... |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os.path
import tempfile
import shutil
from distutils.core import setup, Extension
import distutils.ccompiler
import distutils.dep_util
try:
__default_compiler = distutils.ccompiler.new_compiler()
except:
__default_compiler = None
def make_mod(name, base, source, openCL = False):
"""Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place."""
if __default_compiler==None: raise Exception('No compiler!')
# Work out the various file names - check if we actually need to do anything...
if not isinstance(source, list): source = [source]
source_path = map(lambda s: os.path.join(base, s), source)
library_path = os.path.join(base, __default_compiler.shared_object_filename(name))
if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)):
try:
print 'b'
# Backup the argv variable and create a temporary directory to do all work in...
old_argv = sys.argv[:]
temp_dir = tempfile.mkdtemp()
# Prepare the extension...
sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir]
comp_path = filter(lambda s: not s.endswith('.h'), source_path)
depends = filter(lambda s: s.endswith('.h'), source_path)
if openCL:
ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends)
else:
ext = Extension(name, comp_path, depends=depends)
# Compile...
setup(name=name, version='1.0.0', ext_modules=[ext])
finally:
# Cleanup the argv variable and the temporary directory...
sys.argv = old_argv
shutil.rmtree(temp_dir, True)
| [
[
1,
0,
0.2031,
0.0156,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.2188,
0.0156,
0,
0.66,
0.125,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.2344,
0.0156,
0,
0.6... | [
"import sys",
"import os.path",
"import tempfile",
"import shutil",
"from distutils.core import setup, Extension",
"import distutils.ccompiler",
"import distutils.dep_util",
"try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None",
" __default_compiler... |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| [
[
1,
0,
0.0634,
0.0049,
0,
0.66,
0,
291,
0,
1,
0,
0,
291,
0,
0
],
[
1,
0,
0.0683,
0.0049,
0,
0.66,
0.5,
878,
0,
1,
0,
0,
878,
0,
0
],
[
3,
0,
0.5439,
0.9171,
0,
0.6... | [
"import pydoc",
"import inspect",
"class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from ctypes import *
def setProcName(name):
"""Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases."""
# Call the process control function...
libc = cdll.LoadLibrary('libc.so.6')
libc.prctl(15, c_char_p(name), 0, 0, 0)
# Update argv...
charPP = POINTER(POINTER(c_char))
argv = charPP.in_dll(libc,'_dl_argv')
size = libc.strlen(argv[0])
libc.strncpy(argv[0],c_char_p(name),size)
if __name__=='__main__':
# Quick test that it works...
import os
ps1 = 'ps'
ps2 = 'ps -f'
os.system(ps1)
os.system(ps2)
setProcName('wibble_wobble')
os.system(ps1)
os.system(ps2)
| [
[
1,
0,
0.3636,
0.0227,
0,
0.66,
0,
182,
0,
1,
0,
0,
182,
0,
0
],
[
2,
0,
0.5682,
0.25,
0,
0.66,
0.5,
903,
0,
1,
0,
0,
0,
0,
9
],
[
8,
1,
0.4773,
0.0227,
1,
0.34,
... | [
"from ctypes import *",
"def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import multiprocessing as mp
import multiprocessing.synchronize # To make sure we have all the functionality.
import types
import marshal
import unittest
def repeat(x):
"""A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant."""
while True: yield x
def run_code(code,args):
"""Internal use function that does the work in each process."""
code = marshal.loads(code)
func = types.FunctionType(code, globals(), '_')
return func(*args)
def mp_map(func, *iters, **keywords):
"""A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity."""
if 'pool' in keywords: pool = keywords['pool']
else: pool = mp.Pool()
code = marshal.dumps(func.func_code)
jobs = []
for args in zip(*iters):
jobs.append(pool.apply_async(run_code,(code,args)))
for i in xrange(len(jobs)):
jobs[i] = jobs[i].get()
return jobs
class TestMpMap(unittest.TestCase):
def test_simple1(self):
data = ['a','b','c','d']
def noop(data):
return data
data_noop = mp_map(noop, data)
self.assertEqual(data, data_noop)
def test_simple2(self):
data = [x for x in xrange(1000)]
data_double = mp_map(lambda a: a*2, data)
self.assertEqual(map(lambda a: a*2,data), data_double)
def test_gen(self):
def gen():
for i in xrange(100): yield i
data_double = mp_map(lambda a: a*2, gen())
self.assertEqual(map(lambda a: a*2,gen()), data_double)
def test_repeat(self):
def mult(a,b):
return a*b
data = [x for x in xrange(50,5000,5)]
data_triple = mp_map(mult, data, repeat(3))
self.assertEqual(map(lambda a: a*3,data),data_triple)
def test_none(self):
data = []
data_sqr = mp_map(lambda x: x*x, data)
self.assertEqual([],data_sqr)
if __name__ == '__main__':
unittest.main()
| [
[
1,
0,
0.1456,
0.0097,
0,
0.66,
0,
901,
0,
1,
0,
0,
901,
0,
0
],
[
1,
0,
0.1553,
0.0097,
0,
0.66,
0.1111,
99,
0,
1,
0,
0,
99,
0,
0
],
[
1,
0,
0.1748,
0.0097,
0,
0.... | [
"import multiprocessing as mp",
"import multiprocessing.synchronize # To make sure we have all the functionality.",
"import types",
"import marshal",
"import unittest",
"def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Defines helper functions for accessing numpy arrays...
numpy_util_code = start_cpp() + """
#ifndef NUMPY_UTIL_CODE
#define NUMPY_UTIL_CODE
float & Float1D(PyArrayObject * arr, int index = 0)
{
return *(float*)(arr->data + index*arr->strides[0]);
}
float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
unsigned char & Byte1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index*arr->strides[0]);
}
unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
int & Int1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index*arr->strides[0]);
}
int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
#endif
"""
| [
[
1,
0,
0.1923,
0.0128,
0,
0.66,
0,
972,
0,
1,
0,
0,
972,
0,
0
],
[
14,
0,
0.6282,
0.7564,
0,
0.66,
1,
799,
4,
0,
0,
0,
0,
0,
1
]
] | [
"from utils.start_cpp import start_cpp",
"numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}"
] |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import cvarray
import mp_map
import prog_bar
import numpy_help_cpp
import python_obj_cpp
import matrix_cpp
import gamma_cpp
import setProcName
import start_cpp
import make
import doc_gen
# Setup...
doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.')
doc.addFile('readme.txt', 'Overview')
# Variables...
doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.')
doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.')
doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++')
doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++')
# Functions...
doc.addFunction(make.make_mod)
doc.addFunction(cvarray.cv2array)
doc.addFunction(cvarray.array2cv)
doc.addFunction(mp_map.repeat)
doc.addFunction(mp_map.mp_map)
doc.addFunction(setProcName.setProcName)
doc.addFunction(start_cpp.start_cpp)
doc.addFunction(make.make_mod)
# Classes...
doc.addClass(prog_bar.ProgBar)
doc.addClass(doc_gen.DocGen)
| [
[
1,
0,
0.2857,
0.0179,
0,
0.66,
0,
192,
0,
1,
0,
0,
192,
0,
0
],
[
1,
0,
0.3036,
0.0179,
0,
0.66,
0.0385,
905,
0,
1,
0,
0,
905,
0,
0
],
[
1,
0,
0.3214,
0.0179,
0,
... | [
"import cvarray",
"import mp_map",
"import prog_bar",
"import numpy_help_cpp",
"import python_obj_cpp",
"import matrix_cpp",
"import gamma_cpp",
"import setProcName",
"import start_cpp",
"import make",
"import doc_gen",
"doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc... |
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest
import random
import math
from scipy.special import gammaln, psi, polygamma
from scipy import weave
from utils.start_cpp import start_cpp
# Provides various gamma-related functions...
gamma_code = start_cpp() + """
#ifndef GAMMA_CODE
#define GAMMA_CODE
#include <cmath>
// Returns the natural logarithm of the Gamma function...
// (Uses Lanczos's approximation.)
double lnGamma(double z)
{
static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};
if (z<0.5)
{
// Use reflection formula, as approximation doesn't work down here...
return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z);
}
else
{
double x = coeff[0];
for (int i=1;i<9;i++) x += coeff[i]/(z+i-1);
double t = z + 6.5;
return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x);
}
}
// Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values...
double digamma(double z)
{
static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point.
double ret = 0.0;
while (z<highVal)
{
ret -= 1.0/z;
z += 1.0;
}
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz4 = iz2*iz2;
double iz6 = iz4*iz2;
ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0;
return ret;
}
// Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically...
double trigamma(double z)
{
static const double highVal = 8.0;
double ret = 0.0;
while (z<highVal)
{
ret += 1.0/(z*z);
z += 1.0;
}
z -= 1.0;
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz3 = iz1*iz2;
double iz5 = iz3*iz2;
double iz7 = iz5*iz2;
double iz9 = iz7*iz2;
ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0;
return ret;
}
#endif
"""
def lnGamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function"""
code = start_cpp(gamma_code) + """
return_val = lnGamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def digamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function"""
code = start_cpp(gamma_code) + """
return_val = digamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def trigamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function"""
code = start_cpp(gamma_code) + """
return_val = trigamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
class TestFuncs(unittest.TestCase):
"""Test code for the assorted gamma-related functions."""
def test_compile(self):
code = start_cpp(gamma_code) + """
"""
weave.inline(code, support_code=gamma_code)
def test_error_lngamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = lnGamma(z)
good = gammaln(z)
assert(math.fabs(own-good)<1e-12)
def test_error_digamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = digamma(z)
good = psi(z)
assert(math.fabs(own-good)<1e-9)
def test_error_trigamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = trigamma(z)
good = polygamma(1,z)
assert(math.fabs(own-good)<1e-9)
# If this file is run do the unit tests...
if __name__ == '__main__':
unittest.main()
| [
[
1,
0,
0.0818,
0.0063,
0,
0.66,
0,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.0881,
0.0063,
0,
0.66,
0.0909,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0943,
0.0063,
0,
0.... | [
"import unittest",
"import random",
"import math",
"from scipy.special import gammaln, psi, polygamma",
"from scipy import weave",
"from utils.start_cpp import start_cpp",
"gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o... |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import inspect
import hashlib
def start_cpp(hash_str = None):
"""This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>"""
frame = inspect.currentframe().f_back
info = inspect.getframeinfo(frame)
if hash_str==None:
return '#line %i "%s"\n'%(info[1],info[0])
else:
h = hashlib.md5()
h.update(hash_str)
hash_val = h.hexdigest()
return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
| [
[
1,
0,
0.5,
0.0333,
0,
0.66,
0,
878,
0,
1,
0,
0,
878,
0,
0
],
[
1,
0,
0.5333,
0.0333,
0,
0.66,
0.5,
154,
0,
1,
0,
0,
154,
0,
0
],
[
2,
0,
0.8333,
0.3667,
0,
0.66,
... | [
"import inspect",
"import hashlib",
"def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work... |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os.path
import tempfile
import shutil
from distutils.core import setup, Extension
import distutils.ccompiler
import distutils.dep_util
try:
__default_compiler = distutils.ccompiler.new_compiler()
except:
__default_compiler = None
def make_mod(name, base, source, openCL = False):
"""Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place."""
if __default_compiler==None: raise Exception('No compiler!')
# Work out the various file names - check if we actually need to do anything...
if not isinstance(source, list): source = [source]
source_path = map(lambda s: os.path.join(base, s), source)
library_path = os.path.join(base, __default_compiler.shared_object_filename(name))
if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)):
try:
print 'b'
# Backup the argv variable and create a temporary directory to do all work in...
old_argv = sys.argv[:]
temp_dir = tempfile.mkdtemp()
# Prepare the extension...
sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir]
comp_path = filter(lambda s: not s.endswith('.h'), source_path)
depends = filter(lambda s: s.endswith('.h'), source_path)
if openCL:
ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends)
else:
ext = Extension(name, comp_path, depends=depends)
# Compile...
setup(name=name, version='1.0.0', ext_modules=[ext])
finally:
# Cleanup the argv variable and the temporary directory...
sys.argv = old_argv
shutil.rmtree(temp_dir, True)
| [
[
1,
0,
0.2031,
0.0156,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.2188,
0.0156,
0,
0.66,
0.125,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.2344,
0.0156,
0,
0.6... | [
"import sys",
"import os.path",
"import tempfile",
"import shutil",
"from distutils.core import setup, Extension",
"import distutils.ccompiler",
"import distutils.dep_util",
"try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None",
" __default_compiler... |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| [
[
1,
0,
0.0634,
0.0049,
0,
0.66,
0,
291,
0,
1,
0,
0,
291,
0,
0
],
[
1,
0,
0.0683,
0.0049,
0,
0.66,
0.5,
878,
0,
1,
0,
0,
878,
0,
0
],
[
3,
0,
0.5439,
0.9171,
0,
0.6... | [
"import pydoc",
"import inspect",
"class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from ctypes import *
def setProcName(name):
"""Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases."""
# Call the process control function...
libc = cdll.LoadLibrary('libc.so.6')
libc.prctl(15, c_char_p(name), 0, 0, 0)
# Update argv...
charPP = POINTER(POINTER(c_char))
argv = charPP.in_dll(libc,'_dl_argv')
size = libc.strlen(argv[0])
libc.strncpy(argv[0],c_char_p(name),size)
if __name__=='__main__':
# Quick test that it works...
import os
ps1 = 'ps'
ps2 = 'ps -f'
os.system(ps1)
os.system(ps2)
setProcName('wibble_wobble')
os.system(ps1)
os.system(ps2)
| [
[
1,
0,
0.3636,
0.0227,
0,
0.66,
0,
182,
0,
1,
0,
0,
182,
0,
0
],
[
2,
0,
0.5682,
0.25,
0,
0.66,
0.5,
903,
0,
1,
0,
0,
0,
0,
9
],
[
8,
1,
0.4773,
0.0227,
1,
0.32,
... | [
"from ctypes import *",
"def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import multiprocessing as mp
import multiprocessing.synchronize # To make sure we have all the functionality.
import types
import marshal
import unittest
def repeat(x):
"""A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant."""
while True: yield x
def run_code(code,args):
"""Internal use function that does the work in each process."""
code = marshal.loads(code)
func = types.FunctionType(code, globals(), '_')
return func(*args)
def mp_map(func, *iters, **keywords):
"""A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity."""
if 'pool' in keywords: pool = keywords['pool']
else: pool = mp.Pool()
code = marshal.dumps(func.func_code)
jobs = []
for args in zip(*iters):
jobs.append(pool.apply_async(run_code,(code,args)))
for i in xrange(len(jobs)):
jobs[i] = jobs[i].get()
return jobs
class TestMpMap(unittest.TestCase):
def test_simple1(self):
data = ['a','b','c','d']
def noop(data):
return data
data_noop = mp_map(noop, data)
self.assertEqual(data, data_noop)
def test_simple2(self):
data = [x for x in xrange(1000)]
data_double = mp_map(lambda a: a*2, data)
self.assertEqual(map(lambda a: a*2,data), data_double)
def test_gen(self):
def gen():
for i in xrange(100): yield i
data_double = mp_map(lambda a: a*2, gen())
self.assertEqual(map(lambda a: a*2,gen()), data_double)
def test_repeat(self):
def mult(a,b):
return a*b
data = [x for x in xrange(50,5000,5)]
data_triple = mp_map(mult, data, repeat(3))
self.assertEqual(map(lambda a: a*3,data),data_triple)
def test_none(self):
data = []
data_sqr = mp_map(lambda x: x*x, data)
self.assertEqual([],data_sqr)
if __name__ == '__main__':
unittest.main()
| [
[
1,
0,
0.1456,
0.0097,
0,
0.66,
0,
901,
0,
1,
0,
0,
901,
0,
0
],
[
1,
0,
0.1553,
0.0097,
0,
0.66,
0.1111,
99,
0,
1,
0,
0,
99,
0,
0
],
[
1,
0,
0.1748,
0.0097,
0,
0.... | [
"import multiprocessing as mp",
"import multiprocessing.synchronize # To make sure we have all the functionality.",
"import types",
"import marshal",
"import unittest",
"def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Defines helper functions for accessing numpy arrays...
numpy_util_code = start_cpp() + """
#ifndef NUMPY_UTIL_CODE
#define NUMPY_UTIL_CODE
float & Float1D(PyArrayObject * arr, int index = 0)
{
return *(float*)(arr->data + index*arr->strides[0]);
}
float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
unsigned char & Byte1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index*arr->strides[0]);
}
unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
int & Int1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index*arr->strides[0]);
}
int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
#endif
"""
| [
[
1,
0,
0.1923,
0.0128,
0,
0.66,
0,
972,
0,
1,
0,
0,
972,
0,
0
],
[
14,
0,
0.6282,
0.7564,
0,
0.66,
1,
799,
4,
0,
0,
0,
0,
0,
1
]
] | [
"from utils.start_cpp import start_cpp",
"numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}"
] |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import cvarray
import mp_map
import prog_bar
import numpy_help_cpp
import python_obj_cpp
import matrix_cpp
import gamma_cpp
import setProcName
import start_cpp
import make
import doc_gen
# Setup...
doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.')
doc.addFile('readme.txt', 'Overview')
# Variables...
doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.')
doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.')
doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++')
doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++')
# Functions...
doc.addFunction(make.make_mod)
doc.addFunction(cvarray.cv2array)
doc.addFunction(cvarray.array2cv)
doc.addFunction(mp_map.repeat)
doc.addFunction(mp_map.mp_map)
doc.addFunction(setProcName.setProcName)
doc.addFunction(start_cpp.start_cpp)
doc.addFunction(make.make_mod)
# Classes...
doc.addClass(prog_bar.ProgBar)
doc.addClass(doc_gen.DocGen)
| [
[
1,
0,
0.2857,
0.0179,
0,
0.66,
0,
192,
0,
1,
0,
0,
192,
0,
0
],
[
1,
0,
0.3036,
0.0179,
0,
0.66,
0.0385,
905,
0,
1,
0,
0,
905,
0,
0
],
[
1,
0,
0.3214,
0.0179,
0,
... | [
"import cvarray",
"import mp_map",
"import prog_bar",
"import numpy_help_cpp",
"import python_obj_cpp",
"import matrix_cpp",
"import gamma_cpp",
"import setProcName",
"import start_cpp",
"import make",
"import doc_gen",
"doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of misc... |
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest
import random
import math
from scipy.special import gammaln, psi, polygamma
from scipy import weave
from utils.start_cpp import start_cpp
# Provides various gamma-related functions...
gamma_code = start_cpp() + """
#ifndef GAMMA_CODE
#define GAMMA_CODE
#include <cmath>
// Returns the natural logarithm of the Gamma function...
// (Uses Lanczos's approximation.)
double lnGamma(double z)
{
static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};
if (z<0.5)
{
// Use reflection formula, as approximation doesn't work down here...
return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z);
}
else
{
double x = coeff[0];
for (int i=1;i<9;i++) x += coeff[i]/(z+i-1);
double t = z + 6.5;
return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x);
}
}
// Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values...
double digamma(double z)
{
static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point.
double ret = 0.0;
while (z<highVal)
{
ret -= 1.0/z;
z += 1.0;
}
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz4 = iz2*iz2;
double iz6 = iz4*iz2;
ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0;
return ret;
}
// Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically...
double trigamma(double z)
{
static const double highVal = 8.0;
double ret = 0.0;
while (z<highVal)
{
ret += 1.0/(z*z);
z += 1.0;
}
z -= 1.0;
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz3 = iz1*iz2;
double iz5 = iz3*iz2;
double iz7 = iz5*iz2;
double iz9 = iz7*iz2;
ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0;
return ret;
}
#endif
"""
def lnGamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function"""
code = start_cpp(gamma_code) + """
return_val = lnGamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def digamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function"""
code = start_cpp(gamma_code) + """
return_val = digamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def trigamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function"""
code = start_cpp(gamma_code) + """
return_val = trigamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
class TestFuncs(unittest.TestCase):
"""Test code for the assorted gamma-related functions."""
def test_compile(self):
code = start_cpp(gamma_code) + """
"""
weave.inline(code, support_code=gamma_code)
def test_error_lngamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = lnGamma(z)
good = gammaln(z)
assert(math.fabs(own-good)<1e-12)
def test_error_digamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = digamma(z)
good = psi(z)
assert(math.fabs(own-good)<1e-9)
def test_error_trigamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = trigamma(z)
good = polygamma(1,z)
assert(math.fabs(own-good)<1e-9)
# If this file is run do the unit tests...
if __name__ == '__main__':
unittest.main()
| [
[
1,
0,
0.0818,
0.0063,
0,
0.66,
0,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.0881,
0.0063,
0,
0.66,
0.0909,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0943,
0.0063,
0,
0.... | [
"import unittest",
"import random",
"import math",
"from scipy.special import gammaln, psi, polygamma",
"from scipy import weave",
"from utils.start_cpp import start_cpp",
"gamma_code = start_cpp() + \"\"\"\n#ifndef GAMMA_CODE\n#define GAMMA_CODE\n\n#include <cmath>\n\n// Returns the natural logarithm o... |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import inspect
import hashlib
def start_cpp(hash_str = None):
"""This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>"""
frame = inspect.currentframe().f_back
info = inspect.getframeinfo(frame)
if hash_str==None:
return '#line %i "%s"\n'%(info[1],info[0])
else:
h = hashlib.md5()
h.update(hash_str)
hash_val = h.hexdigest()
return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
| [
[
1,
0,
0.5,
0.0333,
0,
0.66,
0,
878,
0,
1,
0,
0,
878,
0,
0
],
[
1,
0,
0.5333,
0.0333,
0,
0.66,
0.5,
154,
0,
1,
0,
0,
154,
0,
0
],
[
2,
0,
0.8333,
0.3667,
0,
0.66,
... | [
"import inspect",
"import hashlib",
"def start_cpp(hash_str = None):\n \"\"\"This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for work... |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os.path
import tempfile
import shutil
from distutils.core import setup, Extension
import distutils.ccompiler
import distutils.dep_util
try:
__default_compiler = distutils.ccompiler.new_compiler()
except:
__default_compiler = None
def make_mod(name, base, source, openCL = False):
"""Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place."""
if __default_compiler==None: raise Exception('No compiler!')
# Work out the various file names - check if we actually need to do anything...
if not isinstance(source, list): source = [source]
source_path = map(lambda s: os.path.join(base, s), source)
library_path = os.path.join(base, __default_compiler.shared_object_filename(name))
if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)):
try:
print 'b'
# Backup the argv variable and create a temporary directory to do all work in...
old_argv = sys.argv[:]
temp_dir = tempfile.mkdtemp()
# Prepare the extension...
sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir]
comp_path = filter(lambda s: not s.endswith('.h'), source_path)
depends = filter(lambda s: s.endswith('.h'), source_path)
if openCL:
ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends)
else:
ext = Extension(name, comp_path, depends=depends)
# Compile...
setup(name=name, version='1.0.0', ext_modules=[ext])
finally:
# Cleanup the argv variable and the temporary directory...
sys.argv = old_argv
shutil.rmtree(temp_dir, True)
| [
[
1,
0,
0.2031,
0.0156,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.2188,
0.0156,
0,
0.66,
0.125,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.2344,
0.0156,
0,
0.6... | [
"import sys",
"import os.path",
"import tempfile",
"import shutil",
"from distutils.core import setup, Extension",
"import distutils.ccompiler",
"import distutils.dep_util",
"try:\n __default_compiler = distutils.ccompiler.new_compiler()\nexcept:\n __default_compiler = None",
" __default_compiler... |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| [
[
1,
0,
0.0634,
0.0049,
0,
0.66,
0,
291,
0,
1,
0,
0,
291,
0,
0
],
[
1,
0,
0.0683,
0.0049,
0,
0.66,
0.5,
878,
0,
1,
0,
0,
878,
0,
0
],
[
3,
0,
0.5439,
0.9171,
0,
0.6... | [
"import pydoc",
"import inspect",
"class DocGen:\n \"\"\"A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code.\"\"\"\n def __init__(self, name, ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from ctypes import *
def setProcName(name):
"""Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases."""
# Call the process control function...
libc = cdll.LoadLibrary('libc.so.6')
libc.prctl(15, c_char_p(name), 0, 0, 0)
# Update argv...
charPP = POINTER(POINTER(c_char))
argv = charPP.in_dll(libc,'_dl_argv')
size = libc.strlen(argv[0])
libc.strncpy(argv[0],c_char_p(name),size)
if __name__=='__main__':
# Quick test that it works...
import os
ps1 = 'ps'
ps2 = 'ps -f'
os.system(ps1)
os.system(ps2)
setProcName('wibble_wobble')
os.system(ps1)
os.system(ps2)
| [
[
1,
0,
0.3636,
0.0227,
0,
0.66,
0,
182,
0,
1,
0,
0,
182,
0,
0
],
[
2,
0,
0.5682,
0.25,
0,
0.66,
0.5,
903,
0,
1,
0,
0,
0,
0,
9
],
[
8,
1,
0.4773,
0.0227,
1,
0.11,
... | [
"from ctypes import *",
"def setProcName(name):\n \"\"\"Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differin... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import multiprocessing as mp
import multiprocessing.synchronize # To make sure we have all the functionality.
import types
import marshal
import unittest
def repeat(x):
"""A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant."""
while True: yield x
def run_code(code,args):
"""Internal use function that does the work in each process."""
code = marshal.loads(code)
func = types.FunctionType(code, globals(), '_')
return func(*args)
def mp_map(func, *iters, **keywords):
"""A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity."""
if 'pool' in keywords: pool = keywords['pool']
else: pool = mp.Pool()
code = marshal.dumps(func.func_code)
jobs = []
for args in zip(*iters):
jobs.append(pool.apply_async(run_code,(code,args)))
for i in xrange(len(jobs)):
jobs[i] = jobs[i].get()
return jobs
class TestMpMap(unittest.TestCase):
def test_simple1(self):
data = ['a','b','c','d']
def noop(data):
return data
data_noop = mp_map(noop, data)
self.assertEqual(data, data_noop)
def test_simple2(self):
data = [x for x in xrange(1000)]
data_double = mp_map(lambda a: a*2, data)
self.assertEqual(map(lambda a: a*2,data), data_double)
def test_gen(self):
def gen():
for i in xrange(100): yield i
data_double = mp_map(lambda a: a*2, gen())
self.assertEqual(map(lambda a: a*2,gen()), data_double)
def test_repeat(self):
def mult(a,b):
return a*b
data = [x for x in xrange(50,5000,5)]
data_triple = mp_map(mult, data, repeat(3))
self.assertEqual(map(lambda a: a*3,data),data_triple)
def test_none(self):
data = []
data_sqr = mp_map(lambda x: x*x, data)
self.assertEqual([],data_sqr)
if __name__ == '__main__':
unittest.main()
| [
[
1,
0,
0.1456,
0.0097,
0,
0.66,
0,
901,
0,
1,
0,
0,
901,
0,
0
],
[
1,
0,
0.1553,
0.0097,
0,
0.66,
0.1111,
99,
0,
1,
0,
0,
99,
0,
0
],
[
1,
0,
0.1748,
0.0097,
0,
0.... | [
"import multiprocessing as mp",
"import multiprocessing.synchronize # To make sure we have all the functionality.",
"import types",
"import marshal",
"import unittest",
"def repeat(x):\n \"\"\"A generator that repeats the input forever - can be used with the mp_map function to give data to a function tha... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Defines helper functions for accessing numpy arrays...
numpy_util_code = start_cpp() + """
#ifndef NUMPY_UTIL_CODE
#define NUMPY_UTIL_CODE
float & Float1D(PyArrayObject * arr, int index = 0)
{
return *(float*)(arr->data + index*arr->strides[0]);
}
float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
unsigned char & Byte1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index*arr->strides[0]);
}
unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
int & Int1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index*arr->strides[0]);
}
int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
#endif
"""
| [
[
1,
0,
0.1923,
0.0128,
0,
0.66,
0,
972,
0,
1,
0,
0,
972,
0,
0
],
[
14,
0,
0.6282,
0.7564,
0,
0.66,
1,
799,
4,
0,
0,
0,
0,
0,
1
]
] | [
"from utils.start_cpp import start_cpp",
"numpy_util_code = start_cpp() + \"\"\"\n#ifndef NUMPY_UTIL_CODE\n#define NUMPY_UTIL_CODE\n\nfloat & Float1D(PyArrayObject * arr, int index = 0)\n{\n return *(float*)(arr->data + index*arr->strides[0]);\n}"
] |
# -*- coding: utf-8 -*-
# Copyright 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
import math
import numpy
import numpy.linalg
import numpy.random
from wishart import Wishart
from gaussian import Gaussian
from student_t import StudentT
class GaussianPrior:
"""The conjugate prior for the multivariate Gaussian distribution. Maintains the 4 values and supports various operations of interest - initialisation of prior, Bayesian update, drawing a Gaussian and calculating the probability of a data point comming from a Gaussian drawn from the distribution. Not a particularly efficient implimentation, and it has no numerical protection against extremelly large data sets. Interface is not entirly orthogonal, due to the demands of real world usage."""
def __init__(self, dims):
"""Initialises with everything zeroed out, such that a prior must added before anything interesting is done. Supports cloning."""
if isinstance(dims, GaussianPrior):
self.invShape = dims.invShape.copy()
self.shape = dims.shape.copy() if dims.shape!=None else None
self.mu = dims.mu.copy()
self.n = dims.n
self.k = dims.k
else:
self.invShape = numpy.zeros((dims,dims), dtype=numpy.float32) # The inverse of lambda in the equations.
self.shape = None # Cached value - inverse is considered primary.
self.mu = numpy.zeros(dims, dtype=numpy.float32)
self.n = 0.0
self.k = 0.0
def reset(self):
"""Resets as though there is no data, other than the dimensions of course."""
self.invShape[:] = 0.0
self.shape = None
self.mu[:] = 0.0
self.n = 0.0
self.k = 0.0
def addPrior(self, mean, covariance, weight = None):
"""Adds a prior to the structure, as an estimate of the mean and covariance matrix, with a weight which can be interpreted as how many samples that estimate is worth. Note the use of 'add' - you can call this after adding actual samples, or repeatedly. If weight is omitted it defaults to the number of dimensions, as the total weight in the system must match or excede this value before draws etc can be done."""
if weight==None: weight = float(self.mu.shape[0])
delta = mean - self.mu
self.invShape += weight * covariance # *weight converts to a scatter matrix.
self.invShape += ((self.k*weight)/(self.k+weight)) * numpy.outer(delta,delta)
self.shape = None
self.mu += (weight/(self.k+weight)) * delta
self.n += weight
self.k += weight
def addSample(self, sample, weight=1.0):
"""Updates the prior given a single sample drawn from the Gaussian being estimated. Can have a weight provided, in which case it will be equivalent to repetition of that data point, where the repetition count can be fractional."""
sample = numpy.asarray(sample, dtype=numpy.float32)
if len(sample.shape)==0: sample.shape = (1,)
delta = sample - self.mu
self.invShape += (weight*self.k/(self.k+weight)) * numpy.outer(delta,delta)
self.shape = None
self.mu += delta * (weight / (self.k+weight))
self.n += weight
self.k += weight
def remSample(self, sample):
"""Does the inverse of addSample, to in effect remove a previously added sample. Note that the issues of floating point (in-)accuracy mean its not perfect, and removing all samples is bad if there is no prior. Does not support weighting - effectvily removes a sample of weight 1."""
sample = numpy.asarray(sample, dtype=numpy.float32)
if len(sample.shape)==0: sample.shape = (1,)
delta = sample - self.mu
self.k -= 1.0
self.n -= 1.0
self.mu -= delta / self.k
self.invShape -= ((self.k+1.0)/self.k) * numpy.outer(delta,delta)
self.shape = None
def addSamples(self, samples, weight = None):
"""Updates the prior given multiple samples drawn from the Gaussian being estimated. Expects a data matrix ([sample, position in sample]), or an object that numpy.asarray will interpret as such. Note that if you have only a few samples it might be faster to repeatedly call addSample, as this is designed to be efficient for hundreds+ of samples. You can optionally weight the samples, by providing an array to the weight parameter."""
samples = numpy.asarray(samples, dtype=numpy.float32)
# Calculate the mean and scatter matrices...
if weight==None:
# Unweighted samples...
# Calculate the mean and scatter matrix...
d = self.mu.shape[0]
num = samples.shape[0]
mean = numpy.average(samples, axis=0)
scatter = numpy.tensordot(delta, delta, ([0],[0]))
else:
# Weighted samples...
# Calculate the mean and scatter matrix...
d = self.mu.shape[0]
num = weight.sum()
mean = numpy.average(samples, axis=0, weights=weight)
delta = samples - mean.reshape((1,-1))
scatter = numpy.tensordot(weight.reshape((-1,1))*delta, delta, ([0],[0]))
# Update parameters...
delta = mean-self.mu
self.invShape += scatter
self.invShape += ((self.k*num)/(self.k+num)) * numpy.outer(delta,delta)
self.shape = None
self.mu += (num/(self.k+num)) * delta
self.n += num
self.k += num
def addGP(self, gp):
"""Adds another Gaussian prior, combining the two."""
delta = gp.mu - self.mu
self.invShape += gp.invShape
self.invShape += ((gp.k*self.k)/(gp.k+self.k)) * numpy.outer(delta,delta)
self.shape = None
self.mu += (gp.k/(self.k+gp.k)) * delta
self.n += gp.n
self.k += gp.k
def make_safe(self):
"""Checks for a singular inverse shape matrix - if singular replaces it with the identity. Also makes sure n and k are not less than the number of dimensions, clamping them if need be. obviously the result of this is quite arbitary, but its better than getting a crash from bad data."""
dims = self.mu.shape[0]
det = math.fabs(numpy.linalg.det(self.invShape))
if det<1e-3:
self.invShape = numpy.identity(dims, dtype=numpy.float32)
if self.n<dims: self.n = dims
if self.k<1e-3: self.k = 1e-3
def reweight(self, newN = None, newK = None):
"""A slightly cheaky method that reweights the gp such that it has the new values of n and k, effectivly adjusting the relevant weightings of the samples - can be useful for generating a prior for some GPs using the data stored in those GPs. If a new k is not provided it is set to n; if a new n is not provided it is set to the number of dimensions."""
if newN==None: newN = float(self.mu.shape[0])
if newK==None: newK = newN
self.invShape *= newN / self.n
self.shape = None
self.n = newN
self.k = newK
def getN(self):
"""Returns n."""
return self.n
def getK(self):
"""Returns k."""
return self.k
def getMu(self):
"""Returns mu."""
return self.mu
def getLambda(self):
"""Returns lambda."""
if self.shape==None:
self.shape = numpy.linalg.inv(self.invShape)
return self.shape
def getInverseLambda(self):
"""Returns the inverse of lambda."""
return self.invShape
def safe(self):
"""Returns true if it is possible to sample the prior, work out the probability of samples or work out the probability of samples being drawn from a collapsed sample - basically a test that there is enough information."""
return self.n>=self.mu.shape[0] and self.k>0.0
def prob(self, gauss):
"""Returns the probability of drawing the provided Gaussian from this prior."""
d = self.mu.shape[0]
wishart = Wishart(d)
gaussian = Gaussian(d)
wishart.setDof(self.n)
wishart.setScale(self.getLambda())
gaussian.setMean(self.mu)
gaussian.setPrecision(self.k*gauss.getPrecision())
return wishart.prob(gauss.getPrecision()) * gaussian.prob(gauss.getMean())
def intProb(self):
"""Returns a multivariate student-t distribution object that gives the probability of drawing a sample from a Gaussian drawn from this prior, with the Gaussian integrated out. You may then call the prob method of this object on each sample obtained."""
d = self.mu.shape[0]
st = StudentT(d)
dof = self.n-d+1.0
st.setDOF(dof)
st.setLoc(self.mu)
mult = self.k*dof / (self.k+1.0)
st.setInvScale(mult * self.getLambda())
return st
def sample(self):
"""Returns a Gaussian, drawn from this prior."""
d = self.mu.shape[0]
wishart = Wishart(d)
gaussian = Gaussian(d)
ret = Gaussian(d)
wishart.setDof(self.n)
wishart.setScale(self.getLambda())
ret.setPrecision(wishart.sample())
gaussian.setPrecision(self.k*ret.getPrecision())
gaussian.setMean(self.mu)
ret.setMean(gaussian.sample())
return ret
def __str__(self):
return '{n:%f, k:%f, mu:%s, lambda:%s}'%(self.n, self.k, str(self.mu), str(self.getLambda()))
| [
[
1,
0,
0.0568,
0.0044,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
1,
0,
0.0611,
0.0044,
0,
0.66,
0.1429,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.0655,
0.0044,
0,
... | [
"import math",
"import numpy",
"import numpy.linalg",
"import numpy.random",
"from wishart import Wishart",
"from gaussian import Gaussian",
"from student_t import StudentT",
"class GaussianPrior:\n \"\"\"The conjugate prior for the multivariate Gaussian distribution. Maintains the 4 values and suppo... |
#! /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 gcp
from utils import doc_gen
# Setup...
doc = doc_gen.DocGen('gcp', 'Gaussian Conjugate Prior', 'Library of distributions focused on the Gaussian and its conjugate prior')
doc.addFile('readme.txt', 'Overview')
# Classes...
doc.addClass(gcp.Gaussian)
doc.addClass(gcp.GaussianInc)
doc.addClass(gcp.Wishart)
doc.addClass(gcp.StudentT)
doc.addClass(gcp.GaussianPrior)
| [
[
1,
0,
0.4667,
0.0333,
0,
0.66,
0,
884,
0,
1,
0,
0,
884,
0,
0
],
[
1,
0,
0.5333,
0.0333,
0,
0.66,
0.125,
970,
0,
1,
0,
0,
970,
0,
0
],
[
14,
0,
0.7,
0.0333,
0,
0.6... | [
"import gcp",
"from utils import doc_gen",
"doc = doc_gen.DocGen('gcp', 'Gaussian Conjugate Prior', 'Library of distributions focused on the Gaussian and its conjugate prior')",
"doc.addFile('readme.txt', 'Overview')",
"doc.addClass(gcp.Gaussian)",
"doc.addClass(gcp.GaussianInc)",
"doc.addClass(gcp.Wish... |
# -*- 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.
from gaussian import Gaussian
from gaussian_inc import GaussianInc
from wishart import Wishart
from student_t import StudentT
from gaussian_prior import GaussianPrior
| [
[
1,
0,
0.7647,
0.0588,
0,
0.66,
0,
78,
0,
1,
0,
0,
78,
0,
0
],
[
1,
0,
0.8235,
0.0588,
0,
0.66,
0.25,
680,
0,
1,
0,
0,
680,
0,
0
],
[
1,
0,
0.8824,
0.0588,
0,
0.66... | [
"from gaussian import Gaussian",
"from gaussian_inc import GaussianInc",
"from wishart import Wishart",
"from student_t import StudentT",
"from gaussian_prior import GaussianPrior"
] |
# -*- coding: utf-8 -*-
# Copyright 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
import math
import numpy
import numpy.linalg
import numpy.random
class Gaussian:
"""A basic multivariate Gaussian class. Has caching to avoid duplicate calculation."""
def __init__(self, dims):
"""dims is the number of dimensions. Initialises with mu at the origin and the identity matrix for the precision/covariance. dims can also be another Gaussian object, in which case it acts as a copy constructor."""
if isinstance(dims, Gaussian):
self.mean = dims.mean.copy()
self.precision = dims.precision.copy() if dims.precision!=None else None
self.covariance = dims.covariance.copy() if dims.covariance!=None else None
self.norm = dims.norm
self.cholesky = dims.cholesky.copy() if dims.cholesky!=None else None
else:
self.mean = numpy.zeros(dims, dtype=numpy.float32)
self.precision = numpy.identity(dims, dtype=numpy.float32)
self.covariance = None
self.norm = None
self.cholesky = None
def setMean(self, mean):
"""Sets the mean - you can use anything numpy will interprete as a 1D array of the correct length."""
nm = numpy.array(mean, dtype=numpy.float32)
assert(nm.shape==self.mean.shape)
self.mean = nm
def setPrecision(self, precision):
"""Sets the precision matrix. Alternativly you can use the setCovariance method."""
np = numpy.array(precision, dtype=numpy.float32)
assert(np.shape==(self.mean.shape[0],self.mean.shape[0]))
self.precision = np
self.covariance = None
self.norm = None
self.cholesky = None
def setCovariance(self, covariance):
"""Sets the covariance matrix. Alternativly you can use the setPrecision method."""
nc = numpy.array(covariance, dtype=numpy.float32)
assert(nc.shape==(self.mean.shape[0],self.mean.shape[0]))
self.covariance = nc
self.precision = None
self.norm = None
self.cholesky = None
def getMean(self):
"""Returns the mean."""
return self.mean
def getPrecision(self):
"""Returns the precision matrix."""
if self.precision==None:
self.precision = numpy.linalg.inv(self.covariance)
return self.precision
def getCovariance(self):
"""Returns the covariance matrix."""
if self.covariance==None:
self.covariance = numpy.linalg.inv(self.precision)
return self.covariance
def getNorm(self):
"""Returns the normalising constant of the distribution. Typically for internal use only."""
if self.norm==None:
self.norm = math.pow(2.0*math.pi,-0.5*self.mean.shape[0]) * math.sqrt(numpy.linalg.det(self.getPrecision()))
return self.norm
def prob(self, x):
"""Given a vector x evaluates the probability density function at that point."""
x = numpy.asarray(x)
offset = x - self.mean
val = numpy.dot(offset,numpy.dot(self.getPrecision(),offset))
return self.getNorm() * math.exp(-0.5 * val)
def sample(self):
"""Draws and returns a sample from the distribution."""
if self.cholesky==None:
self.cholesky = numpy.linalg.cholesky(self.getCovariance())
z = numpy.random.normal(size=self.mean.shape)
return self.mean + numpy.dot(self.cholesky,z)
def __str__(self):
return '{mean:%s, covar:%s}'%(str(self.mean), str(self.getCovariance()))
| [
[
1,
0,
0.1287,
0.0099,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
1,
0,
0.1386,
0.0099,
0,
0.66,
0.25,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.1485,
0.0099,
0,
0.... | [
"import math",
"import numpy",
"import numpy.linalg",
"import numpy.random",
"class Gaussian:\n \"\"\"A basic multivariate Gaussian class. Has caching to avoid duplicate calculation.\"\"\"\n def __init__(self, dims):\n \"\"\"dims is the number of dimensions. Initialises with mu at the origin and the id... |
#! /usr/bin/env python
# Copyright 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
import dpgmm
from utils import doc_gen
# Setup...
doc = doc_gen.DocGen('dpgmm', 'Dirichlet Process Gaussian Mixture Model', 'Dynamically resizing Gaussian mixture model')
doc.addFile('readme.txt', 'Overview')
# Classes...
doc.addClass(dpgmm.DPGMM)
| [
[
1,
0,
0.52,
0.04,
0,
0.66,
0,
712,
0,
1,
0,
0,
712,
0,
0
],
[
1,
0,
0.6,
0.04,
0,
0.66,
0.25,
970,
0,
1,
0,
0,
970,
0,
0
],
[
14,
0,
0.8,
0.04,
0,
0.66,
0.5,
... | [
"import dpgmm",
"from utils import doc_gen",
"doc = doc_gen.DocGen('dpgmm', 'Dirichlet Process Gaussian Mixture Model', 'Dynamically resizing Gaussian mixture model')",
"doc.addFile('readme.txt', 'Overview')",
"doc.addClass(dpgmm.DPGMM)"
] |
# 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 numpy
import numpy.random
from kde_inc.kde_inc import KDE_INC
from prob_cat import ProbCat
class ClassifyBagKDE(ProbCat):
"""This is the same as ClassifyKDE, except it has multiple instances of KDE_INC for each class. It uses bagging with a boostrap sample to train each set of classifiers, including one density estimate per bagging instance. Because it is incrimental it uses the Poisson(1) approximation of a bootstrap sample."""
def __init__(self, prec, cap = 32, bag_size = 16, useSingle = False):
"""You provide the precision that is to be used (As a 2D numpy array, so it implicitly provides the number of dimensions.), the cap on the number of components in the KDE_INC objects and the number of models to maintain. useSingle indicates if it should also maintain a non-bootstraped model, which it will use when non-list accesses are requested. This happens to mean that with the active learning module for qbc based algorithms you get list mode, but for testing/using the model it reverts to a single model which will generally do better than a set of bootstrapped models."""
self.prec = numpy.array(prec, dtype=numpy.float32)
self.cap = cap
self.bags = map(lambda _: dict(), xrange(bag_size)) # Dictionary for each model, indexed by category. Additionally, the density estimate is indexed by 'None'.
self.counts = defaultdict(int) # Number of instances of each category that have been provided - models might have different numbers due to the bootstrap sampling. Uses None for the density estimate count.
self.single = dict() if useSingle else None
def setPrec(self, prec):
"""Changes the precision matrix - must be called before any samples are added, and must have the same dimensions as the current one."""
self.prec = numpy.array(prec, dtype=numpy.float32)
self.prior.setPrec(self.prec / (self.mult*self.mult))
def priorAdd(self, sample):
self.counts[None] += 1
for bag in self.bags:
if None not in bag:
bag[None] = KDE_INC(self.prec, self.cap)
for _ in xrange(numpy.random.poisson(1.0)):
bag[None].add(sample)
if self.single!=None:
if None not in self.single:
self.single[None] = KDE_INC(self.prec, self.cap)
self.single[None].add(sample)
def add(self, sample, cat):
self.counts[cat] += 1
for bag in self.bags:
if cat not in bag:
bag[cat] = KDE_INC(self.prec, self.cap)
for _ in xrange(numpy.random.poisson(1.0)):
bag[cat].add(sample)
if self.single!=None:
if cat not in self.single:
self.single[cat] = KDE_INC(self.prec, self.cap)
self.single[cat].add(sample)
def getSampleTotal(self):
return sum(self.counts.itervalues()) - self.counts[None]
def getCatTotal(self):
return len(self.counts) - (1 if None in self.counts else 0)
def getCatList(self):
return filter(lambda cat: cat!=None, self.counts.keys())
def getCatCounts(self):
ret = dict(self.counts)
if None in ret: del ret[None]
return ret
def listMode(self):
return True
def getDataProb(self, sample, state = None):
if self.single!=None:
ret = defaultdict(float)
for cat, mod in self.single.iteritems():
ret[cat] = mod.prob(sample)
return ret
else:
ret = defaultdict(float)
for bag in self.bags:
for key, mod in bag.iteritems():
ret[key] += mod.prob(sample)
for key in ret.iterkeys():
ret[key] /= len(bag)
return ret
def getDataNLL(self, sample, state = None):
if self.single!=None:
ret = defaultdict(lambda: -1e64)
for cat, mod in self.single.iteritems():
ret[cat] = mod.nll(sample)
return ret
else:
ret = defaultdict(list)
for bag in self.bags:
for key, mod in bag.iteritems():
ret[key].append(mod.nll(sample))
log_len_bags = numpy.log(len(self.bags))
for key in ret.iterkeys():
high = max(ret[key])
ret[key] = high + numpy.log(numpy.exp(numpy.array(ret[key])-high).sum())
ret[key] -= log_len_bags
return ret
def getDataProbList(self, sample, state = None):
ret = []
for bag in self.bags:
ans = defaultdict(float)
for key, mod in bag.iteritems():
ans[key] = mod.prob(sample)
ret.append(ans)
return ret
def getDataNLLList(self, sample, state = None):
ret = []
for bag in self.bags:
ans = defaultdict(lambda: -1e64)
for key, mod in bag.iteritems():
ans[key] = mod.nll(sample)
ret.append(ans)
return ret
| [
[
1,
0,
0.0821,
0.0075,
0,
0.66,
0,
193,
0,
1,
0,
0,
193,
0,
0
],
[
1,
0,
0.0896,
0.0075,
0,
0.66,
0.2,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.097,
0.0075,
0,
0.66... | [
"from collections import defaultdict",
"import numpy",
"import numpy.random",
"from kde_inc.kde_inc import KDE_INC",
"from prob_cat import ProbCat",
"class ClassifyBagKDE(ProbCat):\n \"\"\"This is the same as ClassifyKDE, except it has multiple instances of KDE_INC for each class. It uses bagging with a ... |
# 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/>.
import math
import numpy
import scipy.misc
from video_node import *
class StepScale(VideoNode):
"""Scales a video up, by an integer number of repetitons of each pixel."""
def __init__(self, scale = 2):
"""You provide scale, how many times to repeat each pixel in both x and y."""
self.scale = scale
self.video = None
self.channel = 0
self.output = None
def width(self):
return self.video.width() * self.scale
def height(self):
return self.video.height() * self.scale
def fps(self):
return self.video.fps()
def frameCount(self):
return self.video.frameCount()
def inputCount(self):
return 1
def inputMode(self, channel=0):
return MODE_RGB
def inputName(self, channel=0):
return 'Video stream to be scaled'
def source(self, toChannel, video, videoChannel=0):
self.video = video
self.channel = videoChannel
def dependencies(self):
return [self.video]
def nextFrame(self):
# Fetch the frame...
img = self.video.fetch(self.channel)
if img==None:
self.output = None
return False
if len(img.shape)==2:
img = img.reshape((img.shape[0],img.shape[1],1))
# If needed create an output...
if self.output==None:
self.output = numpy.empty((img.shape[0]*self.scale,img.shape[1]*self.scale,3), dtype=numpy.float32)
# Time to scale...
self.output[:,:,:] = numpy.repeat(numpy.repeat(img, self.scale, axis=0), self.scale, axis=1)
return True
def outputCount(self):
return 1
def outputMode(self, channel=0):
return MODE_RGB
def outputName(self, channel=0):
return 'Larger video stream'
def fetch(self, channel=0):
return self.output
| [
[
1,
0,
0.1875,
0.0104,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
1,
0,
0.1979,
0.0104,
0,
0.66,
0.25,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.2083,
0.0104,
0,
0.... | [
"import math",
"import numpy",
"import scipy.misc",
"from video_node import *",
"class StepScale(VideoNode):\n \"\"\"Scales a video up, by an integer number of repetitons of each pixel.\"\"\"\n def __init__(self, scale = 2):\n \"\"\"You provide scale, how many times to repeat each pixel in both x and y... |
# 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/>.
import numpy
import scipy.weave as weave
from utils.start_cpp import start_cpp
from video_node import *
five_word_colours = [(0.5,0.5,0.5), (1.0,0.0,0.0), (0.5,1.0,0.0), (0.0,1.0,1.0), (0.5,0.0,1.0)]
class FiveWord(VideoNode):
"""Quantises a video stream into five words per location, specifically 4 directions and no motion. Divides the image into a grid of locations and has a simple vote in each grid cell, with a threshold to decide the difference between moving and not. Has 2 inputs - a flow field from the optical flow and a mask from the background subtraction. Assumes that grid size is a multiple of the dimensions """
def __init__(self, threshold=0.25, gridSize=8):
self.threshold = threshold
self.gridSize = gridSize
self.flow = None
self.flowChannel = 0
self.mask = None
self.maskChannel = 0
self.output = None
def width(self):
return self.flow.width() / self.gridSize
def height(self):
return self.flow.height() / self.gridSize
def fps(self):
return self.flow.fps()
def frameCount(self):
return self.flow.frameCount()
def inputCount(self):
return 2
def inputMode(self, channel=0):
if channel==0: return MODE_FLOW
else: return MODE_MASK
def inputName(self, channel=0):
if channel==0: return 'The flow field providing motion.'
else: return 'The mask indicating foregound areas.'
def source(self, toChannel, video, videoChannel=0):
if toChannel==0:
self.flow = video
self.flowChannel = videoChannel
else:
self.mask = video
self.maskChannel = videoChannel
def wordCount(self):
return 5
def suggestedColours(self):
return five_word_colours
def dependencies(self):
return [self.flow, self.mask]
def nextFrame(self):
# If first call initialise data structures...
if self.output==None:
self.output = numpy.empty((self.height(), self.width()), dtype=numpy.int32)
self.vote = numpy.empty((self.height(), self.width(), 6), dtype=numpy.int32)
# Get the inputs...
flow = self.flow.fetch(self.flowChannel)
mask = self.mask.fetch(self.maskChannel)
# Do the work...
code = start_cpp() + """
// Zero the vote array - first 5 entrys map to the words, 6th entry is the vote for 'no-word'...
for (int y=0;y<Nvote[0];y++)
{
for (int x=0;x<Nvote[1];x++)
{
for (int c=0;c<Nvote[2];c++) VOTE3(y,x,c) = 0;
}
}
// Iterate the pixels, make them each cast a vote...
for (int y=0;y<Nflow[0];y++)
{
for (int x=0;x<Nflow[1];x++)
{
int vy = y / gridSize;
int vx = x / gridSize;
if (MASK2(y,x)!=0)
{
float speed = sqrt(FLOW3(y,x,0)*FLOW3(y,x,0) + FLOW3(y,x,1)*FLOW3(y,x,1));
if (speed<threshold) VOTE3(vy,vx,0) += 1;
else
{
if (fabs(FLOW3(y,x,0))>fabs(FLOW3(y,x,1)))
{
// dy is greater than dx...
if (FLOW3(y,x,0)>0.0) VOTE3(vy,vx,2) += 1;
else VOTE3(vy,vx,4) += 1;
}
else
{
// dx is greater than dy...
if (FLOW3(y,x,1)>0.0) VOTE3(vy,vx,1) += 1;
else VOTE3(vy,vx,3) += 1;
}
}
}
else VOTE3(vy,vx,5) += 1;
}
}
// Count the votes, declare the winners...
for (int y=0;y<Nvote[0];y++)
{
for (int x=0;x<Nvote[1];x++)
{
int maxIndex = 0;
for (int c=1;c<Nvote[2];c++)
{
if (VOTE3(y,x,c)>VOTE3(y,x,maxIndex)) maxIndex = c;
}
if (maxIndex==5) maxIndex = -1;
OUTPUT2(y,x) = maxIndex;
}
}
"""
output = self.output
vote = self.vote
threshold = self.threshold
gridSize = self.gridSize
weave.inline(code, ['flow', 'mask', 'output', 'vote', 'threshold', 'gridSize'])
return True
def outputCount(self):
return 1
def outputMode(self, channel=0):
return MODE_WORD
def outputName(self, channel=0):
return 'Grid of words for each grid location. -1 for no word, 0 for stationary object, then 1 for +ve x, 2 for +ve y, 3 for -ve x and 4 for -ve y.'
def fetch(self, channel=0):
return self.output
| [
[
1,
0,
0.1011,
0.0056,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.1067,
0.0056,
0,
0.66,
0.2,
829,
0,
1,
0,
0,
829,
0,
0
],
[
1,
0,
0.118,
0.0056,
0,
0.66... | [
"import numpy",
"import scipy.weave as weave",
"from utils.start_cpp import start_cpp",
"from video_node import *",
"five_word_colours = [(0.5,0.5,0.5), (1.0,0.0,0.0), (0.5,1.0,0.0), (0.0,1.0,1.0), (0.5,0.0,1.0)]",
"class FiveWord(VideoNode):\n \"\"\"Quantises a video stream into five words per location,... |
# 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 collections import defaultdict
import numpy
from video_node import *
class CombineGrid(VideoNode):
"""Given multiple MODE_RGB streams as input this combines them into a single output, arranged as a grid. Resizes appropriatly and handles gaps."""
def __init__(self, horizontal, vertical = 1):
self.video = map(lambda _: map(lambda _: None, xrange(horizontal)), xrange(vertical))
self.channel = map(lambda _: map(lambda _: 0, xrange(horizontal)), xrange(vertical))
self.output = None
def width(self):
widths = defaultdict(int)
for py in xrange(len(self.video)):
for px in xrange(len(self.video[py])):
if self.video[py][px]!=None:
widths[px] = max((widths[px],self.video[py][px].width()))
return sum(widths.values())
def height(self):
heights = defaultdict(int)
for py in xrange(len(self.video)):
for px in xrange(len(self.video[py])):
if self.video[py][px]!=None:
heights[py] = max((heights[py],self.video[py][px].height()))
return sum(heights.values())
def fps(self):
for py in xrange(len(self.video)):
for px in xrange(len(self.video[py])):
if self.video[py][px]!=None:
return self.video[py][px].fps()
def frameCount(self):
ret = None
for py in xrange(len(self.video)):
for px in xrange(len(self.video[py])):
if self.video[py][px]!=None:
val = self.video[py][px].frameCount()
if ret==None or val<ret:
ret = val
return ret
def inputCount(self):
return len(self.video) * len(self.video[0])
def inputMode(self, channel=0):
return MODE_RGB
def inputName(self, channel=0):
return 'A video stream for a particular grid cell'
def source(self, toChannel, video, videoChannel=0):
py = toChannel // len(self.video[0])
px = toChannel - py*len(self.video[0])
self.video[py][px] = video
self.channel[py][px] = videoChannel
def dependencies(self):
ret = []
for row in self.video: ret += row
return filter(lambda a: a!=None,ret)
def nextFrame(self):
# Work out size info...
widths = defaultdict(int)
heights = defaultdict(int)
for py in xrange(len(self.video)):
for px in xrange(len(self.video[py])):
if self.video[py][px]!=None:
widths[px] = max((widths[px],self.video[py][px].width()))
heights[py] = max((heights[py],self.video[py][px].height()))
# Create the output image if needed...
totalHeight = sum(heights.values())
totalWidth = sum(widths.values())
if self.output==None or self.output.shape[0]!=totalHeight or self.output.shape[1]!=totalWidth:
self.output = numpy.empty((totalHeight,totalWidth,3),dtype=numpy.float32)
# Zero buffer out...
self.output[:,:,:] = 0.0
# Make size dictionaries culumative...
for py in xrange(len(self.video)): heights[py] += heights[py-1]
for px in xrange(len(self.video[0])): widths[px] += widths[px-1]
# Copy each video in turn...
ret = True
for py in xrange(len(self.video)):
for px in xrange(len(self.video[py])):
if self.video[py][px]!=None:
# Fetch the frame, handle non-existance...
frame = self.video[py][px].fetch(self.channel[py][px])
if frame==None:
ret = False
break
# Copy it to the right place...
baseY = heights[py-1]
baseX = widths[px-1]
if len(frame.shape)==2: # Support for greyscale.
frame = numpy.dstack((frame,frame,frame))
self.output[baseY:baseY+frame.shape[0],baseX:baseX+frame.shape[1],:] = frame
return ret
def outputCount(self):
return 1
def outputMode(self, channel=0):
return MODE_RGB
def outputName(self, channel=0):
return 'All input streams combined'
def fetch(self, channel=0):
return self.output
| [
[
1,
0,
0.125,
0.0069,
0,
0.66,
0,
193,
0,
1,
0,
0,
193,
0,
0
],
[
1,
0,
0.1319,
0.0069,
0,
0.66,
0.3333,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.1458,
0.0069,
0,
0... | [
"from collections import defaultdict",
"import numpy",
"from video_node import *",
"class CombineGrid(VideoNode):\n \"\"\"Given multiple MODE_RGB streams as input this combines them into a single output, arranged as a grid. Resizes appropriatly and handles gaps.\"\"\"\n def __init__(self, horizontal, vertic... |
# 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/>.
import os.path
import numpy
import scipy.weave as weave
import cv
from utils.cvarray import cv2array
from utils.start_cpp import start_cpp
from video_node import *
class StatsCD(VideoNode):
"""Calculates the stats required by the changedetection.net website for analysing a background subtraction algorithm, given the data in the format they provide."""
def __init__(self, path):
"""You provide the path of the dataset and then the input to channel 0 is the background subtraction mask."""
self.path = path
# Open the region of interest and convert it into a mask we can use...
roi = cv.LoadImage(os.path.join(path, 'ROI.bmp'))
self.roi = (cv2array(roi)!=0).astype(numpy.uint8)
if len(self.roi.shape)==3: self.roi = self.roi[:,:,0]
# Get the temporal range of the frames we are to analyse...
data = open(os.path.join(path, 'temporalROI.txt'), 'r').read()
tokens = data.split()
assert(len(tokens)==2)
self.start = int(tokens[0])
self.end = int(tokens[1]) # Note that these are inclusive.
# Confusion matrix - first index is truth, second guess, bg=0, fg=1...
self.con = numpy.zeros((2,2), dtype=numpy.int32)
# Shadow matrix - for all pixels that are in shadow records how many are background (0) and how many are foreground (1)...
self.shadow = numpy.zeros(2, dtype=numpy.int32)
# Basic stuff...
self.frame = 0
self.video = None
self.channel = 0
def width(self):
return self.video.width()
def height(self):
return self.video.height()
def fps(self):
return self.video.fps()
def frameCount(self):
return self.video.frameCount()
def inputCount(self):
return 1
def inputMode(self, channel=0):
return MODE_MASK
def inputName(self, channel=0):
return 'Estimated mask.'
def source(self, toChannel, video, videoChannel=0):
self.video = video
self.channel = videoChannel
def dependencies(self):
return [self.video]
def nextFrame(self):
# Increase frame number - need to be 1 based for this...
self.frame += 1
if self.frame>=self.start and self.frame<=self.end:
# Fetch the provided mask...
mask = self.video.fetch(self.channel)
# Load the ground truth file...
fn = os.path.join(self.path, 'groundtruth/gt%06i.png'%self.frame)
gt = cv2array(cv.LoadImage(fn))
gt = gt.astype(numpy.uint8)
if len(gt.shape)==3: gt = gt[:,:,0]
# Loop the pixels and analyse each one, summing into the confusion matrix...
code = start_cpp() + """
for (int y=0; y<Ngt[0]; y++)
{
for (int x=0; x<Ngt[1]; x++)
{
if ((ROI2(y,x)!=0)&&(GT2(y,x)!=170))
{
int t = (GT2(y,x)==255)?1:0;
int g = (MASK2(y,x)!=0)?1:0;
CON2(t,g) += 1;
if (GT2(y,x)==50)
{
SHADOW1(g) += 1;
}
}
}
}
"""
roi = self.roi
con = self.con
shadow = self.shadow
weave.inline(code, ['mask', 'gt', 'roi', 'con', 'shadow'])
return self.frame<=self.end
def outputCount(self):
return 0
def getCon(self):
"""Returns the confusion matrix - [truth, guess], 0=background, 1=foreground."""
return self.con
def getRecall(self):
div = self.con[1,:].sum()
if div==0: return 0.0
else: return self.con[1,1] / float(div)
def getSpecficity(self):
return self.con[0,0] / float(self.con[0,:].sum())
def getFalsePosRate(self):
return self.con[0,1] / float(self.con[0,:].sum())
def getFalseNegRate(self):
return self.con[1,0] / float(self.con[1,:].sum())
def getPrecision(self):
div = self.con[:,1].sum()
if div==0: return 0.0
else: return self.con[1,1] / float(div)
def getFMeasure(self):
recall = self.getRecall()
precision = self.getPrecision()
div = precision + recall
if div<1e-12: return 0.0
else: return (2.0 * precision * recall) / div
def getPercentWrong(self):
return 100.0 * (self.con[0,1] + self.con[1,0]) / float(self.con.sum())
def getFalsePosRateShadow(self):
div = self.shadow.sum()
if div!=0: return self.shadow[1] / float(div)
else: return 0.0
| [
[
1,
0,
0.1017,
0.0056,
0,
0.66,
0,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.113,
0.0056,
0,
0.66,
0.1429,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.1186,
0.0056,
0,
0.6... | [
"import os.path",
"import numpy",
"import scipy.weave as weave",
"import cv",
"from utils.cvarray import cv2array",
"from utils.start_cpp import start_cpp",
"from video_node import *",
"class StatsCD(VideoNode):\n \"\"\"Calculates the stats required by the changedetection.net website for analysing a ... |
# 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/>.
import os.path
import math
import numpy
import numpy.linalg
try:
import scipy.weave as weave
except:
weave = None
from utils.start_cpp import start_cpp
from utils.make import make_mod
from video_node import *
# The OpenCL version - try to compile it, and use it if at all possible...
try:
make_mod('colour_bias_cl', os.path.dirname(__file__), ['manager_cl.h', 'open_cl_help.h', 'colour_bias_cl.c'], openCL=True)
import colour_bias_cl
except:
colour_bias_cl = None
class ColourBias(VideoNode):
"""This converts rgb colour to a luminance/chromaticity colour space - nothing special, specific or well defined. Its trick is that you can choose the scale of the luminance channel, to adjust distance in the space to emphasis differences in colour or lightness. Luminance is put into the red channel with chromaticity in green and blue. Done such that the volume of the colour space always remains as 1."""
def __init__(self, lumScale = 1.0, noiseFloor = 0.2, cl = None):
"""lumScale is how much to bias the luminance - high makes luminance matter, low makes chromaticity matter; 1 is no bias at all. noiseFloor stabalises the variance when it gets darker than the provided value, to prevent noise resulting in unstable chromaticity information - it must not exceed sqrt(3)/3. cl is the return value from getCL() on the manager object - if not provided OpenCL will not be used."""
self.chromaScale = 0.7176 * math.pow(1.0/lumScale,1.0/3.0)
self.lumScale = lumScale * self.chromaScale
self.noiseFloor = noiseFloor
self.video = None
self.channel = 0
self.output = None
self.inter = None
# Generate the rotation matrix...
sr2 = math.sqrt(1.0/2.0)
sr3 = math.sqrt(1.0/3.0)
sr6 = math.sqrt(1.0/6.0)
self.matrix = numpy.array([[sr3,sr3,sr3],[0,sr2,-sr2],[-2.0*sr6,sr6,sr6]])
self.cl = cl if colour_bias_cl!=None else None
self.cb_cl = None
def width(self):
return self.video.width()
def height(self):
return self.video.height()
def fps(self):
return self.video.fps()
def frameCount(self):
return self.video.frameCount()
def inputCount(self):
return 1
def inputMode(self, channel=0):
return MODE_RGB
def inputName(self, channel=0):
return 'Input rgb video stream.'
def source(self, toChannel, video, videoChannel=0):
self.video = video
self.channel = videoChannel
def dependencies(self):
return [self.video]
def nextFrame(self):
# Fetch the frame...
img = self.video.fetch(self.channel)
if img==None:
self.output = None
return False
# Handle the OpenCL object creation if needed...
if self.cb_cl==None and self.cl!=None:
try:
self.cb_cl = colour_bias_cl.ColourBiasCL(self.cl, self.width(), self.height(), os.path.abspath(os.path.dirname(__file__)))
self.cb_cl.chromaScale = self.chromaScale
self.cb_cl.lumScale = self.lumScale
self.cb_cl.noiseFloor = self.noiseFloor
self.cb_cl.post_change()
except:
self.cl = None
# Check we have a copy to mess with...
if self.output==None:
self.output = img.copy()
if weave==None: self.inter = img.copy()
# Run using OpenCl if possible...
if self.cb_cl!=None:
self.cb_cl.from_rgb(img)
self.cb_cl.fetch(self.output)
else:
# Do the conversion - per pixel matrix multiplication, a division to seperate chromacity and a scalling to give it a volume of 1, plus the luminance bias term...
if weave:
code = start_cpp() + """
for (int y=0;y<Noutput[0];y++)
{
for (int x=0;x<Noutput[1];x++)
{
// Rotate luminance into channel 0 (A matrix multiplication.)...
for (int r=0;r<3;r++)
{
OUTPUT3(y,x,r) = 0.0;
for (int c=0;c<3;c++)
{
OUTPUT3(y,x,r) += MATRIX2(r,c) * IMG3(y,x,c);
}
}
// Seperate chromacity, taking into account the noise floor and apply the luminance bias, which includes scaling to a volume of 1...
float cDiv = OUTPUT3(y,x,0);
if (cDiv<noiseFloor) cDiv = noiseFloor;
OUTPUT3(y,x,0) *= lumScale;
OUTPUT3(y,x,1) *= chromaScale / cDiv;
OUTPUT3(y,x,2) *= chromaScale / cDiv;
}
}
"""
output = self.output
matrix = self.matrix
lumScale = self.lumScale
chromaScale = self.chromaScale
noiseFloor = self.noiseFloor
weave.inline(code, ['img', 'output', 'matrix', 'lumScale', 'chromaScale', 'noiseFloor'])
else:
## Apply the rotation matrix...
for r in xrange(3):
self.inter[:,:,r] = (img * self.matrix[r,:].reshape((1,1,-1))).sum(axis=2)
## Divide by luminance to seperate chromacity...
self.inter[:,:,1] /= numpy.clip(self.inter[:,:,0], self.noiseFloor, 1e100)
self.inter[:,:,2] /= numpy.clip(self.inter[:,:,0], self.noiseFloor, 1e100)
# Rescale to get the distance biases...
self.output[:,:,0] = self.inter[:,:,0] * self.lumScale
self.output[:,:,1:] = self.inter[:,:,1:] * self.chromaScale
return True
def outputCount(self):
return 2
def outputMode(self, channel=0):
return MODE_RGB
def outputName(self, channel=0):
if channel==0: return 'Video stream with biased colour space.'
else: return 'Same as cahnnel 0, but with [0..1] normalisation - for visualisation.'
def fetch(self, channel=0):
if channel==0: return self.output
else: return self.inter
class ColourUnBias(VideoNode):
"""Does the exact opposite of ColourBias, assuming you provide the exact same parameters."""
def __init__(self, lumScale = 1.0, noiseFloor = 0.2, cl = None):
"""lumScale is how much to bias the luminance - high makes luminance matter, low makes chromaticity matter. cl is the return value from getCL() on the manager object - if not provided OpenCL will not be used."""
self.chromaScale = 0.7176 * math.pow(1.0/lumScale,1.0/3.0)
self.lumScale = lumScale * self.chromaScale
self.noiseFloor = noiseFloor
self.video = None
self.channel = 0
self.output = None
self.inter = None
# We are going to need the inverse of the matrix...
sr2 = math.sqrt(1.0/2.0)
sr3 = math.sqrt(1.0/3.0)
sr6 = math.sqrt(1.0/6.0)
matrix = numpy.array([[sr3,sr3,sr3],[0,sr2,-sr2],[-2.0*sr6,sr6,sr6]])
self.invMatrix = numpy.linalg.inv(matrix)
self.cl = cl if colour_bias_cl!=None else None
self.cb_cl = None
def width(self):
return self.video.width()
def height(self):
return self.video.height()
def fps(self):
return self.video.fps()
def frameCount(self):
return self.video.frameCount()
def inputCount(self):
return 1
def inputMode(self, channel=0):
return MODE_RGB
def inputName(self, channel=0):
return 'Input video stream, with biased colour.'
def source(self, toChannel, video, videoChannel=0):
self.video = video
self.channel = videoChannel
def dependencies(self):
return [self.video]
def nextFrame(self):
# Fetch the frame...
img = self.video.fetch(self.channel)
if img==None:
self.output = None
return False
# Handle the OpenCL object creation if needed...
if self.cb_cl==None and self.cl!=None:
try:
self.cb_cl = colour_bias_cl.ColourBiasCL(self.cl, self.width(), self.height(), os.path.abspath(os.path.dirname(__file__)))
self.cb_cl.chromaScale = self.chromaScale
self.cb_cl.lumScale = self.lumScale
self.cb_cl.noiseFloor = self.noiseFloor
self.cb_cl.post_change()
except:
self.cl = None
# Check we have a copy to mess with...
if self.output==None:
self.output = img.copy()
if weave==None: self.inter = img.copy()
# Run using OpenCl if possible...
if False: #self.cb_cl!=None:
self.cb_cl.to_rgb(img)
self.cb_cl.fetch(self.output)
else:
# Convert back to rgb...
if weave:
code = start_cpp() + """
for (int y=0;y<Noutput[0];y++)
{
for (int x=0;x<Noutput[1];x++)
{
// Merge luminance and chromacity, taking into account the noise floor and remove the luminance bias, which includes scaling to a volume of 1...
float inter[3];
inter[0] = IMG3(y,x,0) / lumScale;
float cDiv = inter[0];
if (cDiv<noiseFloor) cDiv = noiseFloor;
cDiv /= chromaScale;
inter[1] = IMG3(y,x,1) * cDiv;
inter[2] = IMG3(y,x,2) * cDiv;
// Rotate back to rgb (A matrix multiplication.)...
for (int r=0;r<3;r++)
{
OUTPUT3(y,x,r) = 0.0;
for (int c=0;c<3;c++)
{
OUTPUT3(y,x,r) += MATRIX2(r,c) * inter[c];
}
}
}
}
"""
output = self.output
matrix = self.invMatrix
lumScale = self.lumScale
chromaScale = self.chromaScale
noiseFloor = self.noiseFloor
weave.inline(code, ['img', 'output', 'matrix', 'lumScale', 'chromaScale', 'noiseFloor'])
else:
## Apply the inverse of the bias scalling...
self.inter[:,:,0] = img[:,:,0] / self.lumScale
self.inter[:,:,1:] = img[:,:,1:] / self.chromaScale
## Multiply by luminance to get back the dependency...
self.inter[:,:,1] *= numpy.clip(self.inter[:,:,0], self.noiseFloor, 1e100)
self.inter[:,:,2] *= numpy.clip(self.inter[:,:,0], self.noiseFloor, 1e100)
## Apply the inverse matrix operation...
for r in xrange(3):
self.output[:,:,r] = (self.inter * self.invMatrix[r,:].reshape((1,1,-1))).sum(axis=2)
return True
def outputCount(self):
return 1
def outputMode(self, channel=0):
return MODE_RGB
def outputName(self, channel=0):
return 'Video stream returned to rgb colour space.'
def fetch(self, channel=0):
return self.output
| [
[
1,
0,
0.0522,
0.0029,
0,
0.66,
0,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.0551,
0.0029,
0,
0.66,
0.1,
526,
0,
1,
0,
0,
526,
0,
0
],
[
1,
0,
0.058,
0.0029,
0,
0.66,
... | [
"import os.path",
"import math",
"import numpy",
"import numpy.linalg",
"try:\n import scipy.weave as weave\nexcept:\n weave = None",
" import scipy.weave as weave",
" weave = None",
"from utils.start_cpp import start_cpp",
"from utils.make import make_mod",
"from video_node import *",
"try:... |
# 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 video_node import *
class Remap(VideoNode):
"""This remaps channels, potentially combining multiple video sources and consequentially generating an arbitrary VideoNode object that can involve any data the user decides. All the standard rules of VideoNode are sustained, as long as all the input videos share resolution and fps. Primarily used when saving out node results to disk, to save the precise set of feeds you want."""
def __init__(self, channels = []):
"""This initialises the object - channels is a list of pairs, containing first the video object and then the video channel to use, to indicate what the channels of this object are. Channels can have duplicates. The channels can be editted by the input interface after initialisation, and if you give a toChannel number outside the current range it is appended, so this data can be built/editted latter if needed. (There is no way to delete a channel however.)"""
self.sources = []
self.channels = []
for pair in channels:
if pair[0] not in self.sources: self.sources.append(pair[0])
index = self.source.index(pair[0])
self.channels.append((index,pair[1]))
def width(self):
return self.sources[0].width()
def height(self):
return self.sources[0].height()
def fps(self):
return self.sources[0].fps()
def frameCount(self):
return self.sources[0].frameCount()
def inputCount(self):
return len(self.channels)
def inputMode(self, channel=0):
return MODE_OTHER
def inputName(self, channel=0):
return 'Anything you want'
def source(self, toChannel, video, videoChannel=0):
if video not in self.sources:
self.sources.append(video)
index = self.source.index(video)
if toChannel>=len(self.channels):
self.channels.append((index,videoChannel))
else:
self.channels[toChannel] = (index,videoChannel)
def dependencies(self):
return self.sources
def nextFrame(self):
return True # No-op as it only remaps method calls.
def outputCount(self):
return len(self.channels)
def outputMode(self, channel=0):
pair = self.channels[channel]
return self.sources[pair[0]].mode(pair[1])
def outputName(self, channel=0):
pair = self.channels[channel]
return self.sources[pair[0]].name(pair[1])
def fetch(self, channel=0):
pair = self.channels[channel]
return self.sources[pair[0]].nextFrame(pair[1])
| [
[
1,
0,
0.2045,
0.0114,
0,
0.66,
0,
306,
0,
1,
0,
0,
306,
0,
0
],
[
3,
0,
0.625,
0.7614,
0,
0.66,
1,
988,
0,
15,
0,
0,
442,
0,
16
],
[
8,
1,
0.2614,
0.0114,
1,
0.93... | [
"from video_node import *",
"class Remap(VideoNode):\n \"\"\"This remaps channels, potentially combining multiple video sources and consequentially generating an arbitrary VideoNode object that can involve any data the user decides. All the standard rules of VideoNode are sustained, as long as all the input vide... |
# 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/>.
import os.path
import numpy
import cv
from utils.cvarray import cv2array
from video_node import *
class ReadCamCV(VideoNode):
"""Simple wrapper around open cv's video camera reading interface - for feeding a webcam into the nodes."""
def __init__(self, device = -1):
"""Given a device number provides access to that device - -1, the default, means choose any. There is no way of querying the devices and finding out what each is unfortunatly."""
self.vid = cv.CaptureFromCAM(device)
self.frame = None
def width(self):
return int(cv.GetCaptureProperty(self.vid,cv.CV_CAP_PROP_FRAME_WIDTH))
def height(self):
return int(cv.GetCaptureProperty(self.vid,cv.CV_CAP_PROP_FRAME_HEIGHT))
def fps(self):
return cv.GetCaptureProperty(self.vid,cv.CV_CAP_PROP_FPS)
def frameCount(self):
return int(cv.GetCaptureProperty(self.vid,cv.CV_CAP_PROP_FRAME_COUNT))
def inputCount(self):
return 0
def dependencies(self):
return []
def nextFrame(self):
self.frame = cv.QueryFrame(self.vid)
if self.frame==None: return False
self.frameNP = cv2array(self.frame)[:,:,::-1].astype(numpy.float32)/255.0
return True
def outputCount(self):
return 1
def outputMode(self, channel=0):
return MODE_RGB
def outputName(self, channel=0):
return 'image'
def fetch(self, channel=0):
return self.frameNP
| [
[
1,
0,
0.2432,
0.0135,
0,
0.66,
0,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.2703,
0.0135,
0,
0.66,
0.2,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.2838,
0.0135,
0,
0.66,... | [
"import os.path",
"import numpy",
"import cv",
"from utils.cvarray import cv2array",
"from video_node import *",
"class ReadCamCV(VideoNode):\n \"\"\"Simple wrapper around open cv's video camera reading interface - for feeding a webcam into the nodes.\"\"\"\n def __init__(self, device = -1):\n \"\"\"... |
# 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 video_node import *
class Seq(VideoNode):
"""Defines a video created by appending several videos - effectivly pretends they are one big video. This can theoretically result in details such as frame rate and size changing as the video procedes, though that would typically be avoided as most other nodes do not handle this scenario. Breaks some of the rules as the input videos can not be part of the manager due to the unusual calling strategy."""
def __init__(self, seq):
"""For initialisation it is given a list of objects that impliment the VideoNode interface - it then pretends to be that list of videos in the order given. All videos should be fresh, i.e. nextFrame should never have been called on them, and must not be members of the manager."""
self.seq = seq
self.index = 0
def width(self):
return self.seq[self.index].width()
def height(self):
return self.seq[self.index].height()
def fps(self):
return self.seq[self.index].fps()
def frameCount(self):
return sum(map(lambda rv: rv.frameCount(),self.seq))
def inputCount(self):
return 0
def dependencies(self):
ret = []
for vid in self.seq:
ret += vid.dependencies()
return ret
def nextFrame(self):
while True:
ret = self.seq[self.index].nextFrame()
if (ret==False) and (self.index+1<len(self.seq)):
self.index += 1
else:
break
return ret
def outputCount(self):
return self.seq[self.index].outputCount()
def outputMode(self, channel=0):
return self.seq[self.index].outputMode(channel)
def outputName(self, channel=0):
return self.seq[self.index].outputName(channel)
def fetch(self, channel=0):
return self.seq[self.index].fetch(channel)
| [
[
1,
0,
0.25,
0.0139,
0,
0.66,
0,
306,
0,
1,
0,
0,
306,
0,
0
],
[
3,
0,
0.6528,
0.7083,
0,
0.66,
1,
905,
0,
12,
0,
0,
442,
0,
13
],
[
8,
1,
0.3194,
0.0139,
1,
0.16,... | [
"from video_node import *",
"class Seq(VideoNode):\n \"\"\"Defines a video created by appending several videos - effectivly pretends they are one big video. This can theoretically result in details such as frame rate and size changing as the video procedes, though that would typically be avoided as most other no... |
#! /usr/bin/env python
# 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/>.
import sys
import os.path
from optparse import OptionParser
import time
import video
# Handle the command line agruments...
parser = OptionParser(usage='usage: %prog [options] video_file', version='%prog 0.1')
parser.add_option('-o', '--out', dest='outFN', help="Overide default output filenames. Default is '<video_file without extension>/#.png'.", metavar='FILE')
parser.add_option('-d', '--deinterlace', action='store_true', dest='deinterlace', default=False, help='Deinterlace the input.')
parser.add_option('-e', '--even-first', action='store_true', dest='even_first', default=False, help='When deinterlacing assume even-first rather than odd-first fields.')
parser.add_option('-s', '--sequence', action='store_true', dest='sequence', default=False, help='Treats the filename as a sequence, where a # indicates where a file number should be (Of arbitrary length, with preceding zeros if you want.) - all files in the sequence will be considered as one long video file, in numerical order (It will not complain about gaps).')
parser.add_option('-f', '--frames', type='int', dest='frames', help='Overide number of frames, incase you only want to do part of the file.', metavar='FRAMES')
parser.add_option('-q', '--quarter', action='store_true', dest='half', default=False, help='Halfs the resolution of the video before procesing (If requested deinterlacing will be done first, obviously.), resulting in their being a quarter of the data.')
(options, args) = parser.parse_args()
if len(args)!=1:
parser.print_help()
sys.exit(1)
inFN = args[0]
outFN = filter(lambda c: c!='#', os.path.splitext(inFN)[0]) + '/#.png'
if options.outFN!=None: outFN = options.outFN
lumScale = 0.5
noiseFloor = 0.2
baseFrame = 1
# Build the node tree...
man = video.Manager()
if options.sequence: vid = video.num_to_seq(inFN, video.ReadCV)
else: vid = video.ReadCV(inFN)
man.add(vid)
if options.deinterlace:
ivid = vid
vid = video.DeinterlaceEV(not options.even_first)
vid.source(0,ivid)
man.add(vid)
if options.half:
jvid = vid
vid = video.Half()
vid.source(0,jvid)
man.add(vid)
cb = video.ColourBias(lumScale, noiseFloor, man.getCL())
cb.source(0,vid)
man.add(cb)
lc = video.LightCorrectMS()
lc.source(0,cb)
man.add(lc)
bs = video.BackSubDP()
bs.source(0,cb)
bs.source(1,lc,0)
man.add(bs)
lc.source(1,bs,2) # Calculate lighting change relative to current background estimate
bs.setDP(comp=6, conc=0.01, cap=128.0)
bs.setHackDP(min_weight = 0.0005)
bs.setBP(threshold = 0.4, half_life = 0.05, iters = 2)
bs.setExtraBP(cert_limit = 0.005, change_limit = 0.001, min_same_prob = 0.99, change_mult = 3.0)
bs.setOnlyCL(minSize = 64, maxLayers = 8, itersPerLevel = 2)
mr = video.RenderMask()
mr.source(0,bs)
man.add(mr)
wf = video.WriteFramesCV(outFN, start_frame = baseFrame)
wf.source(0,mr)
man.add(wf)
# Run....
frames = vid.frameCount()
if options.frames!=None: frames = options.frames
lastTime = time.clock()
for i in xrange(frames):
if man.nextFrame()!=True:
print 'Error getting next frame'
break
now = time.clock()
print 'Frame %i of %i, time = %f'%(i+1,frames,now-lastTime)
lastTime = now
| [
[
1,
0,
0.1626,
0.0081,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.1707,
0.0081,
0,
0.66,
0.02,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.1789,
0.0081,
0,
0.66... | [
"import sys",
"import os.path",
"from optparse import OptionParser",
"import time",
"import video",
"parser = OptionParser(usage='usage: %prog [options] video_file', version='%prog 0.1')",
"parser.add_option('-o', '--out', dest='outFN', help=\"Overide default output filenames. Default is '<video_file wi... |
# 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/>.
MODE_RGB = 0 # Each frame is indexed as [y,x,channel], where x is [0,width), y [0,height) and channel one of 0=red, 1=green, 2=blue. The colour channels are represented by float32s, in the range [0,1], unless there is a good reason to leave that range.
MODE_MASK = 1 # Each frame is indexed as [y,x], and goes to an 8 bit unsigned int, which contains 0 for not included and 1 for included.
MODE_FLOW = 2 # Optical flow, where each frame is indexed as [y,x,dir], where dir=0 indexes a y-axis offset and 1 indexes a x-axis offset. Uses float32's.
MODE_WORD = 3 # Indexes words, as in the video has been quantised somehow. Indexing is [y,x], and leads to int32's. What the words mean is defined by the situation, but an interface returning this mode is expected to provide the method wordCount() to indicate how many exist, and -1 is used to indicate 'no word'.
MODE_FLOAT = 4 # Each frame is indexed as [y,x], and goes to a float32, which can mean anything.
MODE_MATRIX = 5 # Returns a matrix that represents something - used for colour transformations for instance with regard to lighting changes.
MODE_OTHER = -1 # For anything not covered by another mode, or when multiple modes are supported.
mode_to_string = {MODE_RGB:'rgb', MODE_MASK:'mask', MODE_FLOW:'flow', MODE_WORD:'word',MODE_FLOAT:'float',MODE_MATRIX:'matrix',MODE_OTHER:'other'}
class VideoNode:
"""Interface for a video procesing object that provides the next frame on demand, as a numpy array that is always indexed from the top right of the frame."""
def width(self):
"""Returns the width of the video."""
raise Exception('width not implimented')
def height(self):
"""Returns the height of the video."""
raise Exception('height not implimented')
def fps(self):
"""Returns the frames per second of the video, as a floating point value."""
raise Exception('fps not implimented')
def frameCount(self):
"""Returns the number of times you can call nextFrame before it starts returning None."""
raise Exception('frameCount not implimented')
def inputCount(self):
"""Returns the number of inputs."""
raise Exception('inputCount not implimented')
def inputMode(self, channel=0):
"""Returns the required mode for the given input."""
raise Exception('inputMode not implimented')
def inputName(self, channel=0):
"""Returns a human readable description of the given input."""
raise Exception('inputName not implimented.')
def source(self, toChannel, video, videoChannel=0):
"""Sets a video as input to the video object, in channel to Channel, optionally including which channel to extract from video as videoChannel."""
raise Exception(' not implimented')
def dependencies(self):
"""Returns a list of video objects that this video object is dependent on - the nextframe method must be called on all of these prior to it being called on this, otherwise strange stuff will happen. The list is allowed to include duplicates."""
raise Exception('dependencies not implimented')
def nextFrame(self):
"""Moves to the next frame, returning True if there is now a set of next frames that can be extracted using the fetch command, and False if not. typically False means we are out of data, as an error would lead to an exception being thrown. Must not be called until the object is setup - i.e. all inputs have been set, and any other object-specific actions."""
raise Exception('nextFrame not implimented')
def outputCount(self):
"""Returns the number of outputs - a video object is allowed to have multiple outputs. The output in position 0 is the default and often the only one."""
raise Exception('outputCount not implimented')
def outputMode(self, channel=0):
"""Returns one of the modes, which indicates the format of the entity returned by nextFrame. The optional out parameter indicates which output to indicate for. Most of these do not both with outputs."""
raise Exception('mode not implimented')
def outputName(self, channel=0):
"""Returns a string indicating what the output in question is - arbitrary and for human consumption only."""
raise Exception('name not implimented')
def fetch(self, channel=0):
"""Returns the requested channel, as a numpy array. You can not assume that the object is persistant, i.e. it might be the same object returned each time, but with a different contents. The optional channel parameter indicates which output to get. fetch can be called multiple times for a channel between each call to nextFrame."""
raise Exception('fetch not implimented')
| [
[
14,
0,
0.1978,
0.011,
0,
0.66,
0,
30,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.2088,
0.011,
0,
0.66,
0.125,
813,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.2198,
0.011,
0,
0.66,
... | [
"MODE_RGB = 0 # Each frame is indexed as [y,x,channel], where x is [0,width), y [0,height) and channel one of 0=red, 1=green, 2=blue. The colour channels are represented by float32s, in the range [0,1], unless there is a good reason to leave that range.",
"MODE_MASK = 1 # Each frame is indexed as [y,x], and goes ... |
# 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/>.
import os.path
import numpy
import cv
from utils.cvarray import cv2array
from video_node import *
class ReadCV_IS(VideoNode):
"""Presents an image sequence as a video, using open cv's image loading routines to load in the image files as needed."""
def __init__(self, fn, fps = 30.0):
"""You initialise with a filename and the frames per second, as that can obviously not be obtained from an image sequence. The filename should have a '#' in it indicating where the number should go - it will then work out the rest. Note that it will order the frames numerically, and then use them - if there are gaps it won't care. Will work regardless of if the numbers are padded with zeros or not. The # must appear in the filename part, not the directory part - all files are expected to be in a single directory."""
if '#' in fn:
# Split into parts...
path, fn = os.path.split(fn)
start, end = map(lambda s: s.replace('#',''),fn.split('#',1))
# Get all files from the directory, filter it down to only those that match the form...
files = os.listdir(path)
def valid(fn):
if fn[:len(start)]!=start: return False
if fn[-len(end):]!=end: return False
if not fn[len(start):-len(end)].isdigit(): return False
return True
files = filter(valid,files)
# Get the relevant numbers, sort the files by them...
files.sort(key=lambda fn: int(fn[len(start):-len(end)]))
# Put the paths back...
self.files = map(lambda f: os.path.join(path, f), files)
else:
self.files = [fn]
self.index = 0
# We have the file list - now determine the various properties...
test = cv.LoadImage(self.files[0])
self.__width = test.width
self.__height = test.height
self.__fps = fps
self.__frameCount = len(self.files)
def width(self):
return self.__width
def height(self):
return self.__height
def fps(self):
return self.__fps
def frameCount(self):
return self.__frameCount
def inputCount(self):
return 0
def dependencies(self):
return []
def nextFrame(self):
if self.index<len(self.files):
try:
img = cv.LoadImage(self.files[self.index])
#print img.nChannels, img.width, img.height, img.depth, img.origin
self.frame = cv2array(img)[:,:,::-1].astype(numpy.float32)/255.0
except:
print 'Frame #%i with filename %s failed to load.'%(self.index,self.files[self.index])
self.index += 1
else:
self.frame = None
return self.frame!=None
def outputCount(self):
return 1
def outputMode(self, channel=0):
return MODE_RGB
def outputName(self, channel=0):
return 'image'
def fetch(self, channel=0):
return self.frame
| [
[
1,
0,
0.1622,
0.009,
0,
0.66,
0,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.1802,
0.009,
0,
0.66,
0.2,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.1892,
0.009,
0,
0.66,
... | [
"import os.path",
"import numpy",
"import cv",
"from utils.cvarray import cv2array",
"from video_node import *",
"class ReadCV_IS(VideoNode):\n \"\"\"Presents an image sequence as a video, using open cv's image loading routines to load in the image files as needed.\"\"\"\n def __init__(self, fn, fps = 3... |
# 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/>.
import os
import os.path
from seq import Seq
def num_to_seq(fn, loader):
"""Given a filename of the form 'directory/start#end' finds all files that match the given form, where # is an arbitrary number. The files are sorted into numerical order, and each is loaded using the provided loader (ReadCV for instance - constructor should take a single filename.), a Seq object is then created. This in effect turns a directory of numbered video files into a single video file."""
# Break the given filename form into its basic parts...
path, fn = os.path.split(fn)
start, end = map(lambda s: s.replace('#',''),fn.split('#',1))
# Get all files from the directory, filter it down to only those that match the form...
files = os.listdir(path)
def valid(fn):
if fn[:len(start)]!=start: return False
if fn[-len(end):]!=end: return False
if not fn[len(start):-len(end)].isdigit(): return False
return True
files = filter(valid,files)
# Get the relevant numbers, sort the files by them...
files.sort(key=lambda fn: int(fn[len(start):-len(end)]))
# Put the paths back...
files = map(lambda f: os.path.join(path, f), files)
# Loop and load the files...
seq = map(lambda fn: loader(fn), files)
# Create and return the sequence object...
return Seq(seq)
| [
[
1,
0,
0.36,
0.02,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.38,
0.02,
0,
0.66,
0.3333,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.42,
0.02,
0,
0.66,
0.66... | [
"import os",
"import os.path",
"from seq import Seq",
"def num_to_seq(fn, loader):\n \"\"\"Given a filename of the form 'directory/start#end' finds all files that match the given form, where # is an arbitrary number. The files are sorted into numerical order, and each is loaded using the provided loader (Rea... |
#! /usr/bin/env python
# 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/>.
import sys
import os.path
from optparse import OptionParser
import time
import video
# Handle the command line agruments...
parser = OptionParser(usage='usage: %prog [options] video_file', version='%prog 0.1')
parser.add_option('-o', '--out', dest='outFN', help="Overide default output filename. (Default is the input filename with its extension replaced by '.word'.", metavar='FILE')
parser.add_option('-d', '--deinterlace', action='store_true', dest='deinterlace', default=False, help='Deinterlace the input.')
parser.add_option('-e', '--even-first', action='store_true', dest='even_first', default=False, help='When deinterlacing assume even-first rather than odd-first fields.')
parser.add_option('-s', '--sequence', action='store_true', dest='sequence', default=False, help='Treats the filename as a sequence, where a # indicates where a file number should be (Of arbitrary length, with preceding zeros if you want.) - all files in the sequence will be considered as one long video file, in numerical order (It will not complain about gaps).')
parser.add_option('-f', '--frames', type='int', dest='frames', help='Overide number of frames, incase you only want to do part of the file. Note the frame count will not be updated - mostly good for testing.', metavar='FRAMES')
parser.add_option('-c', '--clip', type='int', dest='clip', help='Clips off the top of the image, remove such areas from the foreground mask. Useful for removing problematic skys and distant irrelevant activities.', metavar='PIXELS', default=0)
parser.add_option('-q', '--quarter', action='store_true', dest='half', default=False, help='Halfs the resolution of the video before procesing (If requested deinterlacing will be done first, obviously.), resulting in their being a quarter of the data.')
(options, args) = parser.parse_args()
if len(args)!=1:
parser.print_help()
sys.exit(1)
inFN = args[0]
outFN = os.path.splitext(inFN)[0] + '.word'
if options.outFN!=None: outFN = options.outFN
# Build the node tree...
man = video.Manager()
if options.sequence: vid = video.num_to_seq(inFN, video.ReadCV)
else: vid = video.ReadCV(inFN)
man.add(vid)
if options.deinterlace:
ivid = vid
vid = video.DeinterlaceEV(not options.even_first)
vid.source(0,ivid)
man.add(vid)
if options.half:
jvid = vid
vid = video.Half()
vid.source(0,jvid)
man.add(vid)
lc = video.LightCorrectMS()
lc.source(0,vid)
man.add(lc)
bs = video.BackSubDP()
bs.source(0,vid)
bs.source(1,lc,0)
man.add(bs)
lc.source(1,bs,2) # Calculate lighting change relative to current background estimate
cm = video.ClipMask(top = options.clip)
cm.source(0,bs)
man.add(cm)
of = video.OpticalFlowLK()
of.source(0,vid)
of.source(2,cm)
man.add(of)
mf = video.MaskFlow()
mf.source(0,of)
mf.source(1,cm)
man.add(mf)
fw = video.FiveWord()
fw.source(0,of)
fw.source(1,cm)
man.add(fw)
r = video.Record(fw, outFN)
man.add(r)
# Run....
frames = vid.frameCount()
if options.frames!=None: frames = options.frames
lastTime = time.clock()
for i in xrange(frames):
if man.nextFrame()!=True:
print 'Error getting next frame'
break
now = time.clock()
print 'Frame %i of %i, time = %f'%(i+1,frames,now-lastTime)
lastTime = now
| [
[
1,
0,
0.1667,
0.0083,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.175,
0.0083,
0,
0.66,
0.0196,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.1833,
0.0083,
0,
0.6... | [
"import sys",
"import os.path",
"from optparse import OptionParser",
"import time",
"import video",
"parser = OptionParser(usage='usage: %prog [options] video_file', version='%prog 0.1')",
"parser.add_option('-o', '--out', dest='outFN', help=\"Overide default output filename. (Default is the input filen... |
# 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/>.
import os.path
import numpy
import cv
from utils.cvarray import cv2array
from video_node import *
class ReadCV(VideoNode):
"""Simple wrapper around open cv's video reading interface - limited compatability but easy for reading lots of video files."""
def __init__(self, fn):
"""Given a filename opens it and streams video from it."""
if not os.path.exists(fn):
raise Exception('Filename does not exist on filesystem (filename=%s).'%fn)
self.vid = cv.CaptureFromFile(fn)
self.frame = None
def width(self):
return int(cv.GetCaptureProperty(self.vid,cv.CV_CAP_PROP_FRAME_WIDTH))
def height(self):
return int(cv.GetCaptureProperty(self.vid,cv.CV_CAP_PROP_FRAME_HEIGHT))
def fps(self):
return cv.GetCaptureProperty(self.vid,cv.CV_CAP_PROP_FPS)
def frameCount(self):
return int(cv.GetCaptureProperty(self.vid,cv.CV_CAP_PROP_FRAME_COUNT))
def inputCount(self):
return 0
def dependencies(self):
return []
def nextFrame(self):
self.frame = cv.QueryFrame(self.vid)
if self.frame==None: return False
self.frameNP = cv2array(self.frame)[:,:,::-1].astype(numpy.float32)/255.0
return True
def outputCount(self):
return 1
def outputMode(self, channel=0):
return MODE_RGB
def outputName(self, channel=0):
return 'image'
def fetch(self, channel=0):
return self.frameNP
| [
[
1,
0,
0.24,
0.0133,
0,
0.66,
0,
79,
0,
1,
0,
0,
79,
0,
0
],
[
1,
0,
0.2667,
0.0133,
0,
0.66,
0.2,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.28,
0.0133,
0,
0.66,
... | [
"import os.path",
"import numpy",
"import cv",
"from utils.cvarray import cv2array",
"from video_node import *",
"class ReadCV(VideoNode):\n \"\"\"Simple wrapper around open cv's video reading interface - limited compatability but easy for reading lots of video files.\"\"\"\n def __init__(self, fn):\n ... |
# 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/>.
import numpy
import scipy.weave as weave
from utils.start_cpp import start_cpp
from video_node import *
class OpticalFlowLK(VideoNode):
"""Optical flow using Lucas & Kanade - has a pyramid and only does one iteration per pyramid level by default. Uses a median filter for regularisation. Simple, not horrifically slow but obviously nothing amazing - basically the original algorithm for translation only."""
def __init__(self):
self.video = None
self.channel = 0
self.prev = None
self.prevChannel = 0
self.mask = None
self.maskChannel = 0
self.pyramid = None
# All the default parameters...
self.doPyramid = True # Decides if it makes a pyramid or not.
self.minDimCap = 32 # Keeps making levels of the pyramid until both dimensions drop below this.
self.pyramidSD = 0.8 # Strength of the anti-aliasing Gaussian blur applied to each level of the pyramid.
self.iters = 1 # Number of iterations per pyramid level.
self.radiusLK = 1 # Radius of the window used for each Lucas-Kanade iteration.
self.radiusMF = 1 # Radius of the window used for each median filter step.
def width(self):
return self.video.width()
def height(self):
return self.video.height()
def fps(self):
return self.video.fps()
def frameCount(self):
return self.video.frameCount()
def inputCount(self):
return 3
def inputMode(self, channel=0):
if channel!=2: return MODE_RGB
else: return MODE_MASK
def inputName(self, channel=0):
if channel==0: return 'Next frame - optical flow is calculated from this frame to the previous frame and then negated.'
elif channel==1: return 'Optional replacement for the previous frame, instead of using the actual previous frame. Allows for easy integration with a lighting correction module.'
else: return "Optional mask - it only computes optical flow where the mask is true, potentially saving a lot of time. (Note that it takes an 'or' approach for the pyramid, so areas outside the mask will still get values.)"
def source(self, toChannel, video, videoChannel=0):
if toChannel==0:
self.video = video
self.channel = videoChannel
elif toChannel==1:
self.prev = video
self.prevChannel = videoChannel
else:
self.mask = video
self.maskChannel = videoChannel
def dependencies(self):
ret = [self.video]
if self.prev!=None: ret += [self.prev]
if self.mask!=None: ret += [self.mask]
return ret
def nextFrame(self):
# First time this is called we need to setup the data structures, ready to be filled in...
if self.pyramid==None:
self.__setup_ds()
# Fill in the pyramids - what is involved depends on if we are supplied with a previous or not...
if self.prev==None:
# Rolling - means we can swap the pyramids and then rebuild only for the newest image...
swap = self.current
self.current = self.previous
self.previous = swap
c = self.video.fetch(self.channel)
self.__buildPyramid(c, self.current)
else:
# Previous image is being provided externally - have to rebuild both pyramids...
c = self.video.fetch(self.channel)
p = self.prev.fetch(self.prevChannel)
self.__buildPyramid(c, self.current)
self.__buildPyramid(p, self.previous)
# If there is a mask we need to fetch it and build a pyramid, otherwise just set the entire pyramid true and calculate for all pixels...
if self.mask!=None:
m = self.mask.fetch(self.maskChannel)
self.__buildMaskPyramid(m, self.maskPyramid)
else:
for l in xrange(len(self.maskPyramid)):
self.maskPyramid[l][:,:] = 1
# Loop the pyramid and handle each level in turn...
self.uv[:self.pyramid[-1][1],:self.pyramid[-1][0],:] = 0.0
for l in xrange(len(self.pyramid)-1,-1,-1):
# Iterations at this level...
for _ in xrange(self.iters):
self.__do_iter(self.current[l], self.previous[l], self.maskPyramid[l])
self.__do_median(self.maskPyramid[l])
# Upscale uv map...
if l!=0:
base = self.uv[:self.current[l].shape[0],:self.current[l].shape[1],:]
base *= 2.0
base = numpy.repeat(numpy.repeat(base,2,axis=1),2,axis=0)
self.uv[:base.shape[0],:base.shape[1],:] = base
# The map just generated is actually going backwards in time - reverse!..
self.uv *= -1.0
return True
def outputCount(self):
return 1
def outputMode(self, channel=0):
return MODE_FLOW
def outputName(self, channel=0):
return 'Optical flow - the vectors from the current frame to the previous frame, negated so they appear to go forwards in time.'
def fetch(self, channel=0):
return self.uv
def __setup_ds(self):
# For the pyramids we need the frame sizes - calculate...
self.pyramid = []
self.pyramid.append((self.video.width(), self.video.height()))
if self.doPyramid:
while (self.pyramid[-1][0] > self.minDimCap) or (self.pyramid[-1][1] > self.minDimCap):
half = [self.pyramid[-1][0]//2,self.pyramid[-1][1]//2]
if (self.pyramid[-1][0]%2)==1: half[0] += 1
if (self.pyramid[-1][1]%2)==1: half[1] += 1
self.pyramid.append(tuple(half))
# We need two pyramids - one for the current frame, one for the previous frame...
self.current = map(lambda dim: numpy.empty((dim[1], dim[0], 3), dtype=numpy.float32), self.pyramid)
self.previous = map(lambda dim: numpy.empty((dim[1], dim[0], 3), dtype=numpy.float32), self.pyramid)
# We also need a mask pyramid, to save on computation if a mask is provided...
self.maskPyramid = map(lambda dim: numpy.empty((dim[1], dim[0]), dtype=numpy.uint8), self.pyramid)
# The output - a uv (u = change in x, v = change in y.) map...
self.uv = numpy.zeros((self.video.height(),self.video.width(),2), dtype=numpy.float32)
# Temporary storage used at various points...
self.image = numpy.empty((self.video.height(), self.video.width(), 3), dtype=numpy.float32)
sizeMF = 1 + 2 * self.radiusMF
self.window = numpy.empty((sizeMF,sizeMF),dtype=numpy.float32)
def __buildPyramid(self, base, pyramid):
"""Given an image and a pyramid as a list of images, largest first and of the same size as image, this fills in the images with a Gaussian pyramid."""
codeBlur = start_cpp() + """
// Calculate the filter - we just use 3 points as its a very tiny blur...
float filter[3];
filter[0] = exp(-0.5/(strength*strength));
filter[1] = 1.0;
filter[2] = filter[0];
float div = filter[0] + filter[1] + filter[2];
for (int f=0;f<3;f++) filter[f] /= div;
// Apply in the vertical dimension, going from img to temp...
for (int x=0;x<Nimg[1];x++)
{
for (int c=0;c<3;c++)
{
TEMP3(0,x,c) = (filter[0]+filter[1])*IMG3(0,x,c) + filter[2]*IMG3(1,x,c);
}
}
int ym1 = Nimg[0] - 1;
for (int y=1;y<ym1;y++)
{
for (int x=0;x<Nimg[1];x++)
{
for (int c=0;c<3;c++)
{
TEMP3(y,x,c) = filter[0]*IMG3(y-1,x,c) + filter[1]*IMG3(y,x,c) + filter[2]*IMG3(y+1,x,c);
}
}
}
for (int x=0;x<Nimg[1];x++)
{
for (int c=0;c<3;c++)
{
TEMP3(ym1,x,c) = filter[0]*IMG3(ym1-1,x,c) + (filter[1]+filter[2])*IMG3(ym1,x,c);
}
}
// Apply in the horizontal dimension, going from temp to img...
for (int y=0;y<Nimg[0];y++)
{
for (int c=0;c<3;c++)
{
IMG3(y,0,c) = (filter[0]+filter[1])*TEMP3(y,0,c) + filter[2]*TEMP3(y,1,c);
}
}
int xm1 = Nimg[1] - 1;
for (int y=0;y<Nimg[0];y++)
{
for (int x=1;x<xm1;x++)
{
for (int c=0;c<3;c++)
{
IMG3(y,x,c) = filter[0]*TEMP3(y,x-1,c) + filter[1]*TEMP3(y,x,c) + filter[2]*TEMP3(y,x+1,c);
}
}
}
for (int y=0;y<Nimg[0];y++)
{
for (int c=0;c<3;c++)
{
IMG3(y,xm1,c) = filter[0]*TEMP3(y,xm1-1,c) + (filter[1]+filter[2])*TEMP3(y,xm1,c);
}
}
"""
codeHalf = start_cpp() + """
// Iterate the output image and calculate each pixel in turn...
for (int y=0;y<NbOut[0];y++)
{
int sy = y*2;
bool safeY = sy+1<NbOut[0];
for (int x=0;x<NbOut[1];x++)
{
int sx = x*2;
bool safeX = sx+1<NbOut[1];
float div = 1.0;
for (int c=0;c<3;c++)
{
BOUT3(y,x,c) = BIN3(sy,sx,c);
}
if (safeX)
{
div += 1.0;
for (int c=0;c<3;c++) BOUT3(y,x,c) += BIN3(sy,sx+1,c);
}
if (safeY)
{
div += 1.0;
for (int c=0;c<3;c++) BOUT3(y,x,c) += BIN3(sy+1,sx,c);
}
if (safeX&&safeY)
{
div += 1.0;
for (int c=0;c<3;c++) BOUT3(y,x,c) += BIN3(sy+1,sx+1,c);
}
for (int c=0;c<3;c++) BOUT3(y,x,c) /= div;
}
}
"""
temp = self.image
strength = self.pyramidSD
pyramid[0][:,:,:] = base
img = pyramid[0][:,:,:]
weave.inline(codeBlur, ['img','temp','strength'])
for l in xrange(1,len(pyramid)):
bIn = pyramid[l-1]
bOut = pyramid[l]
img = bOut
weave.inline(codeHalf, ['bIn','bOut'])
weave.inline(codeBlur, ['img','temp','strength'])
def __buildMaskPyramid(self, mask, pyramid):
"""Given a mask and a pyramid of masks makes a pyramid, where it uses the or operation for combining flags."""
code = start_cpp() + """
// Make curr all false...
for (int y=0;y<Ncurr[0];y++)
{
for (int x=0;x<Ncurr[1];x++) CURR2(y,x) = 0;
}
// Iterate prev, and update curr...
for (int y=0;y<Nprev[0];y++)
{
for (int x=0;x<Nprev[1];x++)
{
if (PREV2(y,x)!=0)
{
CURR2(y/2,x/2) = 1;
}
}
}
"""
pyramid[0][:,:] = mask
for l in xrange(1,len(pyramid)):
prev = pyramid[l-1]
curr = pyramid[l]
weave.inline(code, ['prev','curr'])
def __do_iter(self, iFrom, iTo, mask):
"""Given a from image and a to image this does a single LK iteration, starting from and updating the values in self.uv. If images are smaller than self.uv then it just uses the corner - means same uv object can be used throughout pyramid construction."""
support_code = start_cpp() + """
// Given a t value in [0,1] calculates the weights of the 4 pixels for a bicubic spline and writes them into out, it also writes into dOut the weights to get the splines differential with respect to t.
void BicubicMult(float t, float out[4], float dOut[4])
{
float t2 = t*t;
float t3 = t2*t;
out[0] = -0.5*t + t2 - 0.5*t3;
out[1] = 1.0 - 2.5*t2 + 1.5*t3;
out[2] = 0.5*t + 2.0*t2 - 1.5*t3;
out[3] = -0.5*t2 + 0.5*t3;
dOut[0] = -0.5 + 2.0*t - 1.5*t2;
dOut[1] = -5.0*t + 4.5*t2;
dOut[2] = 0.5 + 4.0*t - 4.5*t2;
dOut[3] = -t + 1.5*t2;
}
// This does bicubic interpolation of an image, getting both values and differentials, and handling boundary conditions. Input must include the output of calls to BicubicMult for both directions - this encodes the fractional part of the coordinate. The user provides the integer part.
void Bicubic(PyArrayObject * image, int y, float multY[4], float dMultY[4], int x, float multX[4], float dMultX[4], float rgb[3], float rgbDy[3], float rgbDx[3])
{
// Handle coordinates, doing boundary checking - we use repetition at the borders, which makes it a simple matter of coordinate clamping at the boundaries...Y
int coordY[4];
coordY[0] = y-1;
for (int i=1;i<4;i++) coordY[i] = coordY[i-1] + 1;
for (int i=0;i<4;i++)
{
if (coordY[i]>=0) break;
coordY[i] = 0;
}
for (int i=3;i>=0;i--)
{
if (coordY[i]<image->dimensions[0]) break;
coordY[i] = image->dimensions[0]-1;
}
int coordX[4];
coordX[0] = x-1;
for (int i=1;i<4;i++) coordX[i] = coordX[i-1] + 1;
for (int i=0;i<4;i++)
{
if (coordX[i]>=0) break;
coordX[i] = 0;
}
for (int i=3;i>=0;i--)
{
if (coordX[i]<image->dimensions[1]) break;
coordX[i] = image->dimensions[1]-1;
}
// Apply in both dimensions to get value sequences interpolated in both, from which you would typically inteprolate the value in a second step - needed due to calculation of differentials...
float iy[4][3]; // Position, rgb. y=dimension you index with.
float ix[4][3]; // ", but with x.
bzero(iy,sizeof(float)*4*3);
bzero(ix,sizeof(float)*4*3);
for (int v=0;v<4;v++)
{
char * baseV = image->data + coordY[v]*image->strides[0];
for (int u=0;u<4;u++)
{
float * val = (float*)(baseV + coordX[u]*image->strides[1]);
for (int c=0;c<3;c++)
{
iy[v][c] += multX[u] * val[c];
ix[u][c] += multY[v] * val[c];
}
}
}
// Use one dimension and a further step to get the value...
bzero(rgb,sizeof(float)*3);
for (int u=0;u<4;u++)
{
for (int c=0;c<3;c++) rgb[c] += ix[u][c] * multX[u];
}
// Use both dimensions followed by a differential step to get the differentials for both dx and dy...
bzero(rgbDy,sizeof(float)*3);
for (int v=0;v<4;v++)
{
for (int c=0;c<3;c++) rgbDy[c] += iy[v][c] * dMultY[v];
}
bzero(rgbDx,sizeof(float)*3);
for (int u=0;u<4;u++)
{
for (int c=0;c<3;c++) rgbDx[c] += ix[u][c] * dMultX[u];
}
}
"""
code = start_cpp(support_code) + """
// Iterate over the pixels and calculate as estimate for each...
for (int y=0;y<NiFrom[0];y++)
{
for (int x=0;x<NiFrom[1];x++)
{
if (MASK2(y,x)!=0)
{
// Get the range to search - to avoid sampling values outside the image (For the from image - to image is allowed to go outside the range, as handled by the interpolation functions.)...
int yStart = y - radius;
int yEnd = y + radius;
int xStart = x - radius;
int xEnd = x + radius;
if (yStart<0) yStart = 0;
if (yEnd>=NiFrom[0]) yEnd = NiFrom[0] - 1;
if (xStart<0) xStart = 0;
if (xEnd>=NiFrom[1]) xEnd = NiFrom[1] - 1;
// Get the offset from uv, split into integer and fractional parts and calculate the weights for the bicubic interpolation...
int oy = int(UV3(y,x,0));
float ty = UV3(y,x,0) - oy;
float multY[4];
float dMultY[4];
BicubicMult(ty, multY, dMultY);
int ox = int(UV3(y,x,1));
float tx = UV3(y,x,1) - ox;
float multX[4];
float dMultX[4];
BicubicMult(tx, multX, dMultX);
// Calculate the b value and structural tensor, simultaneously, to avoid computing derivatives repeatedly...
float st[3] = {0.0,0.0,0.0}; // Linearised symmetric matrix - [0][0], [0][1]/[1][0], [1][1].
float b[2] = {0.0,0.0};
for (int v=yStart;v<=yEnd;v++)
{
for (int u=xStart;u<=xEnd;u++)
{
if (MASK2(v,u)!=0)
{
// Get the value in the from image...
float * from = (float*)(iFrom_array->data + v*iFrom_array->strides[0] + u*iFrom_array->strides[1]);
// Get the value and differential in the to image...
float rgb[3];
float rgbDy[3];
float rgbDx[3];
Bicubic(iTo_array, v+oy, multY, dMultY, u+ox, multX, dMultX, rgb, rgbDy, rgbDx);
// Loop the colour channels - same calculations for each...
for (int c=0;c<3;c++)
{
// Update the structural tensor...
st[0] += rgbDy[c] * rgbDy[c];
st[1] += rgbDx[c] * rgbDy[c];
st[2] += rgbDx[c] * rgbDx[c];
// Update b...
float diff = from[c] - rgb[c];
b[0] += rgbDy[c] * diff;
b[1] += rgbDx[c] * diff;
}
}
}
}
// Invert the structural tensor, solve the equation, update the uv entry...
double det = double(st[0])*double(st[2]) - double(st[1])*double(st[1]);
if (fabs(det)>1e-9)
{
float temp = st[0];
st[0] = st[2];
st[2] = temp;
st[1] *= -1.0;
st[0] /= det;
st[1] /= det;
st[2] /= det;
// st is now inverted - easy matter to calculate the change...
float dv = st[0]*b[0] + st[1]*b[1];
float du = st[1]*b[0] + st[2]*b[1];
// Only apply the change if it is sensible - approximation is only good for a pixel or so, so ignore if greater than 2 as it being crazy...
float changeSqr = dv*dv + du*du;
if (changeSqr<(2*2))
{
UV3(y,x,0) += dv;
UV3(y,x,1) += du;
}
}
}
}
}
"""
uv = self.uv
radius = self.radiusLK
weave.inline(code, ['iFrom', 'iTo', 'mask', 'uv', 'radius'], support_code=support_code)
def __do_median(self, mask):
"""Applys a median filter to self.uv - pretty simple really. Areas outside the mask are ignored."""
code = start_cpp() + """
int size = radius*2 + 1;
// Iterate and calculate the median for each pixel, writting the output into temp...
for (int y=0;y<Nmask[0];y++)
{
for (int x=0;x<Nmask[1];x++)
{
if (MASK2(y,x)!=0)
{
// Get ranges, bound checked...
int startV = y - radius;
int endV = y + radius;
int startU = x - radius;
int endU = x + radius;
if (startV<0) startV = 0;
if (endV>=Nmask[0]) endV = Nmask[0]-1;
if (startU<0) startU = 0;
if (endU>=Nmask[1]) endU = Nmask[1]-1;
// Zero out the window, so the distances may be summed in...
for (int v=startV;v<=endV;v++)
{
int wv = v - startV;
for (int u=startU;u<=endU;u++)
{
int wu = u - startU;
WIN2(wv,wu) = 0.0;
}
}
// Calculate the distances for each entry - take care to avoid duplicate calculation, even though it makes for some messy code...
for (int v=startV;v<=endV;v++)
{
int wv = v - startV;
for (int u=startU;u<=endU;u++)
{
int wu = u - startU;
if (MASK2(v,u)!=0)
{
int ov = v;
int ou = u;
while (true)
{
ou += 1;
if (ou>endU)
{
ou = startU;
ov += 1;
if (ov>endV) break;
}
if (MASK2(ov,ou)==0) continue;
int wov = ov - startV;
int wou = ou - startU;
float deltaV = UV3(ov,ou,0) - UV3(v,u,0);
float deltaU = UV3(ov,ou,1) - UV3(v,u,1);
float dist = sqrt(deltaU*deltaU + deltaV*deltaV);
WIN2(wv,wu) += dist;
WIN2(wov,wou) += dist;
}
}
}
}
// Find and select the best entry...
float best = 1e100;
for (int v=startV;v<=endV;v++)
{
int wv = v - startV;
for (int u=startU;u<=endU;u++)
{
int wu = u - startU;
if (MASK2(v,u)!=0)
{
if (WIN2(wv,wu)<best)
{
best = WIN2(wv,wu);
TEMP3(y,x,0) = UV3(v,u,0);
TEMP3(y,x,1) = UV3(v,u,1);
}
}
}
}
}
}
}
// Copy from temp into image...
for (int y=0;y<Nmask[0];y++)
{
for (int x=0;x<Nmask[1];x++)
{
if (MASK2(y,x)!=0)
{
UV3(y,x,0) = TEMP3(y,x,0);
UV3(y,x,1) = TEMP3(y,x,1);
}
}
}
"""
uv = self.uv
temp = self.image
win = self.window
radius = self.radiusMF
weave.inline(code, ['mask','uv','temp','win','radius'])
| [
[
1,
0,
0.0272,
0.0015,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.0287,
0.0015,
0,
0.66,
0.25,
829,
0,
1,
0,
0,
829,
0,
0
],
[
1,
0,
0.0317,
0.0015,
0,
0.... | [
"import numpy",
"import scipy.weave as weave",
"from utils.start_cpp import start_cpp",
"from video_node import *",
"class OpticalFlowLK(VideoNode):\n \"\"\"Optical flow using Lucas & Kanade - has a pyramid and only does one iteration per pyramid level by default. Uses a median filter for regularisation. S... |
# 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/>.
import numpy
from video_node import *
class RenderMask(VideoNode):
"""This class converts a MODE_MASK into a MODE_RGB, with various effects. This includes combining an image and setting a background colour."""
def __init__(self, fgColour = (1.0,1.0,1.0), bgColour = (0.0,0.0,0.0)):
self.fgColour = fgColour
self.bgColour = bgColour
self.mask = None
self.maskChannel = 0
self.fg = None
self.fgChannel = 0
self.bg = None
self.bgChannel = 0
self.output = None
def width(self):
return self.mask.width()
def height(self):
return self.mask.height()
def fps(self):
return self.mask.fps()
def frameCount(self):
return self.mask.frameCount()
def inputCount(self):
return 3
def inputMode(self, channel=0):
if channel==0: return MODE_MASK
else: return MODE_RGB
def inputName(self, channel=0):
if channel==0: return 'Input mask'
elif channel==1: return 'Optional video stream to use for the foreground, instead of the colour.'
elif channel==2: return 'Optional video stream to use for the background, instead of the colour.'
def source(self, toChannel, video, videoChannel=0):
if toChannel==0:
self.mask = video
self.maskChannel = videoChannel
elif toChannel==1:
self.fg = video
self.fgChannel = videoChannel
elif toChannel==2:
self.bg = video
self.bgChannel = videoChannel
def dependencies(self):
ret = [self.mask]
if self.fg!=None: ret.append(self.fg)
if self.bg!=None: ret.append(self.bg)
return ret
def nextFrame(self):
mask = self.mask.fetch(self.maskChannel)
if mask==None:
self.output = None
return False
if self.output==None:
self.output = numpy.empty((mask.shape[0], mask.shape[1], 3), dtype=numpy.float32)
mask = mask.astype(numpy.bool)
if self.bg==None:
for c in xrange(3):
self.output[:,:,c] = self.bgColour[c]
else:
bg = self.bg.fetch(self.bgChannel)
if bg==None: return False
self.output[:,:,:] = bg
if self.fg==None:
for c in xrange(3):
self.output[:,:,c][mask] = self.fgColour[c]
else:
fg = self.fg.fetch(self.fgChannel)
if fg==None: return False
for c in xrange(3):
self.output[:,:,c][mask] = fg[:,:,c][mask]
return True
def outputCount(self):
return 1
def outputMode(self, channel=0):
return MODE_RGB
def outputName(self, channel=0):
return 'Mask rendered as specified'
def fetch(self, channel=0):
return self.output | [
[
1,
0,
0.1417,
0.0079,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.1575,
0.0079,
0,
0.66,
0.5,
306,
0,
1,
0,
0,
306,
0,
0
],
[
3,
0,
0.5945,
0.8189,
0,
0.6... | [
"import numpy",
"from video_node import *",
"class RenderMask(VideoNode):\n \"\"\"This class converts a MODE_MASK into a MODE_RGB, with various effects. This includes combining an image and setting a background colour.\"\"\"\n def __init__(self, fgColour = (1.0,1.0,1.0), bgColour = (0.0,0.0,0.0)):\n self.f... |
# 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/>.
import numpy
import cv
from utils.cvarray import *
from video_node import *
class WriteCV(VideoNode):
"""Simple video writting class - turns a video stream into a file on the hardrive. codec defaults to moving jpeg (MJPG), but another good choice is XVID, especially for larger files. Other options exist depending on system."""
def __init__(self, fn, codec='MJPG'):
self.fn = fn
self.codec = codec
self.writer = None
self.video = None
self.channel = 0
def width(self):
return self.video.width()
def height(self):
return self.video.height()
def fps(self):
return self.video.fps()
def frameCount(self):
return self.video.frameCount()
def inputCount(self):
return 1
def inputMode(self, channel=0):
return MODE_OTHER
def inputName(self, channel=0):
return 'Video stream to be saved to disk - supports MODE_RGB and MODE_FLOAT'
def source(self, toChannel, video, videoChannel=0):
self.video = video
self.channel = videoChannel
def dependencies(self):
return [self.video]
def nextFrame(self):
if self.writer==None:
four_cv = cv.CV_FOURCC(self.codec[0], self.codec[1], self.codec[2], self.codec[3])
self.writer = cv.CreateVideoWriter(self.fn, four_cv, self.fps(), (self.width(),self.height()), 1)
frame = self.video.fetch(self.channel)
mode = self.video.outputMode(self.channel)
frame = (frame*255.0).astype(numpy.uint8)
if mode==MODE_RGB:
out = array2cv(frame[:,:,::-1])
elif mode==MODE_FLOAT:
out = array2cv(frame)
else:
raise Exception('Unsuported mode for WriteCV')
cv.WriteFrame(self.writer, out)
return True
def outputCount(self):
return 0
| [
[
1,
0,
0.2069,
0.0115,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.2184,
0.0115,
0,
0.66,
0.25,
492,
0,
1,
0,
0,
492,
0,
0
],
[
1,
0,
0.2299,
0.0115,
0,
0.... | [
"import numpy",
"import cv",
"from utils.cvarray import *",
"from video_node import *",
"class WriteCV(VideoNode):\n \"\"\"Simple video writting class - turns a video stream into a file on the hardrive. codec defaults to moving jpeg (MJPG), but another good choice is XVID, especially for larger files. Othe... |
# 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/>.
import numpy
from video_node import *
class MaskStats(VideoNode):
"""Calculates various statistics based on having two input masks, one being an estimate, the other ground truth. Can also take a validity mask, that indicates the areas where scores are to be calculated. Statistics are stored per frame, and can be queried at any time whilst running or after running. They are basically a per-frame confusion matrix, but interfaces are provided to get the recall, the precision and the f-measure, as defined by the paper 'Evaluation of Background Subtraction Techneques for Video Surveillance' by S. Brutzer, B. Hoferlin and G. Heidemann, to give one example. Averages can also be obtained over ranges of frames. Be warned that the frame indices are zero based."""
def __init__(self):
self.guess = None
self.guessChannel = None
self.truth = None
self.truthChannel = None
self.valid = None
self.validChannel = None
self.confusion = [] # Each 2x2 array is indexed [truth,guess], where 0=False and 1=True.
def width(self):
return self.truth.width()
def height(self):
return self.truth.height()
def fps(self):
return self.truth.fps()
def frameCount(self):
return self.truth.frameCount()
def inputCount(self):
return 3
def inputMode(self, channel=0):
return MODE_MASK
def inputName(self, channel=0):
if channel==0: return 'Estimated mask.'
elif channel==1: return 'Ground truth mask.'
else: return 'Optional scoring mask, indicating the areas to factor in.'
def source(self, toChannel, video, videoChannel=0):
if toChannel==0:
self.guess = video
self.guessChannel = videoChannel
elif toChannel==1:
self.truth = video
self.truthChannel = videoChannel
else:
self.valid = video
self.validChannel = videoChannel
def dependencies(self):
if self.valid==None: return [self.guess, self.truth]
else: return [self.guess, self.truth, self.valid]
def nextFrame(self):
# Fetch the frames...
guess = self.guess.fetch(self.guessChannel)
truth = self.truth.fetch(self.truthChannel)
if self.valid!=None: valid = self.valid.fetch(self.validChannel)
# Calculate the scores...
confusion = numpy.zeros((2,2), dtype=numpy.int32)
s = numpy.logical_and(truth==0, guess==0)
if self.valid!=None: s = numpy.logical_and(s, valid!=0)
confusion[0,0] = s.sum()
s = numpy.logical_and(truth==0, guess!=0)
if self.valid!=None: s = numpy.logical_and(s, valid!=0)
confusion[0,1] = s.sum()
s = numpy.logical_and(truth!=0, guess==0)
if self.valid!=None: s = numpy.logical_and(s, valid!=0)
confusion[1,0] = s.sum()
s = numpy.logical_and(truth!=0, guess!=0)
if self.valid!=None: s = numpy.logical_and(s, valid!=0)
confusion[1,1] = s.sum()
# Store the confusion...
self.confusion.append(confusion)
def outputCount(self):
return 0
def framesAvaliable(self):
"""Returns the number of frames avaliable."""
return len(self.confusion)
def getConfusion(self, frame):
"""Returns the confusion matrix of a specific frame."""
return self.confusion[frame]
def getConfusionTotal(self, start, end):
"""Given an inclusive frame range returns the sum of the confusion matrices over that range."""
ret = numpy.zeros((2,2), dtype=numpy.int64)
for i in xrange(start,end+1): ret += self.confusion[i]
return ret
def getRecall(self, frame):
"""Given a frame returns the recall for that frame."""
con = self.confusion[frame]
if (con[1,0] + con[1,1])==0: return 1.0
return float(con[1,1]) / float(con[1,0] + con[1,1])
def getPrecision(self, frame):
"""Given a frame number returns that framess precision."""
con = self.confusion[frame]
if (con[0,1] + con[1,1])==0: return 1.0
return float(con[1,1]) / float(con[0,1] + con[1,1])
def getFMeasure(self, frame):
"""Returns the f-measure, which is the harmonic mean of the recall and precision, i.e. 2*recall*precision / (recall+precision)."""
con = self.confusion[frame]
if (con[1,0] + con[1,1])==0: recall = 1.0
else: recall = float(con[1,1]) / float(con[1,0] + con[1,1])
if (con[0,1] + con[1,1])==0: prec = 1.0
else: prec = float(con[1,1]) / float(con[0,1] + con[1,1])
return (2.0 * recall * prec) / (recall + prec)
def getFMeasureAvg(self, start, end):
"""Given an inclusive frame range returns the average of the f-measure for that range."""
ret = 0.0
for i in xrange(start,end+1):
val = self.getFMeasure(i)
ret += (val - ret) / float(i+1-start)
return ret
def getFMeasureTotal(self, start, end):
"""Returns the f-measure by summing the confusion matrix over the entire range and then calculating."""
con = self.getConfusionTotal(start, end)
recall = float(con[1,1]) / float(con[1,0] + con[1,1])
prec = float(con[1,1]) / float(con[0,1] + con[1,1])
return (2.0 * recall * prec) / (recall + prec)
| [
[
1,
0,
0.1084,
0.006,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.1205,
0.006,
0,
0.66,
0.5,
306,
0,
1,
0,
0,
306,
0,
0
],
[
3,
0,
0.5723,
0.8614,
0,
0.66,... | [
"import numpy",
"from video_node import *",
"class MaskStats(VideoNode):\n \"\"\"Calculates various statistics based on having two input masks, one being an estimate, the other ground truth. Can also take a validity mask, that indicates the areas where scores are to be calculated. Statistics are stored per fra... |
# 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/>.
import numpy
from video_node import *
class Mask_SABS(VideoNode):
"""Designed to generate the correct masking and validity information given the ground truth data of the 'Stuttgart Artificial Background Subtraction' dataset. Basically binarises the input, with black being background and every other colour being foreground, before using an erode on both channels, such that the pixels that change are marked as invalid for scoring. Outputs two masks - one indicating foreground/background, another indicating where it should be scored."""
def __init__(self):
self.vid = None
self.vidChannel = 0
self.mask = None
self.maskValid = None
self.epsilon = 0.5/255.0
def width(self):
return self.vid.width()
def height(self):
return self.vid.height()
def fps(self):
return self.vid.fps()
def frameCount(self):
return self.vid.frameCount()
def inputCount(self):
return 1
def inputMode(self, channel=0):
return MODE_RGB
def inputName(self, channel=0):
return 'Image to be turned into a mask.'
def source(self, toChannel, video, videoChannel=0):
self.vid = video
self.vidChannel = videoChannel
def dependencies(self):
return [self.vid]
def nextFrame(self):
# Fetch the data...
img = self.vid.fetch(self.vidChannel)
if img==None:
self.mask = None
self.maskValid = None
return False
# If not already created generate the stores for the mask and mask validity mask...
if self.mask==None: self.mask = numpy.empty((img.shape[0], img.shape[1]), dtype=numpy.uint8)
if self.maskValid==None: self.maskValid = numpy.empty((img.shape[0], img.shape[1]), dtype=numpy.uint8)
# Generate the mask - basically black is False, everything else True...
self.mask[:,:] = 1
self.mask[(img<self.epsilon).all(axis=2)] = 0
# Apply the erosion filter, to generate the validity mask (Done in a non-standard way, as the method is such that this can be done in a simpler way.)...
count = self.mask.copy() # Will put 0 where False, 1 where True, a fact also used below.
ind0dec = numpy.append([0],numpy.arange(self.mask.shape[0]-1))
ind1dec = numpy.append([0],numpy.arange(self.mask.shape[1]-1))
ind0inc = numpy.append(numpy.arange(1,self.mask.shape[0]),[-1])
ind1inc = numpy.append(numpy.arange(1,self.mask.shape[1]),[-1])
count += self.mask[ind0dec,:]
count += self.mask[ind0inc,:]
count += self.mask[:,ind1dec]
count += self.mask[:,ind1inc]
count += self.mask[ind0dec,:][:,ind1dec]
count += self.mask[ind0dec,:][:,ind1inc]
count += self.mask[ind0inc,:][:,ind1dec]
count += self.mask[ind0inc,:][:,ind1inc]
self.maskValid[:,:] = 0
self.maskValid[count==0] = 1
self.maskValid[count==9] = 1
return True
def outputCount(self):
return 2
def outputMode(self, channel=0):
return MODE_MASK
def outputName(self, channel=0):
if channel==0: return 'The mask generated from the colour scheme'
else: return 'Indicates where the mask is valid, i.e. where a known colour is.'
def fetch(self, channel=0):
if channel==0: return self.mask
else: return self.maskValid
| [
[
1,
0,
0.1525,
0.0085,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.1695,
0.0085,
0,
0.66,
0.5,
306,
0,
1,
0,
0,
306,
0,
0
],
[
3,
0,
0.6017,
0.8051,
0,
0.6... | [
"import numpy",
"from video_node import *",
"class Mask_SABS(VideoNode):\n \"\"\"Designed to generate the correct masking and validity information given the ground truth data of the 'Stuttgart Artificial Background Subtraction' dataset. Basically binarises the input, with black being background and every other... |
# 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/>.
import numpy
import pygame
from pygame.locals import *
from video_node import *
class ViewPyGame(VideoNode):
"""An output node for visualising frames - uses pygame and runs in fullscreen - implimented for demo purposes."""
def __init__(self, width = 1280, height = 720):
"""You provide the width and height - must be a resolution the monitor can enter."""
pygame.init()
self.flags = pygame.FULLSCREEN | pygame.DOUBLEBUF | pygame.HWSURFACE
self.screen = pygame.display.set_mode((width, height), self.flags)
pygame.mouse.set_visible(0)
self.surface = None
self.video = None
self.channel = 0
def width(self):
return self.video.width()
def height(self):
return self.video.height()
def fps(self):
return self.video.fps()
def frameCount(self):
return self.video.frameCount()
def inputCount(self):
return 1
def inputMode(self, channel=0):
return MODE_OTHER
def inputName(self, channel=0):
return 'Video stream to be visualised - supports MODE_RGB and MODE_FLOAT'
def source(self, toChannel, video, videoChannel=0):
self.video = video
self.channel = videoChannel
def dependencies(self):
return [self.video]
def nextFrame(self):
# Eat up pygame events, dying if requested...
for event in pygame.event.get():
if event.type==QUIT:
return False
if event.type==KEYDOWN and event.key==pygame.K_ESCAPE:
return False
if event.type==KEYDOWN and event.key==pygame.K_SPACE:
width = self.screen.get_width()
height = self.screen.get_height()
pygame.display.quit()
pygame.display.init()
self.flags = self.flags ^ pygame.FULLSCREEN
self.screen = pygame.display.set_mode((width, height), self.flags)
if self.flags & pygame.FULLSCREEN:
pygame.mouse.set_visible(0)
# Fetch the frae we are to draw...
frame = self.video.fetch(self.channel)
mode = self.video.outputMode(self.channel)
if frame==None: return False
# Convert it to something we can blit...
frame = numpy.swapaxes((frame*255.0).astype(numpy.uint8), 0, 1)
if self.surface==None or frame.shape[0]!=self.surface.get_width() or frame.shape[1]!=self.surface.get_height():
self.surface = pygame.surfarray.make_surface(frame)
else:
pygame.surfarray.blit_array(self.surface, frame)
# Find the drawing position...
dx = self.screen.get_width()//2 - self.surface.get_width()//2
dy = self.screen.get_height()//2 - self.surface.get_height()//2
# Draw the frame in the middle of the window...
self.screen.fill((0,0,0))
self.screen.blit(self.surface, (dx,dy))
pygame.display.flip()
return True
def outputCount(self):
return 0
| [
[
1,
0,
0.1538,
0.0085,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.1624,
0.0085,
0,
0.66,
0.25,
87,
0,
1,
0,
0,
87,
0,
0
],
[
1,
0,
0.1709,
0.0085,
0,
0.66... | [
"import numpy",
"import pygame",
"from pygame.locals import *",
"from video_node import *",
"class ViewPyGame(VideoNode):\n \"\"\"An output node for visualising frames - uses pygame and runs in fullscreen - implimented for demo purposes.\"\"\"\n def __init__(self, width = 1280, height = 720):\n \"\"\"Y... |
# 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/>.
import numpy
from video_node import *
class ClipMask(VideoNode):
"""Simple class that zeros out all areas of a mask outside a given box, in terms of displacements from the edges. Good for removing an area from a video stream that we do not want analysed, such as the sky, or a body of water."""
def __init__(self, top = 0, bottom = 0, left = 0, right = 0):
"""The coordinates are distances from the various edges, with 0 meaning to include all pixels."""
self.top = top
self.bottom = bottom
self.left = left
self.right = right
self.video = None
self.channel = 0
self.output = None
def width(self):
return self.video.width()
def height(self):
return self.video.height()
def fps(self):
return self.video.fps()
def frameCount(self):
return self.video.frameCount()
def inputCount(self):
return 1
def inputMode(self, channel=0):
return MODE_MASK
def inputName(self, channel=0):
return 'Input mask, to be spatially clipped'
def source(self, toChannel, video, videoChannel=0):
self.video = video
self.channel = videoChannel
def dependencies(self):
return [self.video]
def nextFrame(self):
# Get the frame...
self.output = self.video.fetch(self.channel)
if self.output==None: return False
self.output = self.output.copy()
# Clip it...
if self.left!=0: self.output[:,:self.left] = 0
if self.right!=0: self.output[:,-1:-self.right:-1] = 0
if self.top!=0: self.output[:self.top,:] = 0
if self.bottom!=0: self.output[-1:-self.bottom:-1,:] = 0
return True
def outputCount(self):
return 1
def outputMode(self, channel=0):
return MODE_MASK
def outputName(self, channel=0):
return 'Clipped mask'
def fetch(self, channel=0):
return self.output
| [
[
1,
0,
0.1935,
0.0108,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.2151,
0.0108,
0,
0.66,
0.5,
306,
0,
1,
0,
0,
306,
0,
0
],
[
3,
0,
0.629,
0.7527,
0,
0.66... | [
"import numpy",
"from video_node import *",
"class ClipMask(VideoNode):\n \"\"\"Simple class that zeros out all areas of a mask outside a given box, in terms of displacements from the edges. Good for removing an area from a video stream that we do not want analysed, such as the sky, or a body of water.\"\"\"\n... |
# 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/>.
import cPickle as pickle
import bz2
from video_node import *
class Play(VideoNode):
"""Plays back a file that has been saved by the Record object. Has an identical output interface to the node that was fed into Record, meaning it can be used identically."""
def __init__(self, fn):
# Open the file, verify its correct...
self.f = bz2.BZ2File(fn, 'r')
head = self.f.read(8)
assert(head=='rvnf-001')
# Read in the header information...
self.header = pickle.load(self.f)
def width(self):
return self.header[0]
def height(self):
return self.header[1]
def fps(self):
return self.header[2]
def frameCount(self):
return self.header[3]
def inputCount(self):
return 0
def dependencies(self):
return []
def nextFrame(self):
try:
self.frame = pickle.load(self.f)
except:
self.frame = None
return False
return True
def outputCount(self):
return len(self.header[4])
def outputMode(self, channel=0):
return self.header[4][channel][0]
def outputName(self, channel=0):
return self.header[4][channel][1]
def fetch(self, channel=0):
if self.frame==None: return None
return self.frame[channel]
| [
[
1,
0,
0.2368,
0.0132,
0,
0.66,
0,
279,
0,
1,
0,
0,
279,
0,
0
],
[
1,
0,
0.25,
0.0132,
0,
0.66,
0.3333,
224,
0,
1,
0,
0,
224,
0,
0
],
[
1,
0,
0.2763,
0.0132,
0,
0.... | [
"import cPickle as pickle",
"import bz2",
"from video_node import *",
"class Play(VideoNode):\n \"\"\"Plays back a file that has been saved by the Record object. Has an identical output interface to the node that was fed into Record, meaning it can be used identically.\"\"\"\n def __init__(self, fn):\n #... |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import time
class ProgBar:
"""Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops."""
def __init__(self, width = 60, onCallback = None):
self.start = time.time()
self.fill = 0
self.width = width
self.onCallback = onCallback
sys.stdout.write(('_'*self.width)+'\n')
sys.stdout.flush()
def __del__(self):
self.end = time.time()
self.__show(self.width)
sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n')
sys.stdout.flush()
def callback(self, nDone, nToDo):
"""Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo)."""
if self.onCallback:
self.onCallback()
n = int(float(self.width)*float(nDone)/float(nToDo))
n = min((n,self.width))
if n>self.fill:
self.__show(n)
def __show(self,n):
sys.stdout.write('|'*(n-self.fill))
sys.stdout.flush()
self.fill = n
| [
[
1,
0,
0.2941,
0.0196,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.3137,
0.0196,
0,
0.66,
0.5,
654,
0,
1,
0,
0,
654,
0,
0
],
[
3,
0,
0.6863,
0.6078,
0,
0.6... | [
"import sys",
"import time",
"class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ... |
# -*- coding: utf-8 -*-
# Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.).
import cv
import numpy as np
def cv2array(im):
"""Converts a cv array to a numpy array."""
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
arrdtype=im.depth
a = np.fromstring(
im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width*im.height*im.nChannels)
a.shape = (im.height,im.width,im.nChannels)
return a
def array2cv(a):
"""Converts a numpy array to a cv array, if possible."""
dtype2depth = {
'uint8': cv.IPL_DEPTH_8U,
'int8': cv.IPL_DEPTH_8S,
'uint16': cv.IPL_DEPTH_16U,
'int16': cv.IPL_DEPTH_16S,
'int32': cv.IPL_DEPTH_32S,
'float32': cv.IPL_DEPTH_32F,
'float64': cv.IPL_DEPTH_64F,
}
try:
nChannels = a.shape[2]
except:
nChannels = 1
cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]),
dtype2depth[str(a.dtype)],
nChannels)
cv.SetData(cv_im, a.tostring(),
a.dtype.itemsize*nChannels*a.shape[1])
return cv_im
| [
[
1,
0,
0.1296,
0.0185,
0,
0.66,
0,
492,
0,
1,
0,
0,
492,
0,
0
],
[
1,
0,
0.1481,
0.0185,
0,
0.66,
0.3333,
954,
0,
1,
0,
0,
954,
0,
0
],
[
2,
0,
0.3889,
0.3519,
0,
... | [
"import cv",
"import numpy as np",
"def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',",
" \... |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Some basic matrix operations that come in use...
matrix_code = start_cpp() + """
#ifndef MATRIX_CODE
#define MATRIX_CODE
template <typename T>
inline void MemSwap(T * lhs, T * rhs, int count = 1)
{
while(count!=0)
{
T t = *lhs;
*lhs = *rhs;
*rhs = t;
++lhs;
++rhs;
--count;
}
}
// Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default.
template <typename T>
inline T Determinant(T * pos, int size, int stride = -1)
{
if (stride==-1) stride = size;
if (size==1) return pos[0];
else
{
if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride];
else
{
T ret = 0.0;
for (int i=0; i<size; i++)
{
if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1);
T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1];
if ((i+size)%2) ret += sub;
else ret -= sub;
}
for (int i=1; i<size; i++)
{
MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1);
}
return ret;
}
}
}
// Inverts a square matrix, will fail on singular and very occasionally on
// non-singular matrices, returns true on success. Uses Gauss-Jordan elimination
// with partial pivoting.
// in is the input matrix, out the output matrix, just be aware that the input matrix is trashed.
// You have to provide its size (Its square, obviously.), and optionally a stride if different from size.
template <typename T>
inline bool Inverse(T * in, T * out, int size, int stride = -1)
{
if (stride==-1) stride = size;
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
out[r*stride + c] = (c==r)?1.0:0.0;
}
}
for (int r=0; r<size; r++)
{
// Find largest pivot and swap in, fail if best we can get is 0...
T max = in[r*stride + r];
int index = r;
for (int i=r+1; i<size; i++)
{
if (fabs(in[i*stride + r])>fabs(max))
{
max = in[i*stride + r];
index = i;
}
}
if (index!=r)
{
MemSwap(&in[index*stride], &in[r*stride], size);
MemSwap(&out[index*stride], &out[r*stride], size);
}
if (fabs(max-0.0)<1e-6) return false;
// Divide through the entire row...
max = 1.0/max;
in[r*stride + r] = 1.0;
for (int i=r+1; i<size; i++) in[r*stride + i] *= max;
for (int i=0; i<size; i++) out[r*stride + i] *= max;
// Row subtract to generate 0's in the current column, so it matches an identity matrix...
for (int i=0; i<size; i++)
{
if (i==r) continue;
T factor = in[i*stride + r];
in[i*stride + r] = 0.0;
for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j];
for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j];
}
}
return true;
}
#endif
"""
| [
[
1,
0,
0.1,
0.0077,
0,
0.66,
0,
972,
0,
1,
0,
0,
972,
0,
0
],
[
14,
0,
0.5692,
0.8692,
0,
0.66,
1,
974,
4,
0,
0,
0,
0,
0,
1
]
] | [
"from utils.start_cpp import start_cpp",
"matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)"
] |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
from utils.numpy_help_cpp import numpy_util_code
# Provides various functions to assist with manipulating python objects from c++ code.
python_obj_code = numpy_util_code + start_cpp() + """
#ifndef PYTHON_OBJ_CODE
#define PYTHON_OBJ_CODE
// Extracts a boolean from an object...
bool GetObjectBoolean(PyObject * obj, const char * name)
{
PyObject * b = PyObject_GetAttrString(obj, name);
bool ret = b!=Py_False;
Py_DECREF(b);
return ret;
}
// Extracts an int from an object...
int GetObjectInt(PyObject * obj, const char * name)
{
PyObject * i = PyObject_GetAttrString(obj, name);
int ret = PyInt_AsLong(i);
Py_DECREF(i);
return ret;
}
// Extracts a float from an object...
float GetObjectFloat(PyObject * obj, const char * name)
{
PyObject * f = PyObject_GetAttrString(obj, name);
float ret = PyFloat_AsDouble(f);
Py_DECREF(f);
return ret;
}
// Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored...
unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
unsigned char * ret = new unsigned char[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i);
Py_DECREF(nao);
return ret;
}
// Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored...
float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
float * ret = new float[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i);
Py_DECREF(nao);
return ret;
}
#endif
"""
| [
[
1,
0,
0.1875,
0.0125,
0,
0.66,
0,
972,
0,
1,
0,
0,
972,
0,
0
],
[
1,
0,
0.2,
0.0125,
0,
0.66,
0.5,
884,
0,
1,
0,
0,
884,
0,
0
],
[
14,
0,
0.6312,
0.75,
0,
0.66,
... | [
"from utils.start_cpp import start_cpp",
"from utils.numpy_help_cpp import numpy_util_code",
"python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj... |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import time
class ProgBar:
"""Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops."""
def __init__(self, width = 60, onCallback = None):
self.start = time.time()
self.fill = 0
self.width = width
self.onCallback = onCallback
sys.stdout.write(('_'*self.width)+'\n')
sys.stdout.flush()
def __del__(self):
self.end = time.time()
self.__show(self.width)
sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n')
sys.stdout.flush()
def callback(self, nDone, nToDo):
"""Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo)."""
if self.onCallback:
self.onCallback()
n = int(float(self.width)*float(nDone)/float(nToDo))
n = min((n,self.width))
if n>self.fill:
self.__show(n)
def __show(self,n):
sys.stdout.write('|'*(n-self.fill))
sys.stdout.flush()
self.fill = n
| [
[
1,
0,
0.2941,
0.0196,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.3137,
0.0196,
0,
0.66,
0.5,
654,
0,
1,
0,
0,
654,
0,
0
],
[
3,
0,
0.6863,
0.6078,
0,
0.6... | [
"import sys",
"import time",
"class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ... |
# -*- coding: utf-8 -*-
# Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.).
import cv
import numpy as np
def cv2array(im):
"""Converts a cv array to a numpy array."""
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
arrdtype=im.depth
a = np.fromstring(
im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width*im.height*im.nChannels)
a.shape = (im.height,im.width,im.nChannels)
return a
def array2cv(a):
"""Converts a numpy array to a cv array, if possible."""
dtype2depth = {
'uint8': cv.IPL_DEPTH_8U,
'int8': cv.IPL_DEPTH_8S,
'uint16': cv.IPL_DEPTH_16U,
'int16': cv.IPL_DEPTH_16S,
'int32': cv.IPL_DEPTH_32S,
'float32': cv.IPL_DEPTH_32F,
'float64': cv.IPL_DEPTH_64F,
}
try:
nChannels = a.shape[2]
except:
nChannels = 1
cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]),
dtype2depth[str(a.dtype)],
nChannels)
cv.SetData(cv_im, a.tostring(),
a.dtype.itemsize*nChannels*a.shape[1])
return cv_im
| [
[
1,
0,
0.1296,
0.0185,
0,
0.66,
0,
492,
0,
1,
0,
0,
492,
0,
0
],
[
1,
0,
0.1481,
0.0185,
0,
0.66,
0.3333,
954,
0,
1,
0,
0,
954,
0,
0
],
[
2,
0,
0.3889,
0.3519,
0,
... | [
"import cv",
"import numpy as np",
"def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',",
" \... |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Some basic matrix operations that come in use...
matrix_code = start_cpp() + """
#ifndef MATRIX_CODE
#define MATRIX_CODE
template <typename T>
inline void MemSwap(T * lhs, T * rhs, int count = 1)
{
while(count!=0)
{
T t = *lhs;
*lhs = *rhs;
*rhs = t;
++lhs;
++rhs;
--count;
}
}
// Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default.
template <typename T>
inline T Determinant(T * pos, int size, int stride = -1)
{
if (stride==-1) stride = size;
if (size==1) return pos[0];
else
{
if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride];
else
{
T ret = 0.0;
for (int i=0; i<size; i++)
{
if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1);
T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1];
if ((i+size)%2) ret += sub;
else ret -= sub;
}
for (int i=1; i<size; i++)
{
MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1);
}
return ret;
}
}
}
// Inverts a square matrix, will fail on singular and very occasionally on
// non-singular matrices, returns true on success. Uses Gauss-Jordan elimination
// with partial pivoting.
// in is the input matrix, out the output matrix, just be aware that the input matrix is trashed.
// You have to provide its size (Its square, obviously.), and optionally a stride if different from size.
template <typename T>
inline bool Inverse(T * in, T * out, int size, int stride = -1)
{
if (stride==-1) stride = size;
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
out[r*stride + c] = (c==r)?1.0:0.0;
}
}
for (int r=0; r<size; r++)
{
// Find largest pivot and swap in, fail if best we can get is 0...
T max = in[r*stride + r];
int index = r;
for (int i=r+1; i<size; i++)
{
if (fabs(in[i*stride + r])>fabs(max))
{
max = in[i*stride + r];
index = i;
}
}
if (index!=r)
{
MemSwap(&in[index*stride], &in[r*stride], size);
MemSwap(&out[index*stride], &out[r*stride], size);
}
if (fabs(max-0.0)<1e-6) return false;
// Divide through the entire row...
max = 1.0/max;
in[r*stride + r] = 1.0;
for (int i=r+1; i<size; i++) in[r*stride + i] *= max;
for (int i=0; i<size; i++) out[r*stride + i] *= max;
// Row subtract to generate 0's in the current column, so it matches an identity matrix...
for (int i=0; i<size; i++)
{
if (i==r) continue;
T factor = in[i*stride + r];
in[i*stride + r] = 0.0;
for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j];
for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j];
}
}
return true;
}
#endif
"""
| [
[
1,
0,
0.1,
0.0077,
0,
0.66,
0,
972,
0,
1,
0,
0,
972,
0,
0
],
[
14,
0,
0.5692,
0.8692,
0,
0.66,
1,
974,
4,
0,
0,
0,
0,
0,
1
]
] | [
"from utils.start_cpp import start_cpp",
"matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)"
] |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
from utils.numpy_help_cpp import numpy_util_code
# Provides various functions to assist with manipulating python objects from c++ code.
python_obj_code = numpy_util_code + start_cpp() + """
#ifndef PYTHON_OBJ_CODE
#define PYTHON_OBJ_CODE
// Extracts a boolean from an object...
bool GetObjectBoolean(PyObject * obj, const char * name)
{
PyObject * b = PyObject_GetAttrString(obj, name);
bool ret = b!=Py_False;
Py_DECREF(b);
return ret;
}
// Extracts an int from an object...
int GetObjectInt(PyObject * obj, const char * name)
{
PyObject * i = PyObject_GetAttrString(obj, name);
int ret = PyInt_AsLong(i);
Py_DECREF(i);
return ret;
}
// Extracts a float from an object...
float GetObjectFloat(PyObject * obj, const char * name)
{
PyObject * f = PyObject_GetAttrString(obj, name);
float ret = PyFloat_AsDouble(f);
Py_DECREF(f);
return ret;
}
// Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored...
unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
unsigned char * ret = new unsigned char[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i);
Py_DECREF(nao);
return ret;
}
// Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored...
float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
float * ret = new float[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i);
Py_DECREF(nao);
return ret;
}
#endif
"""
| [
[
1,
0,
0.1875,
0.0125,
0,
0.66,
0,
972,
0,
1,
0,
0,
972,
0,
0
],
[
1,
0,
0.2,
0.0125,
0,
0.66,
0.5,
884,
0,
1,
0,
0,
884,
0,
0
],
[
14,
0,
0.6312,
0.75,
0,
0.66,
... | [
"from utils.start_cpp import start_cpp",
"from utils.numpy_help_cpp import numpy_util_code",
"python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj... |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import time
class ProgBar:
"""Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops."""
def __init__(self, width = 60, onCallback = None):
self.start = time.time()
self.fill = 0
self.width = width
self.onCallback = onCallback
sys.stdout.write(('_'*self.width)+'\n')
sys.stdout.flush()
def __del__(self):
self.end = time.time()
self.__show(self.width)
sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n')
sys.stdout.flush()
def callback(self, nDone, nToDo):
"""Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo)."""
if self.onCallback:
self.onCallback()
n = int(float(self.width)*float(nDone)/float(nToDo))
n = min((n,self.width))
if n>self.fill:
self.__show(n)
def __show(self,n):
sys.stdout.write('|'*(n-self.fill))
sys.stdout.flush()
self.fill = n
| [
[
1,
0,
0.2941,
0.0196,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.3137,
0.0196,
0,
0.66,
0.5,
654,
0,
1,
0,
0,
654,
0,
0
],
[
3,
0,
0.6863,
0.6078,
0,
0.6... | [
"import sys",
"import time",
"class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ... |
# -*- coding: utf-8 -*-
# Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.).
import cv
import numpy as np
def cv2array(im):
"""Converts a cv array to a numpy array."""
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
arrdtype=im.depth
a = np.fromstring(
im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width*im.height*im.nChannels)
a.shape = (im.height,im.width,im.nChannels)
return a
def array2cv(a):
"""Converts a numpy array to a cv array, if possible."""
dtype2depth = {
'uint8': cv.IPL_DEPTH_8U,
'int8': cv.IPL_DEPTH_8S,
'uint16': cv.IPL_DEPTH_16U,
'int16': cv.IPL_DEPTH_16S,
'int32': cv.IPL_DEPTH_32S,
'float32': cv.IPL_DEPTH_32F,
'float64': cv.IPL_DEPTH_64F,
}
try:
nChannels = a.shape[2]
except:
nChannels = 1
cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]),
dtype2depth[str(a.dtype)],
nChannels)
cv.SetData(cv_im, a.tostring(),
a.dtype.itemsize*nChannels*a.shape[1])
return cv_im
| [
[
1,
0,
0.1296,
0.0185,
0,
0.66,
0,
492,
0,
1,
0,
0,
492,
0,
0
],
[
1,
0,
0.1481,
0.0185,
0,
0.66,
0.3333,
954,
0,
1,
0,
0,
954,
0,
0
],
[
2,
0,
0.3889,
0.3519,
0,
... | [
"import cv",
"import numpy as np",
"def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',",
" \... |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Some basic matrix operations that come in use...
matrix_code = start_cpp() + """
#ifndef MATRIX_CODE
#define MATRIX_CODE
template <typename T>
inline void MemSwap(T * lhs, T * rhs, int count = 1)
{
while(count!=0)
{
T t = *lhs;
*lhs = *rhs;
*rhs = t;
++lhs;
++rhs;
--count;
}
}
// Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default.
template <typename T>
inline T Determinant(T * pos, int size, int stride = -1)
{
if (stride==-1) stride = size;
if (size==1) return pos[0];
else
{
if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride];
else
{
T ret = 0.0;
for (int i=0; i<size; i++)
{
if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1);
T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1];
if ((i+size)%2) ret += sub;
else ret -= sub;
}
for (int i=1; i<size; i++)
{
MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1);
}
return ret;
}
}
}
// Inverts a square matrix, will fail on singular and very occasionally on
// non-singular matrices, returns true on success. Uses Gauss-Jordan elimination
// with partial pivoting.
// in is the input matrix, out the output matrix, just be aware that the input matrix is trashed.
// You have to provide its size (Its square, obviously.), and optionally a stride if different from size.
template <typename T>
inline bool Inverse(T * in, T * out, int size, int stride = -1)
{
if (stride==-1) stride = size;
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
out[r*stride + c] = (c==r)?1.0:0.0;
}
}
for (int r=0; r<size; r++)
{
// Find largest pivot and swap in, fail if best we can get is 0...
T max = in[r*stride + r];
int index = r;
for (int i=r+1; i<size; i++)
{
if (fabs(in[i*stride + r])>fabs(max))
{
max = in[i*stride + r];
index = i;
}
}
if (index!=r)
{
MemSwap(&in[index*stride], &in[r*stride], size);
MemSwap(&out[index*stride], &out[r*stride], size);
}
if (fabs(max-0.0)<1e-6) return false;
// Divide through the entire row...
max = 1.0/max;
in[r*stride + r] = 1.0;
for (int i=r+1; i<size; i++) in[r*stride + i] *= max;
for (int i=0; i<size; i++) out[r*stride + i] *= max;
// Row subtract to generate 0's in the current column, so it matches an identity matrix...
for (int i=0; i<size; i++)
{
if (i==r) continue;
T factor = in[i*stride + r];
in[i*stride + r] = 0.0;
for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j];
for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j];
}
}
return true;
}
#endif
"""
| [
[
1,
0,
0.1,
0.0077,
0,
0.66,
0,
972,
0,
1,
0,
0,
972,
0,
0
],
[
14,
0,
0.5692,
0.8692,
0,
0.66,
1,
974,
4,
0,
0,
0,
0,
0,
1
]
] | [
"from utils.start_cpp import start_cpp",
"matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)"
] |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
from utils.numpy_help_cpp import numpy_util_code
# Provides various functions to assist with manipulating python objects from c++ code.
python_obj_code = numpy_util_code + start_cpp() + """
#ifndef PYTHON_OBJ_CODE
#define PYTHON_OBJ_CODE
// Extracts a boolean from an object...
bool GetObjectBoolean(PyObject * obj, const char * name)
{
PyObject * b = PyObject_GetAttrString(obj, name);
bool ret = b!=Py_False;
Py_DECREF(b);
return ret;
}
// Extracts an int from an object...
int GetObjectInt(PyObject * obj, const char * name)
{
PyObject * i = PyObject_GetAttrString(obj, name);
int ret = PyInt_AsLong(i);
Py_DECREF(i);
return ret;
}
// Extracts a float from an object...
float GetObjectFloat(PyObject * obj, const char * name)
{
PyObject * f = PyObject_GetAttrString(obj, name);
float ret = PyFloat_AsDouble(f);
Py_DECREF(f);
return ret;
}
// Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored...
unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
unsigned char * ret = new unsigned char[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i);
Py_DECREF(nao);
return ret;
}
// Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored...
float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
float * ret = new float[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i);
Py_DECREF(nao);
return ret;
}
#endif
"""
| [
[
1,
0,
0.1875,
0.0125,
0,
0.66,
0,
972,
0,
1,
0,
0,
972,
0,
0
],
[
1,
0,
0.2,
0.0125,
0,
0.66,
0.5,
884,
0,
1,
0,
0,
884,
0,
0
],
[
14,
0,
0.6312,
0.75,
0,
0.66,
... | [
"from utils.start_cpp import start_cpp",
"from utils.numpy_help_cpp import numpy_util_code",
"python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj... |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import time
class ProgBar:
"""Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops."""
def __init__(self, width = 60, onCallback = None):
self.start = time.time()
self.fill = 0
self.width = width
self.onCallback = onCallback
sys.stdout.write(('_'*self.width)+'\n')
sys.stdout.flush()
def __del__(self):
self.end = time.time()
self.__show(self.width)
sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n')
sys.stdout.flush()
def callback(self, nDone, nToDo):
"""Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo)."""
if self.onCallback:
self.onCallback()
n = int(float(self.width)*float(nDone)/float(nToDo))
n = min((n,self.width))
if n>self.fill:
self.__show(n)
def __show(self,n):
sys.stdout.write('|'*(n-self.fill))
sys.stdout.flush()
self.fill = n
| [
[
1,
0,
0.2941,
0.0196,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.3137,
0.0196,
0,
0.66,
0.5,
654,
0,
1,
0,
0,
654,
0,
0
],
[
3,
0,
0.6863,
0.6078,
0,
0.6... | [
"import sys",
"import time",
"class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.