code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
from utils.numpy_help_cpp import numpy_util_code
# Provides various functions to assist with manipulating python objects from c++ code.
python_obj_code = numpy_util_code + start_cpp() + """
#ifndef PYTHON_OBJ_CODE
#define PYTHON_OBJ_CODE
// Extracts a boolean from an object...
bool GetObjectBoolean(PyObject * obj, const char * name)
{
PyObject * b = PyObject_GetAttrString(obj, name);
bool ret = b!=Py_False;
Py_DECREF(b);
return ret;
}
// Extracts an int from an object...
int GetObjectInt(PyObject * obj, const char * name)
{
PyObject * i = PyObject_GetAttrString(obj, name);
int ret = PyInt_AsLong(i);
Py_DECREF(i);
return ret;
}
// Extracts a float from an object...
float GetObjectFloat(PyObject * obj, const char * name)
{
PyObject * f = PyObject_GetAttrString(obj, name);
float ret = PyFloat_AsDouble(f);
Py_DECREF(f);
return ret;
}
// Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored...
unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
unsigned char * ret = new unsigned char[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i);
Py_DECREF(nao);
return ret;
}
// Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored...
float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
float * ret = new float[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i);
Py_DECREF(nao);
return ret;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import time
class ProgBar:
"""Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops."""
def __init__(self, width = 60, onCallback = None):
self.start = time.time()
self.fill = 0
self.width = width
self.onCallback = onCallback
sys.stdout.write(('_'*self.width)+'\n')
sys.stdout.flush()
def __del__(self):
self.end = time.time()
self.__show(self.width)
sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n')
sys.stdout.flush()
def callback(self, nDone, nToDo):
"""Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo)."""
if self.onCallback:
self.onCallback()
n = int(float(self.width)*float(nDone)/float(nToDo))
n = min((n,self.width))
if n>self.fill:
self.__show(n)
def __show(self,n):
sys.stdout.write('|'*(n-self.fill))
sys.stdout.flush()
self.fill = n
| Python |
# -*- coding: utf-8 -*-
# Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.).
import cv
import numpy as np
def cv2array(im):
"""Converts a cv array to a numpy array."""
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
arrdtype=im.depth
a = np.fromstring(
im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width*im.height*im.nChannels)
a.shape = (im.height,im.width,im.nChannels)
return a
def array2cv(a):
"""Converts a numpy array to a cv array, if possible."""
dtype2depth = {
'uint8': cv.IPL_DEPTH_8U,
'int8': cv.IPL_DEPTH_8S,
'uint16': cv.IPL_DEPTH_16U,
'int16': cv.IPL_DEPTH_16S,
'int32': cv.IPL_DEPTH_32S,
'float32': cv.IPL_DEPTH_32F,
'float64': cv.IPL_DEPTH_64F,
}
try:
nChannels = a.shape[2]
except:
nChannels = 1
cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]),
dtype2depth[str(a.dtype)],
nChannels)
cv.SetData(cv_im, a.tostring(),
a.dtype.itemsize*nChannels*a.shape[1])
return cv_im
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Some basic matrix operations that come in use...
matrix_code = start_cpp() + """
#ifndef MATRIX_CODE
#define MATRIX_CODE
template <typename T>
inline void MemSwap(T * lhs, T * rhs, int count = 1)
{
while(count!=0)
{
T t = *lhs;
*lhs = *rhs;
*rhs = t;
++lhs;
++rhs;
--count;
}
}
// Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default.
template <typename T>
inline T Determinant(T * pos, int size, int stride = -1)
{
if (stride==-1) stride = size;
if (size==1) return pos[0];
else
{
if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride];
else
{
T ret = 0.0;
for (int i=0; i<size; i++)
{
if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1);
T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1];
if ((i+size)%2) ret += sub;
else ret -= sub;
}
for (int i=1; i<size; i++)
{
MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1);
}
return ret;
}
}
}
// Inverts a square matrix, will fail on singular and very occasionally on
// non-singular matrices, returns true on success. Uses Gauss-Jordan elimination
// with partial pivoting.
// in is the input matrix, out the output matrix, just be aware that the input matrix is trashed.
// You have to provide its size (Its square, obviously.), and optionally a stride if different from size.
template <typename T>
inline bool Inverse(T * in, T * out, int size, int stride = -1)
{
if (stride==-1) stride = size;
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
out[r*stride + c] = (c==r)?1.0:0.0;
}
}
for (int r=0; r<size; r++)
{
// Find largest pivot and swap in, fail if best we can get is 0...
T max = in[r*stride + r];
int index = r;
for (int i=r+1; i<size; i++)
{
if (fabs(in[i*stride + r])>fabs(max))
{
max = in[i*stride + r];
index = i;
}
}
if (index!=r)
{
MemSwap(&in[index*stride], &in[r*stride], size);
MemSwap(&out[index*stride], &out[r*stride], size);
}
if (fabs(max-0.0)<1e-6) return false;
// Divide through the entire row...
max = 1.0/max;
in[r*stride + r] = 1.0;
for (int i=r+1; i<size; i++) in[r*stride + i] *= max;
for (int i=0; i<size; i++) out[r*stride + i] *= max;
// Row subtract to generate 0's in the current column, so it matches an identity matrix...
for (int i=0; i<size; i++)
{
if (i==r) continue;
T factor = in[i*stride + r];
in[i*stride + r] = 0.0;
for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j];
for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j];
}
}
return true;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
from utils.numpy_help_cpp import numpy_util_code
# Provides various functions to assist with manipulating python objects from c++ code.
python_obj_code = numpy_util_code + start_cpp() + """
#ifndef PYTHON_OBJ_CODE
#define PYTHON_OBJ_CODE
// Extracts a boolean from an object...
bool GetObjectBoolean(PyObject * obj, const char * name)
{
PyObject * b = PyObject_GetAttrString(obj, name);
bool ret = b!=Py_False;
Py_DECREF(b);
return ret;
}
// Extracts an int from an object...
int GetObjectInt(PyObject * obj, const char * name)
{
PyObject * i = PyObject_GetAttrString(obj, name);
int ret = PyInt_AsLong(i);
Py_DECREF(i);
return ret;
}
// Extracts a float from an object...
float GetObjectFloat(PyObject * obj, const char * name)
{
PyObject * f = PyObject_GetAttrString(obj, name);
float ret = PyFloat_AsDouble(f);
Py_DECREF(f);
return ret;
}
// Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored...
unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
unsigned char * ret = new unsigned char[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i);
Py_DECREF(nao);
return ret;
}
// Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored...
float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
float * ret = new float[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i);
Py_DECREF(nao);
return ret;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import time
class ProgBar:
"""Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops."""
def __init__(self, width = 60, onCallback = None):
self.start = time.time()
self.fill = 0
self.width = width
self.onCallback = onCallback
sys.stdout.write(('_'*self.width)+'\n')
sys.stdout.flush()
def __del__(self):
self.end = time.time()
self.__show(self.width)
sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n')
sys.stdout.flush()
def callback(self, nDone, nToDo):
"""Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo)."""
if self.onCallback:
self.onCallback()
n = int(float(self.width)*float(nDone)/float(nToDo))
n = min((n,self.width))
if n>self.fill:
self.__show(n)
def __show(self,n):
sys.stdout.write('|'*(n-self.fill))
sys.stdout.flush()
self.fill = n
| Python |
# -*- coding: utf-8 -*-
# Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.).
import cv
import numpy as np
def cv2array(im):
"""Converts a cv array to a numpy array."""
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
arrdtype=im.depth
a = np.fromstring(
im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width*im.height*im.nChannels)
a.shape = (im.height,im.width,im.nChannels)
return a
def array2cv(a):
"""Converts a numpy array to a cv array, if possible."""
dtype2depth = {
'uint8': cv.IPL_DEPTH_8U,
'int8': cv.IPL_DEPTH_8S,
'uint16': cv.IPL_DEPTH_16U,
'int16': cv.IPL_DEPTH_16S,
'int32': cv.IPL_DEPTH_32S,
'float32': cv.IPL_DEPTH_32F,
'float64': cv.IPL_DEPTH_64F,
}
try:
nChannels = a.shape[2]
except:
nChannels = 1
cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]),
dtype2depth[str(a.dtype)],
nChannels)
cv.SetData(cv_im, a.tostring(),
a.dtype.itemsize*nChannels*a.shape[1])
return cv_im
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Some basic matrix operations that come in use...
matrix_code = start_cpp() + """
#ifndef MATRIX_CODE
#define MATRIX_CODE
template <typename T>
inline void MemSwap(T * lhs, T * rhs, int count = 1)
{
while(count!=0)
{
T t = *lhs;
*lhs = *rhs;
*rhs = t;
++lhs;
++rhs;
--count;
}
}
// Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default.
template <typename T>
inline T Determinant(T * pos, int size, int stride = -1)
{
if (stride==-1) stride = size;
if (size==1) return pos[0];
else
{
if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride];
else
{
T ret = 0.0;
for (int i=0; i<size; i++)
{
if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1);
T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1];
if ((i+size)%2) ret += sub;
else ret -= sub;
}
for (int i=1; i<size; i++)
{
MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1);
}
return ret;
}
}
}
// Inverts a square matrix, will fail on singular and very occasionally on
// non-singular matrices, returns true on success. Uses Gauss-Jordan elimination
// with partial pivoting.
// in is the input matrix, out the output matrix, just be aware that the input matrix is trashed.
// You have to provide its size (Its square, obviously.), and optionally a stride if different from size.
template <typename T>
inline bool Inverse(T * in, T * out, int size, int stride = -1)
{
if (stride==-1) stride = size;
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
out[r*stride + c] = (c==r)?1.0:0.0;
}
}
for (int r=0; r<size; r++)
{
// Find largest pivot and swap in, fail if best we can get is 0...
T max = in[r*stride + r];
int index = r;
for (int i=r+1; i<size; i++)
{
if (fabs(in[i*stride + r])>fabs(max))
{
max = in[i*stride + r];
index = i;
}
}
if (index!=r)
{
MemSwap(&in[index*stride], &in[r*stride], size);
MemSwap(&out[index*stride], &out[r*stride], size);
}
if (fabs(max-0.0)<1e-6) return false;
// Divide through the entire row...
max = 1.0/max;
in[r*stride + r] = 1.0;
for (int i=r+1; i<size; i++) in[r*stride + i] *= max;
for (int i=0; i<size; i++) out[r*stride + i] *= max;
// Row subtract to generate 0's in the current column, so it matches an identity matrix...
for (int i=0; i<size; i++)
{
if (i==r) continue;
T factor = in[i*stride + r];
in[i*stride + r] = 0.0;
for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j];
for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j];
}
}
return true;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
from utils.numpy_help_cpp import numpy_util_code
# Provides various functions to assist with manipulating python objects from c++ code.
python_obj_code = numpy_util_code + start_cpp() + """
#ifndef PYTHON_OBJ_CODE
#define PYTHON_OBJ_CODE
// Extracts a boolean from an object...
bool GetObjectBoolean(PyObject * obj, const char * name)
{
PyObject * b = PyObject_GetAttrString(obj, name);
bool ret = b!=Py_False;
Py_DECREF(b);
return ret;
}
// Extracts an int from an object...
int GetObjectInt(PyObject * obj, const char * name)
{
PyObject * i = PyObject_GetAttrString(obj, name);
int ret = PyInt_AsLong(i);
Py_DECREF(i);
return ret;
}
// Extracts a float from an object...
float GetObjectFloat(PyObject * obj, const char * name)
{
PyObject * f = PyObject_GetAttrString(obj, name);
float ret = PyFloat_AsDouble(f);
Py_DECREF(f);
return ret;
}
// Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored...
unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
unsigned char * ret = new unsigned char[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i);
Py_DECREF(nao);
return ret;
}
// Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored...
float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
float * ret = new float[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i);
Py_DECREF(nao);
return ret;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import time
class ProgBar:
"""Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops."""
def __init__(self, width = 60, onCallback = None):
self.start = time.time()
self.fill = 0
self.width = width
self.onCallback = onCallback
sys.stdout.write(('_'*self.width)+'\n')
sys.stdout.flush()
def __del__(self):
self.end = time.time()
self.__show(self.width)
sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n')
sys.stdout.flush()
def callback(self, nDone, nToDo):
"""Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo)."""
if self.onCallback:
self.onCallback()
n = int(float(self.width)*float(nDone)/float(nToDo))
n = min((n,self.width))
if n>self.fill:
self.__show(n)
def __show(self,n):
sys.stdout.write('|'*(n-self.fill))
sys.stdout.flush()
self.fill = n
| Python |
# -*- coding: utf-8 -*-
# Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.).
import cv
import numpy as np
def cv2array(im):
"""Converts a cv array to a numpy array."""
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
arrdtype=im.depth
a = np.fromstring(
im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width*im.height*im.nChannels)
a.shape = (im.height,im.width,im.nChannels)
return a
def array2cv(a):
"""Converts a numpy array to a cv array, if possible."""
dtype2depth = {
'uint8': cv.IPL_DEPTH_8U,
'int8': cv.IPL_DEPTH_8S,
'uint16': cv.IPL_DEPTH_16U,
'int16': cv.IPL_DEPTH_16S,
'int32': cv.IPL_DEPTH_32S,
'float32': cv.IPL_DEPTH_32F,
'float64': cv.IPL_DEPTH_64F,
}
try:
nChannels = a.shape[2]
except:
nChannels = 1
cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]),
dtype2depth[str(a.dtype)],
nChannels)
cv.SetData(cv_im, a.tostring(),
a.dtype.itemsize*nChannels*a.shape[1])
return cv_im
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Some basic matrix operations that come in use...
matrix_code = start_cpp() + """
#ifndef MATRIX_CODE
#define MATRIX_CODE
template <typename T>
inline void MemSwap(T * lhs, T * rhs, int count = 1)
{
while(count!=0)
{
T t = *lhs;
*lhs = *rhs;
*rhs = t;
++lhs;
++rhs;
--count;
}
}
// Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default.
template <typename T>
inline T Determinant(T * pos, int size, int stride = -1)
{
if (stride==-1) stride = size;
if (size==1) return pos[0];
else
{
if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride];
else
{
T ret = 0.0;
for (int i=0; i<size; i++)
{
if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1);
T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1];
if ((i+size)%2) ret += sub;
else ret -= sub;
}
for (int i=1; i<size; i++)
{
MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1);
}
return ret;
}
}
}
// Inverts a square matrix, will fail on singular and very occasionally on
// non-singular matrices, returns true on success. Uses Gauss-Jordan elimination
// with partial pivoting.
// in is the input matrix, out the output matrix, just be aware that the input matrix is trashed.
// You have to provide its size (Its square, obviously.), and optionally a stride if different from size.
template <typename T>
inline bool Inverse(T * in, T * out, int size, int stride = -1)
{
if (stride==-1) stride = size;
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
out[r*stride + c] = (c==r)?1.0:0.0;
}
}
for (int r=0; r<size; r++)
{
// Find largest pivot and swap in, fail if best we can get is 0...
T max = in[r*stride + r];
int index = r;
for (int i=r+1; i<size; i++)
{
if (fabs(in[i*stride + r])>fabs(max))
{
max = in[i*stride + r];
index = i;
}
}
if (index!=r)
{
MemSwap(&in[index*stride], &in[r*stride], size);
MemSwap(&out[index*stride], &out[r*stride], size);
}
if (fabs(max-0.0)<1e-6) return false;
// Divide through the entire row...
max = 1.0/max;
in[r*stride + r] = 1.0;
for (int i=r+1; i<size; i++) in[r*stride + i] *= max;
for (int i=0; i<size; i++) out[r*stride + i] *= max;
// Row subtract to generate 0's in the current column, so it matches an identity matrix...
for (int i=0; i<size; i++)
{
if (i==r) continue;
T factor = in[i*stride + r];
in[i*stride + r] = 0.0;
for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j];
for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j];
}
}
return true;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
from utils.numpy_help_cpp import numpy_util_code
# Provides various functions to assist with manipulating python objects from c++ code.
python_obj_code = numpy_util_code + start_cpp() + """
#ifndef PYTHON_OBJ_CODE
#define PYTHON_OBJ_CODE
// Extracts a boolean from an object...
bool GetObjectBoolean(PyObject * obj, const char * name)
{
PyObject * b = PyObject_GetAttrString(obj, name);
bool ret = b!=Py_False;
Py_DECREF(b);
return ret;
}
// Extracts an int from an object...
int GetObjectInt(PyObject * obj, const char * name)
{
PyObject * i = PyObject_GetAttrString(obj, name);
int ret = PyInt_AsLong(i);
Py_DECREF(i);
return ret;
}
// Extracts a float from an object...
float GetObjectFloat(PyObject * obj, const char * name)
{
PyObject * f = PyObject_GetAttrString(obj, name);
float ret = PyFloat_AsDouble(f);
Py_DECREF(f);
return ret;
}
// Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored...
unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
unsigned char * ret = new unsigned char[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i);
Py_DECREF(nao);
return ret;
}
// Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored...
float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
float * ret = new float[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i);
Py_DECREF(nao);
return ret;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import time
class ProgBar:
"""Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops."""
def __init__(self, width = 60, onCallback = None):
self.start = time.time()
self.fill = 0
self.width = width
self.onCallback = onCallback
sys.stdout.write(('_'*self.width)+'\n')
sys.stdout.flush()
def __del__(self):
self.end = time.time()
self.__show(self.width)
sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n')
sys.stdout.flush()
def callback(self, nDone, nToDo):
"""Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo)."""
if self.onCallback:
self.onCallback()
n = int(float(self.width)*float(nDone)/float(nToDo))
n = min((n,self.width))
if n>self.fill:
self.__show(n)
def __show(self,n):
sys.stdout.write('|'*(n-self.fill))
sys.stdout.flush()
self.fill = n
| Python |
# -*- coding: utf-8 -*-
# Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.).
import cv
import numpy as np
def cv2array(im):
"""Converts a cv array to a numpy array."""
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
arrdtype=im.depth
a = np.fromstring(
im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width*im.height*im.nChannels)
a.shape = (im.height,im.width,im.nChannels)
return a
def array2cv(a):
"""Converts a numpy array to a cv array, if possible."""
dtype2depth = {
'uint8': cv.IPL_DEPTH_8U,
'int8': cv.IPL_DEPTH_8S,
'uint16': cv.IPL_DEPTH_16U,
'int16': cv.IPL_DEPTH_16S,
'int32': cv.IPL_DEPTH_32S,
'float32': cv.IPL_DEPTH_32F,
'float64': cv.IPL_DEPTH_64F,
}
try:
nChannels = a.shape[2]
except:
nChannels = 1
cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]),
dtype2depth[str(a.dtype)],
nChannels)
cv.SetData(cv_im, a.tostring(),
a.dtype.itemsize*nChannels*a.shape[1])
return cv_im
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Some basic matrix operations that come in use...
matrix_code = start_cpp() + """
#ifndef MATRIX_CODE
#define MATRIX_CODE
template <typename T>
inline void MemSwap(T * lhs, T * rhs, int count = 1)
{
while(count!=0)
{
T t = *lhs;
*lhs = *rhs;
*rhs = t;
++lhs;
++rhs;
--count;
}
}
// Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default.
template <typename T>
inline T Determinant(T * pos, int size, int stride = -1)
{
if (stride==-1) stride = size;
if (size==1) return pos[0];
else
{
if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride];
else
{
T ret = 0.0;
for (int i=0; i<size; i++)
{
if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1);
T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1];
if ((i+size)%2) ret += sub;
else ret -= sub;
}
for (int i=1; i<size; i++)
{
MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1);
}
return ret;
}
}
}
// Inverts a square matrix, will fail on singular and very occasionally on
// non-singular matrices, returns true on success. Uses Gauss-Jordan elimination
// with partial pivoting.
// in is the input matrix, out the output matrix, just be aware that the input matrix is trashed.
// You have to provide its size (Its square, obviously.), and optionally a stride if different from size.
template <typename T>
inline bool Inverse(T * in, T * out, int size, int stride = -1)
{
if (stride==-1) stride = size;
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
out[r*stride + c] = (c==r)?1.0:0.0;
}
}
for (int r=0; r<size; r++)
{
// Find largest pivot and swap in, fail if best we can get is 0...
T max = in[r*stride + r];
int index = r;
for (int i=r+1; i<size; i++)
{
if (fabs(in[i*stride + r])>fabs(max))
{
max = in[i*stride + r];
index = i;
}
}
if (index!=r)
{
MemSwap(&in[index*stride], &in[r*stride], size);
MemSwap(&out[index*stride], &out[r*stride], size);
}
if (fabs(max-0.0)<1e-6) return false;
// Divide through the entire row...
max = 1.0/max;
in[r*stride + r] = 1.0;
for (int i=r+1; i<size; i++) in[r*stride + i] *= max;
for (int i=0; i<size; i++) out[r*stride + i] *= max;
// Row subtract to generate 0's in the current column, so it matches an identity matrix...
for (int i=0; i<size; i++)
{
if (i==r) continue;
T factor = in[i*stride + r];
in[i*stride + r] = 0.0;
for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j];
for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j];
}
}
return true;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
from utils.numpy_help_cpp import numpy_util_code
# Provides various functions to assist with manipulating python objects from c++ code.
python_obj_code = numpy_util_code + start_cpp() + """
#ifndef PYTHON_OBJ_CODE
#define PYTHON_OBJ_CODE
// Extracts a boolean from an object...
bool GetObjectBoolean(PyObject * obj, const char * name)
{
PyObject * b = PyObject_GetAttrString(obj, name);
bool ret = b!=Py_False;
Py_DECREF(b);
return ret;
}
// Extracts an int from an object...
int GetObjectInt(PyObject * obj, const char * name)
{
PyObject * i = PyObject_GetAttrString(obj, name);
int ret = PyInt_AsLong(i);
Py_DECREF(i);
return ret;
}
// Extracts a float from an object...
float GetObjectFloat(PyObject * obj, const char * name)
{
PyObject * f = PyObject_GetAttrString(obj, name);
float ret = PyFloat_AsDouble(f);
Py_DECREF(f);
return ret;
}
// Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored...
unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
unsigned char * ret = new unsigned char[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i);
Py_DECREF(nao);
return ret;
}
// Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored...
float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
float * ret = new float[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i);
Py_DECREF(nao);
return ret;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import time
class ProgBar:
"""Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops."""
def __init__(self, width = 60, onCallback = None):
self.start = time.time()
self.fill = 0
self.width = width
self.onCallback = onCallback
sys.stdout.write(('_'*self.width)+'\n')
sys.stdout.flush()
def __del__(self):
self.end = time.time()
self.__show(self.width)
sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n')
sys.stdout.flush()
def callback(self, nDone, nToDo):
"""Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo)."""
if self.onCallback:
self.onCallback()
n = int(float(self.width)*float(nDone)/float(nToDo))
n = min((n,self.width))
if n>self.fill:
self.__show(n)
def __show(self,n):
sys.stdout.write('|'*(n-self.fill))
sys.stdout.flush()
self.fill = n
| Python |
# -*- coding: utf-8 -*-
# Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.).
import cv
import numpy as np
def cv2array(im):
"""Converts a cv array to a numpy array."""
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
arrdtype=im.depth
a = np.fromstring(
im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width*im.height*im.nChannels)
a.shape = (im.height,im.width,im.nChannels)
return a
def array2cv(a):
"""Converts a numpy array to a cv array, if possible."""
dtype2depth = {
'uint8': cv.IPL_DEPTH_8U,
'int8': cv.IPL_DEPTH_8S,
'uint16': cv.IPL_DEPTH_16U,
'int16': cv.IPL_DEPTH_16S,
'int32': cv.IPL_DEPTH_32S,
'float32': cv.IPL_DEPTH_32F,
'float64': cv.IPL_DEPTH_64F,
}
try:
nChannels = a.shape[2]
except:
nChannels = 1
cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]),
dtype2depth[str(a.dtype)],
nChannels)
cv.SetData(cv_im, a.tostring(),
a.dtype.itemsize*nChannels*a.shape[1])
return cv_im
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Some basic matrix operations that come in use...
matrix_code = start_cpp() + """
#ifndef MATRIX_CODE
#define MATRIX_CODE
template <typename T>
inline void MemSwap(T * lhs, T * rhs, int count = 1)
{
while(count!=0)
{
T t = *lhs;
*lhs = *rhs;
*rhs = t;
++lhs;
++rhs;
--count;
}
}
// Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default.
template <typename T>
inline T Determinant(T * pos, int size, int stride = -1)
{
if (stride==-1) stride = size;
if (size==1) return pos[0];
else
{
if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride];
else
{
T ret = 0.0;
for (int i=0; i<size; i++)
{
if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1);
T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1];
if ((i+size)%2) ret += sub;
else ret -= sub;
}
for (int i=1; i<size; i++)
{
MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1);
}
return ret;
}
}
}
// Inverts a square matrix, will fail on singular and very occasionally on
// non-singular matrices, returns true on success. Uses Gauss-Jordan elimination
// with partial pivoting.
// in is the input matrix, out the output matrix, just be aware that the input matrix is trashed.
// You have to provide its size (Its square, obviously.), and optionally a stride if different from size.
template <typename T>
inline bool Inverse(T * in, T * out, int size, int stride = -1)
{
if (stride==-1) stride = size;
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
out[r*stride + c] = (c==r)?1.0:0.0;
}
}
for (int r=0; r<size; r++)
{
// Find largest pivot and swap in, fail if best we can get is 0...
T max = in[r*stride + r];
int index = r;
for (int i=r+1; i<size; i++)
{
if (fabs(in[i*stride + r])>fabs(max))
{
max = in[i*stride + r];
index = i;
}
}
if (index!=r)
{
MemSwap(&in[index*stride], &in[r*stride], size);
MemSwap(&out[index*stride], &out[r*stride], size);
}
if (fabs(max-0.0)<1e-6) return false;
// Divide through the entire row...
max = 1.0/max;
in[r*stride + r] = 1.0;
for (int i=r+1; i<size; i++) in[r*stride + i] *= max;
for (int i=0; i<size; i++) out[r*stride + i] *= max;
// Row subtract to generate 0's in the current column, so it matches an identity matrix...
for (int i=0; i<size; i++)
{
if (i==r) continue;
T factor = in[i*stride + r];
in[i*stride + r] = 0.0;
for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j];
for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j];
}
}
return true;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
from utils.numpy_help_cpp import numpy_util_code
# Provides various functions to assist with manipulating python objects from c++ code.
python_obj_code = numpy_util_code + start_cpp() + """
#ifndef PYTHON_OBJ_CODE
#define PYTHON_OBJ_CODE
// Extracts a boolean from an object...
bool GetObjectBoolean(PyObject * obj, const char * name)
{
PyObject * b = PyObject_GetAttrString(obj, name);
bool ret = b!=Py_False;
Py_DECREF(b);
return ret;
}
// Extracts an int from an object...
int GetObjectInt(PyObject * obj, const char * name)
{
PyObject * i = PyObject_GetAttrString(obj, name);
int ret = PyInt_AsLong(i);
Py_DECREF(i);
return ret;
}
// Extracts a float from an object...
float GetObjectFloat(PyObject * obj, const char * name)
{
PyObject * f = PyObject_GetAttrString(obj, name);
float ret = PyFloat_AsDouble(f);
Py_DECREF(f);
return ret;
}
// Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored...
unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
unsigned char * ret = new unsigned char[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i);
Py_DECREF(nao);
return ret;
}
// Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored...
float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
float * ret = new float[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i);
Py_DECREF(nao);
return ret;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import time
class ProgBar:
"""Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops."""
def __init__(self, width = 60, onCallback = None):
self.start = time.time()
self.fill = 0
self.width = width
self.onCallback = onCallback
sys.stdout.write(('_'*self.width)+'\n')
sys.stdout.flush()
def __del__(self):
self.end = time.time()
self.__show(self.width)
sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n')
sys.stdout.flush()
def callback(self, nDone, nToDo):
"""Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo)."""
if self.onCallback:
self.onCallback()
n = int(float(self.width)*float(nDone)/float(nToDo))
n = min((n,self.width))
if n>self.fill:
self.__show(n)
def __show(self,n):
sys.stdout.write('|'*(n-self.fill))
sys.stdout.flush()
self.fill = n
| Python |
# -*- coding: utf-8 -*-
# Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.).
import cv
import numpy as np
def cv2array(im):
"""Converts a cv array to a numpy array."""
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
arrdtype=im.depth
a = np.fromstring(
im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width*im.height*im.nChannels)
a.shape = (im.height,im.width,im.nChannels)
return a
def array2cv(a):
"""Converts a numpy array to a cv array, if possible."""
dtype2depth = {
'uint8': cv.IPL_DEPTH_8U,
'int8': cv.IPL_DEPTH_8S,
'uint16': cv.IPL_DEPTH_16U,
'int16': cv.IPL_DEPTH_16S,
'int32': cv.IPL_DEPTH_32S,
'float32': cv.IPL_DEPTH_32F,
'float64': cv.IPL_DEPTH_64F,
}
try:
nChannels = a.shape[2]
except:
nChannels = 1
cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]),
dtype2depth[str(a.dtype)],
nChannels)
cv.SetData(cv_im, a.tostring(),
a.dtype.itemsize*nChannels*a.shape[1])
return cv_im
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Some basic matrix operations that come in use...
matrix_code = start_cpp() + """
#ifndef MATRIX_CODE
#define MATRIX_CODE
template <typename T>
inline void MemSwap(T * lhs, T * rhs, int count = 1)
{
while(count!=0)
{
T t = *lhs;
*lhs = *rhs;
*rhs = t;
++lhs;
++rhs;
--count;
}
}
// Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default.
template <typename T>
inline T Determinant(T * pos, int size, int stride = -1)
{
if (stride==-1) stride = size;
if (size==1) return pos[0];
else
{
if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride];
else
{
T ret = 0.0;
for (int i=0; i<size; i++)
{
if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1);
T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1];
if ((i+size)%2) ret += sub;
else ret -= sub;
}
for (int i=1; i<size; i++)
{
MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1);
}
return ret;
}
}
}
// Inverts a square matrix, will fail on singular and very occasionally on
// non-singular matrices, returns true on success. Uses Gauss-Jordan elimination
// with partial pivoting.
// in is the input matrix, out the output matrix, just be aware that the input matrix is trashed.
// You have to provide its size (Its square, obviously.), and optionally a stride if different from size.
template <typename T>
inline bool Inverse(T * in, T * out, int size, int stride = -1)
{
if (stride==-1) stride = size;
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
out[r*stride + c] = (c==r)?1.0:0.0;
}
}
for (int r=0; r<size; r++)
{
// Find largest pivot and swap in, fail if best we can get is 0...
T max = in[r*stride + r];
int index = r;
for (int i=r+1; i<size; i++)
{
if (fabs(in[i*stride + r])>fabs(max))
{
max = in[i*stride + r];
index = i;
}
}
if (index!=r)
{
MemSwap(&in[index*stride], &in[r*stride], size);
MemSwap(&out[index*stride], &out[r*stride], size);
}
if (fabs(max-0.0)<1e-6) return false;
// Divide through the entire row...
max = 1.0/max;
in[r*stride + r] = 1.0;
for (int i=r+1; i<size; i++) in[r*stride + i] *= max;
for (int i=0; i<size; i++) out[r*stride + i] *= max;
// Row subtract to generate 0's in the current column, so it matches an identity matrix...
for (int i=0; i<size; i++)
{
if (i==r) continue;
T factor = in[i*stride + r];
in[i*stride + r] = 0.0;
for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j];
for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j];
}
}
return true;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
from utils.numpy_help_cpp import numpy_util_code
# Provides various functions to assist with manipulating python objects from c++ code.
python_obj_code = numpy_util_code + start_cpp() + """
#ifndef PYTHON_OBJ_CODE
#define PYTHON_OBJ_CODE
// Extracts a boolean from an object...
bool GetObjectBoolean(PyObject * obj, const char * name)
{
PyObject * b = PyObject_GetAttrString(obj, name);
bool ret = b!=Py_False;
Py_DECREF(b);
return ret;
}
// Extracts an int from an object...
int GetObjectInt(PyObject * obj, const char * name)
{
PyObject * i = PyObject_GetAttrString(obj, name);
int ret = PyInt_AsLong(i);
Py_DECREF(i);
return ret;
}
// Extracts a float from an object...
float GetObjectFloat(PyObject * obj, const char * name)
{
PyObject * f = PyObject_GetAttrString(obj, name);
float ret = PyFloat_AsDouble(f);
Py_DECREF(f);
return ret;
}
// Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored...
unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
unsigned char * ret = new unsigned char[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i);
Py_DECREF(nao);
return ret;
}
// Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored...
float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
float * ret = new float[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i);
Py_DECREF(nao);
return ret;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import time
class ProgBar:
"""Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops."""
def __init__(self, width = 60, onCallback = None):
self.start = time.time()
self.fill = 0
self.width = width
self.onCallback = onCallback
sys.stdout.write(('_'*self.width)+'\n')
sys.stdout.flush()
def __del__(self):
self.end = time.time()
self.__show(self.width)
sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n')
sys.stdout.flush()
def callback(self, nDone, nToDo):
"""Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo)."""
if self.onCallback:
self.onCallback()
n = int(float(self.width)*float(nDone)/float(nToDo))
n = min((n,self.width))
if n>self.fill:
self.__show(n)
def __show(self,n):
sys.stdout.write('|'*(n-self.fill))
sys.stdout.flush()
self.fill = n
| Python |
# -*- coding: utf-8 -*-
# Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.).
import cv
import numpy as np
def cv2array(im):
"""Converts a cv array to a numpy array."""
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
arrdtype=im.depth
a = np.fromstring(
im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width*im.height*im.nChannels)
a.shape = (im.height,im.width,im.nChannels)
return a
def array2cv(a):
"""Converts a numpy array to a cv array, if possible."""
dtype2depth = {
'uint8': cv.IPL_DEPTH_8U,
'int8': cv.IPL_DEPTH_8S,
'uint16': cv.IPL_DEPTH_16U,
'int16': cv.IPL_DEPTH_16S,
'int32': cv.IPL_DEPTH_32S,
'float32': cv.IPL_DEPTH_32F,
'float64': cv.IPL_DEPTH_64F,
}
try:
nChannels = a.shape[2]
except:
nChannels = 1
cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]),
dtype2depth[str(a.dtype)],
nChannels)
cv.SetData(cv_im, a.tostring(),
a.dtype.itemsize*nChannels*a.shape[1])
return cv_im
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Some basic matrix operations that come in use...
matrix_code = start_cpp() + """
#ifndef MATRIX_CODE
#define MATRIX_CODE
template <typename T>
inline void MemSwap(T * lhs, T * rhs, int count = 1)
{
while(count!=0)
{
T t = *lhs;
*lhs = *rhs;
*rhs = t;
++lhs;
++rhs;
--count;
}
}
// Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default.
template <typename T>
inline T Determinant(T * pos, int size, int stride = -1)
{
if (stride==-1) stride = size;
if (size==1) return pos[0];
else
{
if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride];
else
{
T ret = 0.0;
for (int i=0; i<size; i++)
{
if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1);
T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1];
if ((i+size)%2) ret += sub;
else ret -= sub;
}
for (int i=1; i<size; i++)
{
MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1);
}
return ret;
}
}
}
// Inverts a square matrix, will fail on singular and very occasionally on
// non-singular matrices, returns true on success. Uses Gauss-Jordan elimination
// with partial pivoting.
// in is the input matrix, out the output matrix, just be aware that the input matrix is trashed.
// You have to provide its size (Its square, obviously.), and optionally a stride if different from size.
template <typename T>
inline bool Inverse(T * in, T * out, int size, int stride = -1)
{
if (stride==-1) stride = size;
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
out[r*stride + c] = (c==r)?1.0:0.0;
}
}
for (int r=0; r<size; r++)
{
// Find largest pivot and swap in, fail if best we can get is 0...
T max = in[r*stride + r];
int index = r;
for (int i=r+1; i<size; i++)
{
if (fabs(in[i*stride + r])>fabs(max))
{
max = in[i*stride + r];
index = i;
}
}
if (index!=r)
{
MemSwap(&in[index*stride], &in[r*stride], size);
MemSwap(&out[index*stride], &out[r*stride], size);
}
if (fabs(max-0.0)<1e-6) return false;
// Divide through the entire row...
max = 1.0/max;
in[r*stride + r] = 1.0;
for (int i=r+1; i<size; i++) in[r*stride + i] *= max;
for (int i=0; i<size; i++) out[r*stride + i] *= max;
// Row subtract to generate 0's in the current column, so it matches an identity matrix...
for (int i=0; i<size; i++)
{
if (i==r) continue;
T factor = in[i*stride + r];
in[i*stride + r] = 0.0;
for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j];
for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j];
}
}
return true;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
from utils.numpy_help_cpp import numpy_util_code
# Provides various functions to assist with manipulating python objects from c++ code.
python_obj_code = numpy_util_code + start_cpp() + """
#ifndef PYTHON_OBJ_CODE
#define PYTHON_OBJ_CODE
// Extracts a boolean from an object...
bool GetObjectBoolean(PyObject * obj, const char * name)
{
PyObject * b = PyObject_GetAttrString(obj, name);
bool ret = b!=Py_False;
Py_DECREF(b);
return ret;
}
// Extracts an int from an object...
int GetObjectInt(PyObject * obj, const char * name)
{
PyObject * i = PyObject_GetAttrString(obj, name);
int ret = PyInt_AsLong(i);
Py_DECREF(i);
return ret;
}
// Extracts a float from an object...
float GetObjectFloat(PyObject * obj, const char * name)
{
PyObject * f = PyObject_GetAttrString(obj, name);
float ret = PyFloat_AsDouble(f);
Py_DECREF(f);
return ret;
}
// Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored...
unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
unsigned char * ret = new unsigned char[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i);
Py_DECREF(nao);
return ret;
}
// Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored...
float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
float * ret = new float[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i);
Py_DECREF(nao);
return ret;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import time
class ProgBar:
"""Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops."""
def __init__(self, width = 60, onCallback = None):
self.start = time.time()
self.fill = 0
self.width = width
self.onCallback = onCallback
sys.stdout.write(('_'*self.width)+'\n')
sys.stdout.flush()
def __del__(self):
self.end = time.time()
self.__show(self.width)
sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n')
sys.stdout.flush()
def callback(self, nDone, nToDo):
"""Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo)."""
if self.onCallback:
self.onCallback()
n = int(float(self.width)*float(nDone)/float(nToDo))
n = min((n,self.width))
if n>self.fill:
self.__show(n)
def __show(self,n):
sys.stdout.write('|'*(n-self.fill))
sys.stdout.flush()
self.fill = n
| Python |
# -*- coding: utf-8 -*-
# Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.).
import cv
import numpy as np
def cv2array(im):
"""Converts a cv array to a numpy array."""
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
arrdtype=im.depth
a = np.fromstring(
im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width*im.height*im.nChannels)
a.shape = (im.height,im.width,im.nChannels)
return a
def array2cv(a):
"""Converts a numpy array to a cv array, if possible."""
dtype2depth = {
'uint8': cv.IPL_DEPTH_8U,
'int8': cv.IPL_DEPTH_8S,
'uint16': cv.IPL_DEPTH_16U,
'int16': cv.IPL_DEPTH_16S,
'int32': cv.IPL_DEPTH_32S,
'float32': cv.IPL_DEPTH_32F,
'float64': cv.IPL_DEPTH_64F,
}
try:
nChannels = a.shape[2]
except:
nChannels = 1
cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]),
dtype2depth[str(a.dtype)],
nChannels)
cv.SetData(cv_im, a.tostring(),
a.dtype.itemsize*nChannels*a.shape[1])
return cv_im
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Some basic matrix operations that come in use...
matrix_code = start_cpp() + """
#ifndef MATRIX_CODE
#define MATRIX_CODE
template <typename T>
inline void MemSwap(T * lhs, T * rhs, int count = 1)
{
while(count!=0)
{
T t = *lhs;
*lhs = *rhs;
*rhs = t;
++lhs;
++rhs;
--count;
}
}
// Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default.
template <typename T>
inline T Determinant(T * pos, int size, int stride = -1)
{
if (stride==-1) stride = size;
if (size==1) return pos[0];
else
{
if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride];
else
{
T ret = 0.0;
for (int i=0; i<size; i++)
{
if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1);
T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1];
if ((i+size)%2) ret += sub;
else ret -= sub;
}
for (int i=1; i<size; i++)
{
MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1);
}
return ret;
}
}
}
// Inverts a square matrix, will fail on singular and very occasionally on
// non-singular matrices, returns true on success. Uses Gauss-Jordan elimination
// with partial pivoting.
// in is the input matrix, out the output matrix, just be aware that the input matrix is trashed.
// You have to provide its size (Its square, obviously.), and optionally a stride if different from size.
template <typename T>
inline bool Inverse(T * in, T * out, int size, int stride = -1)
{
if (stride==-1) stride = size;
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
out[r*stride + c] = (c==r)?1.0:0.0;
}
}
for (int r=0; r<size; r++)
{
// Find largest pivot and swap in, fail if best we can get is 0...
T max = in[r*stride + r];
int index = r;
for (int i=r+1; i<size; i++)
{
if (fabs(in[i*stride + r])>fabs(max))
{
max = in[i*stride + r];
index = i;
}
}
if (index!=r)
{
MemSwap(&in[index*stride], &in[r*stride], size);
MemSwap(&out[index*stride], &out[r*stride], size);
}
if (fabs(max-0.0)<1e-6) return false;
// Divide through the entire row...
max = 1.0/max;
in[r*stride + r] = 1.0;
for (int i=r+1; i<size; i++) in[r*stride + i] *= max;
for (int i=0; i<size; i++) out[r*stride + i] *= max;
// Row subtract to generate 0's in the current column, so it matches an identity matrix...
for (int i=0; i<size; i++)
{
if (i==r) continue;
T factor = in[i*stride + r];
in[i*stride + r] = 0.0;
for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j];
for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j];
}
}
return true;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
from utils.numpy_help_cpp import numpy_util_code
# Provides various functions to assist with manipulating python objects from c++ code.
python_obj_code = numpy_util_code + start_cpp() + """
#ifndef PYTHON_OBJ_CODE
#define PYTHON_OBJ_CODE
// Extracts a boolean from an object...
bool GetObjectBoolean(PyObject * obj, const char * name)
{
PyObject * b = PyObject_GetAttrString(obj, name);
bool ret = b!=Py_False;
Py_DECREF(b);
return ret;
}
// Extracts an int from an object...
int GetObjectInt(PyObject * obj, const char * name)
{
PyObject * i = PyObject_GetAttrString(obj, name);
int ret = PyInt_AsLong(i);
Py_DECREF(i);
return ret;
}
// Extracts a float from an object...
float GetObjectFloat(PyObject * obj, const char * name)
{
PyObject * f = PyObject_GetAttrString(obj, name);
float ret = PyFloat_AsDouble(f);
Py_DECREF(f);
return ret;
}
// Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored...
unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
unsigned char * ret = new unsigned char[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i);
Py_DECREF(nao);
return ret;
}
// Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored...
float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
float * ret = new float[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i);
Py_DECREF(nao);
return ret;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import time
class ProgBar:
"""Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops."""
def __init__(self, width = 60, onCallback = None):
self.start = time.time()
self.fill = 0
self.width = width
self.onCallback = onCallback
sys.stdout.write(('_'*self.width)+'\n')
sys.stdout.flush()
def __del__(self):
self.end = time.time()
self.__show(self.width)
sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n')
sys.stdout.flush()
def callback(self, nDone, nToDo):
"""Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo)."""
if self.onCallback:
self.onCallback()
n = int(float(self.width)*float(nDone)/float(nToDo))
n = min((n,self.width))
if n>self.fill:
self.__show(n)
def __show(self,n):
sys.stdout.write('|'*(n-self.fill))
sys.stdout.flush()
self.fill = n
| Python |
# -*- coding: utf-8 -*-
# Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.).
import cv
import numpy as np
def cv2array(im):
"""Converts a cv array to a numpy array."""
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
arrdtype=im.depth
a = np.fromstring(
im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width*im.height*im.nChannels)
a.shape = (im.height,im.width,im.nChannels)
return a
def array2cv(a):
"""Converts a numpy array to a cv array, if possible."""
dtype2depth = {
'uint8': cv.IPL_DEPTH_8U,
'int8': cv.IPL_DEPTH_8S,
'uint16': cv.IPL_DEPTH_16U,
'int16': cv.IPL_DEPTH_16S,
'int32': cv.IPL_DEPTH_32S,
'float32': cv.IPL_DEPTH_32F,
'float64': cv.IPL_DEPTH_64F,
}
try:
nChannels = a.shape[2]
except:
nChannels = 1
cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]),
dtype2depth[str(a.dtype)],
nChannels)
cv.SetData(cv_im, a.tostring(),
a.dtype.itemsize*nChannels*a.shape[1])
return cv_im
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Some basic matrix operations that come in use...
matrix_code = start_cpp() + """
#ifndef MATRIX_CODE
#define MATRIX_CODE
template <typename T>
inline void MemSwap(T * lhs, T * rhs, int count = 1)
{
while(count!=0)
{
T t = *lhs;
*lhs = *rhs;
*rhs = t;
++lhs;
++rhs;
--count;
}
}
// Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default.
template <typename T>
inline T Determinant(T * pos, int size, int stride = -1)
{
if (stride==-1) stride = size;
if (size==1) return pos[0];
else
{
if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride];
else
{
T ret = 0.0;
for (int i=0; i<size; i++)
{
if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1);
T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1];
if ((i+size)%2) ret += sub;
else ret -= sub;
}
for (int i=1; i<size; i++)
{
MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1);
}
return ret;
}
}
}
// Inverts a square matrix, will fail on singular and very occasionally on
// non-singular matrices, returns true on success. Uses Gauss-Jordan elimination
// with partial pivoting.
// in is the input matrix, out the output matrix, just be aware that the input matrix is trashed.
// You have to provide its size (Its square, obviously.), and optionally a stride if different from size.
template <typename T>
inline bool Inverse(T * in, T * out, int size, int stride = -1)
{
if (stride==-1) stride = size;
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
out[r*stride + c] = (c==r)?1.0:0.0;
}
}
for (int r=0; r<size; r++)
{
// Find largest pivot and swap in, fail if best we can get is 0...
T max = in[r*stride + r];
int index = r;
for (int i=r+1; i<size; i++)
{
if (fabs(in[i*stride + r])>fabs(max))
{
max = in[i*stride + r];
index = i;
}
}
if (index!=r)
{
MemSwap(&in[index*stride], &in[r*stride], size);
MemSwap(&out[index*stride], &out[r*stride], size);
}
if (fabs(max-0.0)<1e-6) return false;
// Divide through the entire row...
max = 1.0/max;
in[r*stride + r] = 1.0;
for (int i=r+1; i<size; i++) in[r*stride + i] *= max;
for (int i=0; i<size; i++) out[r*stride + i] *= max;
// Row subtract to generate 0's in the current column, so it matches an identity matrix...
for (int i=0; i<size; i++)
{
if (i==r) continue;
T factor = in[i*stride + r];
in[i*stride + r] = 0.0;
for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j];
for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j];
}
}
return true;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
from utils.numpy_help_cpp import numpy_util_code
# Provides various functions to assist with manipulating python objects from c++ code.
python_obj_code = numpy_util_code + start_cpp() + """
#ifndef PYTHON_OBJ_CODE
#define PYTHON_OBJ_CODE
// Extracts a boolean from an object...
bool GetObjectBoolean(PyObject * obj, const char * name)
{
PyObject * b = PyObject_GetAttrString(obj, name);
bool ret = b!=Py_False;
Py_DECREF(b);
return ret;
}
// Extracts an int from an object...
int GetObjectInt(PyObject * obj, const char * name)
{
PyObject * i = PyObject_GetAttrString(obj, name);
int ret = PyInt_AsLong(i);
Py_DECREF(i);
return ret;
}
// Extracts a float from an object...
float GetObjectFloat(PyObject * obj, const char * name)
{
PyObject * f = PyObject_GetAttrString(obj, name);
float ret = PyFloat_AsDouble(f);
Py_DECREF(f);
return ret;
}
// Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored...
unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
unsigned char * ret = new unsigned char[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i);
Py_DECREF(nao);
return ret;
}
// Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored...
float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
float * ret = new float[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i);
Py_DECREF(nao);
return ret;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import time
class ProgBar:
"""Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops."""
def __init__(self, width = 60, onCallback = None):
self.start = time.time()
self.fill = 0
self.width = width
self.onCallback = onCallback
sys.stdout.write(('_'*self.width)+'\n')
sys.stdout.flush()
def __del__(self):
self.end = time.time()
self.__show(self.width)
sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n')
sys.stdout.flush()
def callback(self, nDone, nToDo):
"""Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo)."""
if self.onCallback:
self.onCallback()
n = int(float(self.width)*float(nDone)/float(nToDo))
n = min((n,self.width))
if n>self.fill:
self.__show(n)
def __show(self,n):
sys.stdout.write('|'*(n-self.fill))
sys.stdout.flush()
self.fill = n
| Python |
# -*- coding: utf-8 -*-
# Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.).
import cv
import numpy as np
def cv2array(im):
"""Converts a cv array to a numpy array."""
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
arrdtype=im.depth
a = np.fromstring(
im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width*im.height*im.nChannels)
a.shape = (im.height,im.width,im.nChannels)
return a
def array2cv(a):
"""Converts a numpy array to a cv array, if possible."""
dtype2depth = {
'uint8': cv.IPL_DEPTH_8U,
'int8': cv.IPL_DEPTH_8S,
'uint16': cv.IPL_DEPTH_16U,
'int16': cv.IPL_DEPTH_16S,
'int32': cv.IPL_DEPTH_32S,
'float32': cv.IPL_DEPTH_32F,
'float64': cv.IPL_DEPTH_64F,
}
try:
nChannels = a.shape[2]
except:
nChannels = 1
cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]),
dtype2depth[str(a.dtype)],
nChannels)
cv.SetData(cv_im, a.tostring(),
a.dtype.itemsize*nChannels*a.shape[1])
return cv_im
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Some basic matrix operations that come in use...
matrix_code = start_cpp() + """
#ifndef MATRIX_CODE
#define MATRIX_CODE
template <typename T>
inline void MemSwap(T * lhs, T * rhs, int count = 1)
{
while(count!=0)
{
T t = *lhs;
*lhs = *rhs;
*rhs = t;
++lhs;
++rhs;
--count;
}
}
// Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default.
template <typename T>
inline T Determinant(T * pos, int size, int stride = -1)
{
if (stride==-1) stride = size;
if (size==1) return pos[0];
else
{
if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride];
else
{
T ret = 0.0;
for (int i=0; i<size; i++)
{
if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1);
T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1];
if ((i+size)%2) ret += sub;
else ret -= sub;
}
for (int i=1; i<size; i++)
{
MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1);
}
return ret;
}
}
}
// Inverts a square matrix, will fail on singular and very occasionally on
// non-singular matrices, returns true on success. Uses Gauss-Jordan elimination
// with partial pivoting.
// in is the input matrix, out the output matrix, just be aware that the input matrix is trashed.
// You have to provide its size (Its square, obviously.), and optionally a stride if different from size.
template <typename T>
inline bool Inverse(T * in, T * out, int size, int stride = -1)
{
if (stride==-1) stride = size;
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
out[r*stride + c] = (c==r)?1.0:0.0;
}
}
for (int r=0; r<size; r++)
{
// Find largest pivot and swap in, fail if best we can get is 0...
T max = in[r*stride + r];
int index = r;
for (int i=r+1; i<size; i++)
{
if (fabs(in[i*stride + r])>fabs(max))
{
max = in[i*stride + r];
index = i;
}
}
if (index!=r)
{
MemSwap(&in[index*stride], &in[r*stride], size);
MemSwap(&out[index*stride], &out[r*stride], size);
}
if (fabs(max-0.0)<1e-6) return false;
// Divide through the entire row...
max = 1.0/max;
in[r*stride + r] = 1.0;
for (int i=r+1; i<size; i++) in[r*stride + i] *= max;
for (int i=0; i<size; i++) out[r*stride + i] *= max;
// Row subtract to generate 0's in the current column, so it matches an identity matrix...
for (int i=0; i<size; i++)
{
if (i==r) continue;
T factor = in[i*stride + r];
in[i*stride + r] = 0.0;
for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j];
for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j];
}
}
return true;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
from utils.numpy_help_cpp import numpy_util_code
# Provides various functions to assist with manipulating python objects from c++ code.
python_obj_code = numpy_util_code + start_cpp() + """
#ifndef PYTHON_OBJ_CODE
#define PYTHON_OBJ_CODE
// Extracts a boolean from an object...
bool GetObjectBoolean(PyObject * obj, const char * name)
{
PyObject * b = PyObject_GetAttrString(obj, name);
bool ret = b!=Py_False;
Py_DECREF(b);
return ret;
}
// Extracts an int from an object...
int GetObjectInt(PyObject * obj, const char * name)
{
PyObject * i = PyObject_GetAttrString(obj, name);
int ret = PyInt_AsLong(i);
Py_DECREF(i);
return ret;
}
// Extracts a float from an object...
float GetObjectFloat(PyObject * obj, const char * name)
{
PyObject * f = PyObject_GetAttrString(obj, name);
float ret = PyFloat_AsDouble(f);
Py_DECREF(f);
return ret;
}
// Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored...
unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
unsigned char * ret = new unsigned char[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i);
Py_DECREF(nao);
return ret;
}
// Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored...
float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
float * ret = new float[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i);
Py_DECREF(nao);
return ret;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import time
class ProgBar:
"""Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops."""
def __init__(self, width = 60, onCallback = None):
self.start = time.time()
self.fill = 0
self.width = width
self.onCallback = onCallback
sys.stdout.write(('_'*self.width)+'\n')
sys.stdout.flush()
def __del__(self):
self.end = time.time()
self.__show(self.width)
sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n')
sys.stdout.flush()
def callback(self, nDone, nToDo):
"""Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo)."""
if self.onCallback:
self.onCallback()
n = int(float(self.width)*float(nDone)/float(nToDo))
n = min((n,self.width))
if n>self.fill:
self.__show(n)
def __show(self,n):
sys.stdout.write('|'*(n-self.fill))
sys.stdout.flush()
self.fill = n
| Python |
# -*- coding: utf-8 -*-
# Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.).
import cv
import numpy as np
def cv2array(im):
"""Converts a cv array to a numpy array."""
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
arrdtype=im.depth
a = np.fromstring(
im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width*im.height*im.nChannels)
a.shape = (im.height,im.width,im.nChannels)
return a
def array2cv(a):
"""Converts a numpy array to a cv array, if possible."""
dtype2depth = {
'uint8': cv.IPL_DEPTH_8U,
'int8': cv.IPL_DEPTH_8S,
'uint16': cv.IPL_DEPTH_16U,
'int16': cv.IPL_DEPTH_16S,
'int32': cv.IPL_DEPTH_32S,
'float32': cv.IPL_DEPTH_32F,
'float64': cv.IPL_DEPTH_64F,
}
try:
nChannels = a.shape[2]
except:
nChannels = 1
cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]),
dtype2depth[str(a.dtype)],
nChannels)
cv.SetData(cv_im, a.tostring(),
a.dtype.itemsize*nChannels*a.shape[1])
return cv_im
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Some basic matrix operations that come in use...
matrix_code = start_cpp() + """
#ifndef MATRIX_CODE
#define MATRIX_CODE
template <typename T>
inline void MemSwap(T * lhs, T * rhs, int count = 1)
{
while(count!=0)
{
T t = *lhs;
*lhs = *rhs;
*rhs = t;
++lhs;
++rhs;
--count;
}
}
// Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default.
template <typename T>
inline T Determinant(T * pos, int size, int stride = -1)
{
if (stride==-1) stride = size;
if (size==1) return pos[0];
else
{
if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride];
else
{
T ret = 0.0;
for (int i=0; i<size; i++)
{
if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1);
T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1];
if ((i+size)%2) ret += sub;
else ret -= sub;
}
for (int i=1; i<size; i++)
{
MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1);
}
return ret;
}
}
}
// Inverts a square matrix, will fail on singular and very occasionally on
// non-singular matrices, returns true on success. Uses Gauss-Jordan elimination
// with partial pivoting.
// in is the input matrix, out the output matrix, just be aware that the input matrix is trashed.
// You have to provide its size (Its square, obviously.), and optionally a stride if different from size.
template <typename T>
inline bool Inverse(T * in, T * out, int size, int stride = -1)
{
if (stride==-1) stride = size;
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
out[r*stride + c] = (c==r)?1.0:0.0;
}
}
for (int r=0; r<size; r++)
{
// Find largest pivot and swap in, fail if best we can get is 0...
T max = in[r*stride + r];
int index = r;
for (int i=r+1; i<size; i++)
{
if (fabs(in[i*stride + r])>fabs(max))
{
max = in[i*stride + r];
index = i;
}
}
if (index!=r)
{
MemSwap(&in[index*stride], &in[r*stride], size);
MemSwap(&out[index*stride], &out[r*stride], size);
}
if (fabs(max-0.0)<1e-6) return false;
// Divide through the entire row...
max = 1.0/max;
in[r*stride + r] = 1.0;
for (int i=r+1; i<size; i++) in[r*stride + i] *= max;
for (int i=0; i<size; i++) out[r*stride + i] *= max;
// Row subtract to generate 0's in the current column, so it matches an identity matrix...
for (int i=0; i<size; i++)
{
if (i==r) continue;
T factor = in[i*stride + r];
in[i*stride + r] = 0.0;
for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j];
for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j];
}
}
return true;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
from utils.numpy_help_cpp import numpy_util_code
# Provides various functions to assist with manipulating python objects from c++ code.
python_obj_code = numpy_util_code + start_cpp() + """
#ifndef PYTHON_OBJ_CODE
#define PYTHON_OBJ_CODE
// Extracts a boolean from an object...
bool GetObjectBoolean(PyObject * obj, const char * name)
{
PyObject * b = PyObject_GetAttrString(obj, name);
bool ret = b!=Py_False;
Py_DECREF(b);
return ret;
}
// Extracts an int from an object...
int GetObjectInt(PyObject * obj, const char * name)
{
PyObject * i = PyObject_GetAttrString(obj, name);
int ret = PyInt_AsLong(i);
Py_DECREF(i);
return ret;
}
// Extracts a float from an object...
float GetObjectFloat(PyObject * obj, const char * name)
{
PyObject * f = PyObject_GetAttrString(obj, name);
float ret = PyFloat_AsDouble(f);
Py_DECREF(f);
return ret;
}
// Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored...
unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
unsigned char * ret = new unsigned char[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i);
Py_DECREF(nao);
return ret;
}
// Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored...
float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
float * ret = new float[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i);
Py_DECREF(nao);
return ret;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import time
class ProgBar:
"""Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops."""
def __init__(self, width = 60, onCallback = None):
self.start = time.time()
self.fill = 0
self.width = width
self.onCallback = onCallback
sys.stdout.write(('_'*self.width)+'\n')
sys.stdout.flush()
def __del__(self):
self.end = time.time()
self.__show(self.width)
sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n')
sys.stdout.flush()
def callback(self, nDone, nToDo):
"""Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo)."""
if self.onCallback:
self.onCallback()
n = int(float(self.width)*float(nDone)/float(nToDo))
n = min((n,self.width))
if n>self.fill:
self.__show(n)
def __show(self,n):
sys.stdout.write('|'*(n-self.fill))
sys.stdout.flush()
self.fill = n
| Python |
# -*- coding: utf-8 -*-
# Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.).
import cv
import numpy as np
def cv2array(im):
"""Converts a cv array to a numpy array."""
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
arrdtype=im.depth
a = np.fromstring(
im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width*im.height*im.nChannels)
a.shape = (im.height,im.width,im.nChannels)
return a
def array2cv(a):
"""Converts a numpy array to a cv array, if possible."""
dtype2depth = {
'uint8': cv.IPL_DEPTH_8U,
'int8': cv.IPL_DEPTH_8S,
'uint16': cv.IPL_DEPTH_16U,
'int16': cv.IPL_DEPTH_16S,
'int32': cv.IPL_DEPTH_32S,
'float32': cv.IPL_DEPTH_32F,
'float64': cv.IPL_DEPTH_64F,
}
try:
nChannels = a.shape[2]
except:
nChannels = 1
cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]),
dtype2depth[str(a.dtype)],
nChannels)
cv.SetData(cv_im, a.tostring(),
a.dtype.itemsize*nChannels*a.shape[1])
return cv_im
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Some basic matrix operations that come in use...
matrix_code = start_cpp() + """
#ifndef MATRIX_CODE
#define MATRIX_CODE
template <typename T>
inline void MemSwap(T * lhs, T * rhs, int count = 1)
{
while(count!=0)
{
T t = *lhs;
*lhs = *rhs;
*rhs = t;
++lhs;
++rhs;
--count;
}
}
// Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default.
template <typename T>
inline T Determinant(T * pos, int size, int stride = -1)
{
if (stride==-1) stride = size;
if (size==1) return pos[0];
else
{
if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride];
else
{
T ret = 0.0;
for (int i=0; i<size; i++)
{
if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1);
T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1];
if ((i+size)%2) ret += sub;
else ret -= sub;
}
for (int i=1; i<size; i++)
{
MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1);
}
return ret;
}
}
}
// Inverts a square matrix, will fail on singular and very occasionally on
// non-singular matrices, returns true on success. Uses Gauss-Jordan elimination
// with partial pivoting.
// in is the input matrix, out the output matrix, just be aware that the input matrix is trashed.
// You have to provide its size (Its square, obviously.), and optionally a stride if different from size.
template <typename T>
inline bool Inverse(T * in, T * out, int size, int stride = -1)
{
if (stride==-1) stride = size;
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
out[r*stride + c] = (c==r)?1.0:0.0;
}
}
for (int r=0; r<size; r++)
{
// Find largest pivot and swap in, fail if best we can get is 0...
T max = in[r*stride + r];
int index = r;
for (int i=r+1; i<size; i++)
{
if (fabs(in[i*stride + r])>fabs(max))
{
max = in[i*stride + r];
index = i;
}
}
if (index!=r)
{
MemSwap(&in[index*stride], &in[r*stride], size);
MemSwap(&out[index*stride], &out[r*stride], size);
}
if (fabs(max-0.0)<1e-6) return false;
// Divide through the entire row...
max = 1.0/max;
in[r*stride + r] = 1.0;
for (int i=r+1; i<size; i++) in[r*stride + i] *= max;
for (int i=0; i<size; i++) out[r*stride + i] *= max;
// Row subtract to generate 0's in the current column, so it matches an identity matrix...
for (int i=0; i<size; i++)
{
if (i==r) continue;
T factor = in[i*stride + r];
in[i*stride + r] = 0.0;
for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j];
for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j];
}
}
return true;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
from utils.numpy_help_cpp import numpy_util_code
# Provides various functions to assist with manipulating python objects from c++ code.
python_obj_code = numpy_util_code + start_cpp() + """
#ifndef PYTHON_OBJ_CODE
#define PYTHON_OBJ_CODE
// Extracts a boolean from an object...
bool GetObjectBoolean(PyObject * obj, const char * name)
{
PyObject * b = PyObject_GetAttrString(obj, name);
bool ret = b!=Py_False;
Py_DECREF(b);
return ret;
}
// Extracts an int from an object...
int GetObjectInt(PyObject * obj, const char * name)
{
PyObject * i = PyObject_GetAttrString(obj, name);
int ret = PyInt_AsLong(i);
Py_DECREF(i);
return ret;
}
// Extracts a float from an object...
float GetObjectFloat(PyObject * obj, const char * name)
{
PyObject * f = PyObject_GetAttrString(obj, name);
float ret = PyFloat_AsDouble(f);
Py_DECREF(f);
return ret;
}
// Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored...
unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
unsigned char * ret = new unsigned char[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i);
Py_DECREF(nao);
return ret;
}
// Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored...
float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
float * ret = new float[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i);
Py_DECREF(nao);
return ret;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import time
class ProgBar:
"""Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops."""
def __init__(self, width = 60, onCallback = None):
self.start = time.time()
self.fill = 0
self.width = width
self.onCallback = onCallback
sys.stdout.write(('_'*self.width)+'\n')
sys.stdout.flush()
def __del__(self):
self.end = time.time()
self.__show(self.width)
sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n')
sys.stdout.flush()
def callback(self, nDone, nToDo):
"""Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo)."""
if self.onCallback:
self.onCallback()
n = int(float(self.width)*float(nDone)/float(nToDo))
n = min((n,self.width))
if n>self.fill:
self.__show(n)
def __show(self,n):
sys.stdout.write('|'*(n-self.fill))
sys.stdout.flush()
self.fill = n
| Python |
# -*- coding: utf-8 -*-
# Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.).
import cv
import numpy as np
def cv2array(im):
"""Converts a cv array to a numpy array."""
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
arrdtype=im.depth
a = np.fromstring(
im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width*im.height*im.nChannels)
a.shape = (im.height,im.width,im.nChannels)
return a
def array2cv(a):
"""Converts a numpy array to a cv array, if possible."""
dtype2depth = {
'uint8': cv.IPL_DEPTH_8U,
'int8': cv.IPL_DEPTH_8S,
'uint16': cv.IPL_DEPTH_16U,
'int16': cv.IPL_DEPTH_16S,
'int32': cv.IPL_DEPTH_32S,
'float32': cv.IPL_DEPTH_32F,
'float64': cv.IPL_DEPTH_64F,
}
try:
nChannels = a.shape[2]
except:
nChannels = 1
cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]),
dtype2depth[str(a.dtype)],
nChannels)
cv.SetData(cv_im, a.tostring(),
a.dtype.itemsize*nChannels*a.shape[1])
return cv_im
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Some basic matrix operations that come in use...
matrix_code = start_cpp() + """
#ifndef MATRIX_CODE
#define MATRIX_CODE
template <typename T>
inline void MemSwap(T * lhs, T * rhs, int count = 1)
{
while(count!=0)
{
T t = *lhs;
*lhs = *rhs;
*rhs = t;
++lhs;
++rhs;
--count;
}
}
// Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default.
template <typename T>
inline T Determinant(T * pos, int size, int stride = -1)
{
if (stride==-1) stride = size;
if (size==1) return pos[0];
else
{
if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride];
else
{
T ret = 0.0;
for (int i=0; i<size; i++)
{
if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1);
T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1];
if ((i+size)%2) ret += sub;
else ret -= sub;
}
for (int i=1; i<size; i++)
{
MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1);
}
return ret;
}
}
}
// Inverts a square matrix, will fail on singular and very occasionally on
// non-singular matrices, returns true on success. Uses Gauss-Jordan elimination
// with partial pivoting.
// in is the input matrix, out the output matrix, just be aware that the input matrix is trashed.
// You have to provide its size (Its square, obviously.), and optionally a stride if different from size.
template <typename T>
inline bool Inverse(T * in, T * out, int size, int stride = -1)
{
if (stride==-1) stride = size;
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
out[r*stride + c] = (c==r)?1.0:0.0;
}
}
for (int r=0; r<size; r++)
{
// Find largest pivot and swap in, fail if best we can get is 0...
T max = in[r*stride + r];
int index = r;
for (int i=r+1; i<size; i++)
{
if (fabs(in[i*stride + r])>fabs(max))
{
max = in[i*stride + r];
index = i;
}
}
if (index!=r)
{
MemSwap(&in[index*stride], &in[r*stride], size);
MemSwap(&out[index*stride], &out[r*stride], size);
}
if (fabs(max-0.0)<1e-6) return false;
// Divide through the entire row...
max = 1.0/max;
in[r*stride + r] = 1.0;
for (int i=r+1; i<size; i++) in[r*stride + i] *= max;
for (int i=0; i<size; i++) out[r*stride + i] *= max;
// Row subtract to generate 0's in the current column, so it matches an identity matrix...
for (int i=0; i<size; i++)
{
if (i==r) continue;
T factor = in[i*stride + r];
in[i*stride + r] = 0.0;
for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j];
for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j];
}
}
return true;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
from utils.numpy_help_cpp import numpy_util_code
# Provides various functions to assist with manipulating python objects from c++ code.
python_obj_code = numpy_util_code + start_cpp() + """
#ifndef PYTHON_OBJ_CODE
#define PYTHON_OBJ_CODE
// Extracts a boolean from an object...
bool GetObjectBoolean(PyObject * obj, const char * name)
{
PyObject * b = PyObject_GetAttrString(obj, name);
bool ret = b!=Py_False;
Py_DECREF(b);
return ret;
}
// Extracts an int from an object...
int GetObjectInt(PyObject * obj, const char * name)
{
PyObject * i = PyObject_GetAttrString(obj, name);
int ret = PyInt_AsLong(i);
Py_DECREF(i);
return ret;
}
// Extracts a float from an object...
float GetObjectFloat(PyObject * obj, const char * name)
{
PyObject * f = PyObject_GetAttrString(obj, name);
float ret = PyFloat_AsDouble(f);
Py_DECREF(f);
return ret;
}
// Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored...
unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
unsigned char * ret = new unsigned char[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i);
Py_DECREF(nao);
return ret;
}
// Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored...
float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
float * ret = new float[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i);
Py_DECREF(nao);
return ret;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import time
class ProgBar:
"""Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops."""
def __init__(self, width = 60, onCallback = None):
self.start = time.time()
self.fill = 0
self.width = width
self.onCallback = onCallback
sys.stdout.write(('_'*self.width)+'\n')
sys.stdout.flush()
def __del__(self):
self.end = time.time()
self.__show(self.width)
sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n')
sys.stdout.flush()
def callback(self, nDone, nToDo):
"""Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo)."""
if self.onCallback:
self.onCallback()
n = int(float(self.width)*float(nDone)/float(nToDo))
n = min((n,self.width))
if n>self.fill:
self.__show(n)
def __show(self,n):
sys.stdout.write('|'*(n-self.fill))
sys.stdout.flush()
self.fill = n
| Python |
# -*- coding: utf-8 -*-
# Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.).
import cv
import numpy as np
def cv2array(im):
"""Converts a cv array to a numpy array."""
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
arrdtype=im.depth
a = np.fromstring(
im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width*im.height*im.nChannels)
a.shape = (im.height,im.width,im.nChannels)
return a
def array2cv(a):
"""Converts a numpy array to a cv array, if possible."""
dtype2depth = {
'uint8': cv.IPL_DEPTH_8U,
'int8': cv.IPL_DEPTH_8S,
'uint16': cv.IPL_DEPTH_16U,
'int16': cv.IPL_DEPTH_16S,
'int32': cv.IPL_DEPTH_32S,
'float32': cv.IPL_DEPTH_32F,
'float64': cv.IPL_DEPTH_64F,
}
try:
nChannels = a.shape[2]
except:
nChannels = 1
cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]),
dtype2depth[str(a.dtype)],
nChannels)
cv.SetData(cv_im, a.tostring(),
a.dtype.itemsize*nChannels*a.shape[1])
return cv_im
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Some basic matrix operations that come in use...
matrix_code = start_cpp() + """
#ifndef MATRIX_CODE
#define MATRIX_CODE
template <typename T>
inline void MemSwap(T * lhs, T * rhs, int count = 1)
{
while(count!=0)
{
T t = *lhs;
*lhs = *rhs;
*rhs = t;
++lhs;
++rhs;
--count;
}
}
// Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default.
template <typename T>
inline T Determinant(T * pos, int size, int stride = -1)
{
if (stride==-1) stride = size;
if (size==1) return pos[0];
else
{
if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride];
else
{
T ret = 0.0;
for (int i=0; i<size; i++)
{
if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1);
T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1];
if ((i+size)%2) ret += sub;
else ret -= sub;
}
for (int i=1; i<size; i++)
{
MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1);
}
return ret;
}
}
}
// Inverts a square matrix, will fail on singular and very occasionally on
// non-singular matrices, returns true on success. Uses Gauss-Jordan elimination
// with partial pivoting.
// in is the input matrix, out the output matrix, just be aware that the input matrix is trashed.
// You have to provide its size (Its square, obviously.), and optionally a stride if different from size.
template <typename T>
inline bool Inverse(T * in, T * out, int size, int stride = -1)
{
if (stride==-1) stride = size;
for (int r=0; r<size; r++)
{
for (int c=0; c<size; c++)
{
out[r*stride + c] = (c==r)?1.0:0.0;
}
}
for (int r=0; r<size; r++)
{
// Find largest pivot and swap in, fail if best we can get is 0...
T max = in[r*stride + r];
int index = r;
for (int i=r+1; i<size; i++)
{
if (fabs(in[i*stride + r])>fabs(max))
{
max = in[i*stride + r];
index = i;
}
}
if (index!=r)
{
MemSwap(&in[index*stride], &in[r*stride], size);
MemSwap(&out[index*stride], &out[r*stride], size);
}
if (fabs(max-0.0)<1e-6) return false;
// Divide through the entire row...
max = 1.0/max;
in[r*stride + r] = 1.0;
for (int i=r+1; i<size; i++) in[r*stride + i] *= max;
for (int i=0; i<size; i++) out[r*stride + i] *= max;
// Row subtract to generate 0's in the current column, so it matches an identity matrix...
for (int i=0; i<size; i++)
{
if (i==r) continue;
T factor = in[i*stride + r];
in[i*stride + r] = 0.0;
for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j];
for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j];
}
}
return true;
}
#endif
"""
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
from utils.numpy_help_cpp import numpy_util_code
# Provides various functions to assist with manipulating python objects from c++ code.
python_obj_code = numpy_util_code + start_cpp() + """
#ifndef PYTHON_OBJ_CODE
#define PYTHON_OBJ_CODE
// Extracts a boolean from an object...
bool GetObjectBoolean(PyObject * obj, const char * name)
{
PyObject * b = PyObject_GetAttrString(obj, name);
bool ret = b!=Py_False;
Py_DECREF(b);
return ret;
}
// Extracts an int from an object...
int GetObjectInt(PyObject * obj, const char * name)
{
PyObject * i = PyObject_GetAttrString(obj, name);
int ret = PyInt_AsLong(i);
Py_DECREF(i);
return ret;
}
// Extracts a float from an object...
float GetObjectFloat(PyObject * obj, const char * name)
{
PyObject * f = PyObject_GetAttrString(obj, name);
float ret = PyFloat_AsDouble(f);
Py_DECREF(f);
return ret;
}
// Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored...
unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
unsigned char * ret = new unsigned char[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i);
Py_DECREF(nao);
return ret;
}
// Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored...
float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0)
{
PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name);
float * ret = new float[nao->dimensions[0]];
if (size) *size = nao->dimensions[0];
for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i);
Py_DECREF(nao);
return ret;
}
#endif
"""
| Python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import cvarray
import mp_map
import prog_bar
import numpy_help_cpp
import python_obj_cpp
import matrix_cpp
import gamma_cpp
import setProcName
import start_cpp
import make
import doc_gen
# Setup...
doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.')
doc.addFile('readme.txt', 'Overview')
# Variables...
doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.')
doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.')
doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++')
doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++')
# Functions...
doc.addFunction(make.make_mod)
doc.addFunction(cvarray.cv2array)
doc.addFunction(cvarray.array2cv)
doc.addFunction(mp_map.repeat)
doc.addFunction(mp_map.mp_map)
doc.addFunction(setProcName.setProcName)
doc.addFunction(start_cpp.start_cpp)
doc.addFunction(make.make_mod)
# Classes...
doc.addClass(prog_bar.ProgBar)
doc.addClass(doc_gen.DocGen)
| Python |
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest
import random
import math
from scipy.special import gammaln, psi, polygamma
from scipy import weave
from utils.start_cpp import start_cpp
# Provides various gamma-related functions...
gamma_code = start_cpp() + """
#ifndef GAMMA_CODE
#define GAMMA_CODE
#include <cmath>
// Returns the natural logarithm of the Gamma function...
// (Uses Lanczos's approximation.)
double lnGamma(double z)
{
static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};
if (z<0.5)
{
// Use reflection formula, as approximation doesn't work down here...
return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z);
}
else
{
double x = coeff[0];
for (int i=1;i<9;i++) x += coeff[i]/(z+i-1);
double t = z + 6.5;
return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x);
}
}
// Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values...
double digamma(double z)
{
static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point.
double ret = 0.0;
while (z<highVal)
{
ret -= 1.0/z;
z += 1.0;
}
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz4 = iz2*iz2;
double iz6 = iz4*iz2;
ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0;
return ret;
}
// Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically...
double trigamma(double z)
{
static const double highVal = 8.0;
double ret = 0.0;
while (z<highVal)
{
ret += 1.0/(z*z);
z += 1.0;
}
z -= 1.0;
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz3 = iz1*iz2;
double iz5 = iz3*iz2;
double iz7 = iz5*iz2;
double iz9 = iz7*iz2;
ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0;
return ret;
}
#endif
"""
def lnGamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function"""
code = start_cpp(gamma_code) + """
return_val = lnGamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def digamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function"""
code = start_cpp(gamma_code) + """
return_val = digamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def trigamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function"""
code = start_cpp(gamma_code) + """
return_val = trigamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
class TestFuncs(unittest.TestCase):
"""Test code for the assorted gamma-related functions."""
def test_compile(self):
code = start_cpp(gamma_code) + """
"""
weave.inline(code, support_code=gamma_code)
def test_error_lngamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = lnGamma(z)
good = gammaln(z)
assert(math.fabs(own-good)<1e-12)
def test_error_digamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = digamma(z)
good = psi(z)
assert(math.fabs(own-good)<1e-9)
def test_error_trigamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = trigamma(z)
good = polygamma(1,z)
assert(math.fabs(own-good)<1e-9)
# If this file is run do the unit tests...
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import inspect
import hashlib
def start_cpp(hash_str = None):
"""This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>"""
frame = inspect.currentframe().f_back
info = inspect.getframeinfo(frame)
if hash_str==None:
return '#line %i "%s"\n'%(info[1],info[0])
else:
h = hashlib.md5()
h.update(hash_str)
hash_val = h.hexdigest()
return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os.path
import tempfile
import shutil
from distutils.core import setup, Extension
import distutils.ccompiler
import distutils.dep_util
try:
__default_compiler = distutils.ccompiler.new_compiler()
except:
__default_compiler = None
def make_mod(name, base, source, openCL = False):
"""Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place."""
if __default_compiler==None: raise Exception('No compiler!')
# Work out the various file names - check if we actually need to do anything...
if not isinstance(source, list): source = [source]
source_path = map(lambda s: os.path.join(base, s), source)
library_path = os.path.join(base, __default_compiler.shared_object_filename(name))
if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)):
try:
print 'b'
# Backup the argv variable and create a temporary directory to do all work in...
old_argv = sys.argv[:]
temp_dir = tempfile.mkdtemp()
# Prepare the extension...
sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir]
comp_path = filter(lambda s: not s.endswith('.h'), source_path)
depends = filter(lambda s: s.endswith('.h'), source_path)
if openCL:
ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends)
else:
ext = Extension(name, comp_path, depends=depends)
# Compile...
setup(name=name, version='1.0.0', ext_modules=[ext])
finally:
# Cleanup the argv variable and the temporary directory...
sys.argv = old_argv
shutil.rmtree(temp_dir, True)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| Python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from ctypes import *
def setProcName(name):
"""Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases."""
# Call the process control function...
libc = cdll.LoadLibrary('libc.so.6')
libc.prctl(15, c_char_p(name), 0, 0, 0)
# Update argv...
charPP = POINTER(POINTER(c_char))
argv = charPP.in_dll(libc,'_dl_argv')
size = libc.strlen(argv[0])
libc.strncpy(argv[0],c_char_p(name),size)
if __name__=='__main__':
# Quick test that it works...
import os
ps1 = 'ps'
ps2 = 'ps -f'
os.system(ps1)
os.system(ps2)
setProcName('wibble_wobble')
os.system(ps1)
os.system(ps2)
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import multiprocessing as mp
import multiprocessing.synchronize # To make sure we have all the functionality.
import types
import marshal
import unittest
def repeat(x):
"""A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant."""
while True: yield x
def run_code(code,args):
"""Internal use function that does the work in each process."""
code = marshal.loads(code)
func = types.FunctionType(code, globals(), '_')
return func(*args)
def mp_map(func, *iters, **keywords):
"""A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity."""
if 'pool' in keywords: pool = keywords['pool']
else: pool = mp.Pool()
code = marshal.dumps(func.func_code)
jobs = []
for args in zip(*iters):
jobs.append(pool.apply_async(run_code,(code,args)))
for i in xrange(len(jobs)):
jobs[i] = jobs[i].get()
return jobs
class TestMpMap(unittest.TestCase):
def test_simple1(self):
data = ['a','b','c','d']
def noop(data):
return data
data_noop = mp_map(noop, data)
self.assertEqual(data, data_noop)
def test_simple2(self):
data = [x for x in xrange(1000)]
data_double = mp_map(lambda a: a*2, data)
self.assertEqual(map(lambda a: a*2,data), data_double)
def test_gen(self):
def gen():
for i in xrange(100): yield i
data_double = mp_map(lambda a: a*2, gen())
self.assertEqual(map(lambda a: a*2,gen()), data_double)
def test_repeat(self):
def mult(a,b):
return a*b
data = [x for x in xrange(50,5000,5)]
data_triple = mp_map(mult, data, repeat(3))
self.assertEqual(map(lambda a: a*3,data),data_triple)
def test_none(self):
data = []
data_sqr = mp_map(lambda x: x*x, data)
self.assertEqual([],data_sqr)
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Defines helper functions for accessing numpy arrays...
numpy_util_code = start_cpp() + """
#ifndef NUMPY_UTIL_CODE
#define NUMPY_UTIL_CODE
float & Float1D(PyArrayObject * arr, int index = 0)
{
return *(float*)(arr->data + index*arr->strides[0]);
}
float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
unsigned char & Byte1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index*arr->strides[0]);
}
unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
int & Int1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index*arr->strides[0]);
}
int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
#endif
"""
| Python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import cvarray
import mp_map
import prog_bar
import numpy_help_cpp
import python_obj_cpp
import matrix_cpp
import gamma_cpp
import setProcName
import start_cpp
import make
import doc_gen
# Setup...
doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.')
doc.addFile('readme.txt', 'Overview')
# Variables...
doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.')
doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.')
doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++')
doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++')
# Functions...
doc.addFunction(make.make_mod)
doc.addFunction(cvarray.cv2array)
doc.addFunction(cvarray.array2cv)
doc.addFunction(mp_map.repeat)
doc.addFunction(mp_map.mp_map)
doc.addFunction(setProcName.setProcName)
doc.addFunction(start_cpp.start_cpp)
doc.addFunction(make.make_mod)
# Classes...
doc.addClass(prog_bar.ProgBar)
doc.addClass(doc_gen.DocGen)
| Python |
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest
import random
import math
from scipy.special import gammaln, psi, polygamma
from scipy import weave
from utils.start_cpp import start_cpp
# Provides various gamma-related functions...
gamma_code = start_cpp() + """
#ifndef GAMMA_CODE
#define GAMMA_CODE
#include <cmath>
// Returns the natural logarithm of the Gamma function...
// (Uses Lanczos's approximation.)
double lnGamma(double z)
{
static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};
if (z<0.5)
{
// Use reflection formula, as approximation doesn't work down here...
return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z);
}
else
{
double x = coeff[0];
for (int i=1;i<9;i++) x += coeff[i]/(z+i-1);
double t = z + 6.5;
return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x);
}
}
// Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values...
double digamma(double z)
{
static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point.
double ret = 0.0;
while (z<highVal)
{
ret -= 1.0/z;
z += 1.0;
}
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz4 = iz2*iz2;
double iz6 = iz4*iz2;
ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0;
return ret;
}
// Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically...
double trigamma(double z)
{
static const double highVal = 8.0;
double ret = 0.0;
while (z<highVal)
{
ret += 1.0/(z*z);
z += 1.0;
}
z -= 1.0;
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz3 = iz1*iz2;
double iz5 = iz3*iz2;
double iz7 = iz5*iz2;
double iz9 = iz7*iz2;
ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0;
return ret;
}
#endif
"""
def lnGamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function"""
code = start_cpp(gamma_code) + """
return_val = lnGamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def digamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function"""
code = start_cpp(gamma_code) + """
return_val = digamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def trigamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function"""
code = start_cpp(gamma_code) + """
return_val = trigamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
class TestFuncs(unittest.TestCase):
"""Test code for the assorted gamma-related functions."""
def test_compile(self):
code = start_cpp(gamma_code) + """
"""
weave.inline(code, support_code=gamma_code)
def test_error_lngamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = lnGamma(z)
good = gammaln(z)
assert(math.fabs(own-good)<1e-12)
def test_error_digamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = digamma(z)
good = psi(z)
assert(math.fabs(own-good)<1e-9)
def test_error_trigamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = trigamma(z)
good = polygamma(1,z)
assert(math.fabs(own-good)<1e-9)
# If this file is run do the unit tests...
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import inspect
import hashlib
def start_cpp(hash_str = None):
"""This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>"""
frame = inspect.currentframe().f_back
info = inspect.getframeinfo(frame)
if hash_str==None:
return '#line %i "%s"\n'%(info[1],info[0])
else:
h = hashlib.md5()
h.update(hash_str)
hash_val = h.hexdigest()
return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os.path
import tempfile
import shutil
from distutils.core import setup, Extension
import distutils.ccompiler
import distutils.dep_util
try:
__default_compiler = distutils.ccompiler.new_compiler()
except:
__default_compiler = None
def make_mod(name, base, source, openCL = False):
"""Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place."""
if __default_compiler==None: raise Exception('No compiler!')
# Work out the various file names - check if we actually need to do anything...
if not isinstance(source, list): source = [source]
source_path = map(lambda s: os.path.join(base, s), source)
library_path = os.path.join(base, __default_compiler.shared_object_filename(name))
if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)):
try:
print 'b'
# Backup the argv variable and create a temporary directory to do all work in...
old_argv = sys.argv[:]
temp_dir = tempfile.mkdtemp()
# Prepare the extension...
sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir]
comp_path = filter(lambda s: not s.endswith('.h'), source_path)
depends = filter(lambda s: s.endswith('.h'), source_path)
if openCL:
ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends)
else:
ext = Extension(name, comp_path, depends=depends)
# Compile...
setup(name=name, version='1.0.0', ext_modules=[ext])
finally:
# Cleanup the argv variable and the temporary directory...
sys.argv = old_argv
shutil.rmtree(temp_dir, True)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| Python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from ctypes import *
def setProcName(name):
"""Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases."""
# Call the process control function...
libc = cdll.LoadLibrary('libc.so.6')
libc.prctl(15, c_char_p(name), 0, 0, 0)
# Update argv...
charPP = POINTER(POINTER(c_char))
argv = charPP.in_dll(libc,'_dl_argv')
size = libc.strlen(argv[0])
libc.strncpy(argv[0],c_char_p(name),size)
if __name__=='__main__':
# Quick test that it works...
import os
ps1 = 'ps'
ps2 = 'ps -f'
os.system(ps1)
os.system(ps2)
setProcName('wibble_wobble')
os.system(ps1)
os.system(ps2)
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import multiprocessing as mp
import multiprocessing.synchronize # To make sure we have all the functionality.
import types
import marshal
import unittest
def repeat(x):
"""A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant."""
while True: yield x
def run_code(code,args):
"""Internal use function that does the work in each process."""
code = marshal.loads(code)
func = types.FunctionType(code, globals(), '_')
return func(*args)
def mp_map(func, *iters, **keywords):
"""A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity."""
if 'pool' in keywords: pool = keywords['pool']
else: pool = mp.Pool()
code = marshal.dumps(func.func_code)
jobs = []
for args in zip(*iters):
jobs.append(pool.apply_async(run_code,(code,args)))
for i in xrange(len(jobs)):
jobs[i] = jobs[i].get()
return jobs
class TestMpMap(unittest.TestCase):
def test_simple1(self):
data = ['a','b','c','d']
def noop(data):
return data
data_noop = mp_map(noop, data)
self.assertEqual(data, data_noop)
def test_simple2(self):
data = [x for x in xrange(1000)]
data_double = mp_map(lambda a: a*2, data)
self.assertEqual(map(lambda a: a*2,data), data_double)
def test_gen(self):
def gen():
for i in xrange(100): yield i
data_double = mp_map(lambda a: a*2, gen())
self.assertEqual(map(lambda a: a*2,gen()), data_double)
def test_repeat(self):
def mult(a,b):
return a*b
data = [x for x in xrange(50,5000,5)]
data_triple = mp_map(mult, data, repeat(3))
self.assertEqual(map(lambda a: a*3,data),data_triple)
def test_none(self):
data = []
data_sqr = mp_map(lambda x: x*x, data)
self.assertEqual([],data_sqr)
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Defines helper functions for accessing numpy arrays...
numpy_util_code = start_cpp() + """
#ifndef NUMPY_UTIL_CODE
#define NUMPY_UTIL_CODE
float & Float1D(PyArrayObject * arr, int index = 0)
{
return *(float*)(arr->data + index*arr->strides[0]);
}
float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
unsigned char & Byte1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index*arr->strides[0]);
}
unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
int & Int1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index*arr->strides[0]);
}
int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
#endif
"""
| Python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import cvarray
import mp_map
import prog_bar
import numpy_help_cpp
import python_obj_cpp
import matrix_cpp
import gamma_cpp
import setProcName
import start_cpp
import make
import doc_gen
# Setup...
doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.')
doc.addFile('readme.txt', 'Overview')
# Variables...
doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.')
doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.')
doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++')
doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++')
# Functions...
doc.addFunction(make.make_mod)
doc.addFunction(cvarray.cv2array)
doc.addFunction(cvarray.array2cv)
doc.addFunction(mp_map.repeat)
doc.addFunction(mp_map.mp_map)
doc.addFunction(setProcName.setProcName)
doc.addFunction(start_cpp.start_cpp)
doc.addFunction(make.make_mod)
# Classes...
doc.addClass(prog_bar.ProgBar)
doc.addClass(doc_gen.DocGen)
| Python |
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest
import random
import math
from scipy.special import gammaln, psi, polygamma
from scipy import weave
from utils.start_cpp import start_cpp
# Provides various gamma-related functions...
gamma_code = start_cpp() + """
#ifndef GAMMA_CODE
#define GAMMA_CODE
#include <cmath>
// Returns the natural logarithm of the Gamma function...
// (Uses Lanczos's approximation.)
double lnGamma(double z)
{
static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};
if (z<0.5)
{
// Use reflection formula, as approximation doesn't work down here...
return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z);
}
else
{
double x = coeff[0];
for (int i=1;i<9;i++) x += coeff[i]/(z+i-1);
double t = z + 6.5;
return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x);
}
}
// Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values...
double digamma(double z)
{
static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point.
double ret = 0.0;
while (z<highVal)
{
ret -= 1.0/z;
z += 1.0;
}
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz4 = iz2*iz2;
double iz6 = iz4*iz2;
ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0;
return ret;
}
// Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically...
double trigamma(double z)
{
static const double highVal = 8.0;
double ret = 0.0;
while (z<highVal)
{
ret += 1.0/(z*z);
z += 1.0;
}
z -= 1.0;
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz3 = iz1*iz2;
double iz5 = iz3*iz2;
double iz7 = iz5*iz2;
double iz9 = iz7*iz2;
ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0;
return ret;
}
#endif
"""
def lnGamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function"""
code = start_cpp(gamma_code) + """
return_val = lnGamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def digamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function"""
code = start_cpp(gamma_code) + """
return_val = digamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def trigamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function"""
code = start_cpp(gamma_code) + """
return_val = trigamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
class TestFuncs(unittest.TestCase):
"""Test code for the assorted gamma-related functions."""
def test_compile(self):
code = start_cpp(gamma_code) + """
"""
weave.inline(code, support_code=gamma_code)
def test_error_lngamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = lnGamma(z)
good = gammaln(z)
assert(math.fabs(own-good)<1e-12)
def test_error_digamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = digamma(z)
good = psi(z)
assert(math.fabs(own-good)<1e-9)
def test_error_trigamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = trigamma(z)
good = polygamma(1,z)
assert(math.fabs(own-good)<1e-9)
# If this file is run do the unit tests...
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import inspect
import hashlib
def start_cpp(hash_str = None):
"""This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>"""
frame = inspect.currentframe().f_back
info = inspect.getframeinfo(frame)
if hash_str==None:
return '#line %i "%s"\n'%(info[1],info[0])
else:
h = hashlib.md5()
h.update(hash_str)
hash_val = h.hexdigest()
return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os.path
import tempfile
import shutil
from distutils.core import setup, Extension
import distutils.ccompiler
import distutils.dep_util
try:
__default_compiler = distutils.ccompiler.new_compiler()
except:
__default_compiler = None
def make_mod(name, base, source, openCL = False):
"""Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place."""
if __default_compiler==None: raise Exception('No compiler!')
# Work out the various file names - check if we actually need to do anything...
if not isinstance(source, list): source = [source]
source_path = map(lambda s: os.path.join(base, s), source)
library_path = os.path.join(base, __default_compiler.shared_object_filename(name))
if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)):
try:
print 'b'
# Backup the argv variable and create a temporary directory to do all work in...
old_argv = sys.argv[:]
temp_dir = tempfile.mkdtemp()
# Prepare the extension...
sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir]
comp_path = filter(lambda s: not s.endswith('.h'), source_path)
depends = filter(lambda s: s.endswith('.h'), source_path)
if openCL:
ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends)
else:
ext = Extension(name, comp_path, depends=depends)
# Compile...
setup(name=name, version='1.0.0', ext_modules=[ext])
finally:
# Cleanup the argv variable and the temporary directory...
sys.argv = old_argv
shutil.rmtree(temp_dir, True)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| Python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from ctypes import *
def setProcName(name):
"""Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases."""
# Call the process control function...
libc = cdll.LoadLibrary('libc.so.6')
libc.prctl(15, c_char_p(name), 0, 0, 0)
# Update argv...
charPP = POINTER(POINTER(c_char))
argv = charPP.in_dll(libc,'_dl_argv')
size = libc.strlen(argv[0])
libc.strncpy(argv[0],c_char_p(name),size)
if __name__=='__main__':
# Quick test that it works...
import os
ps1 = 'ps'
ps2 = 'ps -f'
os.system(ps1)
os.system(ps2)
setProcName('wibble_wobble')
os.system(ps1)
os.system(ps2)
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import multiprocessing as mp
import multiprocessing.synchronize # To make sure we have all the functionality.
import types
import marshal
import unittest
def repeat(x):
"""A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant."""
while True: yield x
def run_code(code,args):
"""Internal use function that does the work in each process."""
code = marshal.loads(code)
func = types.FunctionType(code, globals(), '_')
return func(*args)
def mp_map(func, *iters, **keywords):
"""A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity."""
if 'pool' in keywords: pool = keywords['pool']
else: pool = mp.Pool()
code = marshal.dumps(func.func_code)
jobs = []
for args in zip(*iters):
jobs.append(pool.apply_async(run_code,(code,args)))
for i in xrange(len(jobs)):
jobs[i] = jobs[i].get()
return jobs
class TestMpMap(unittest.TestCase):
def test_simple1(self):
data = ['a','b','c','d']
def noop(data):
return data
data_noop = mp_map(noop, data)
self.assertEqual(data, data_noop)
def test_simple2(self):
data = [x for x in xrange(1000)]
data_double = mp_map(lambda a: a*2, data)
self.assertEqual(map(lambda a: a*2,data), data_double)
def test_gen(self):
def gen():
for i in xrange(100): yield i
data_double = mp_map(lambda a: a*2, gen())
self.assertEqual(map(lambda a: a*2,gen()), data_double)
def test_repeat(self):
def mult(a,b):
return a*b
data = [x for x in xrange(50,5000,5)]
data_triple = mp_map(mult, data, repeat(3))
self.assertEqual(map(lambda a: a*3,data),data_triple)
def test_none(self):
data = []
data_sqr = mp_map(lambda x: x*x, data)
self.assertEqual([],data_sqr)
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Defines helper functions for accessing numpy arrays...
numpy_util_code = start_cpp() + """
#ifndef NUMPY_UTIL_CODE
#define NUMPY_UTIL_CODE
float & Float1D(PyArrayObject * arr, int index = 0)
{
return *(float*)(arr->data + index*arr->strides[0]);
}
float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
unsigned char & Byte1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index*arr->strides[0]);
}
unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
int & Int1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index*arr->strides[0]);
}
int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
#endif
"""
| Python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import cvarray
import mp_map
import prog_bar
import numpy_help_cpp
import python_obj_cpp
import matrix_cpp
import gamma_cpp
import setProcName
import start_cpp
import make
import doc_gen
# Setup...
doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.')
doc.addFile('readme.txt', 'Overview')
# Variables...
doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.')
doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.')
doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++')
doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++')
# Functions...
doc.addFunction(make.make_mod)
doc.addFunction(cvarray.cv2array)
doc.addFunction(cvarray.array2cv)
doc.addFunction(mp_map.repeat)
doc.addFunction(mp_map.mp_map)
doc.addFunction(setProcName.setProcName)
doc.addFunction(start_cpp.start_cpp)
doc.addFunction(make.make_mod)
# Classes...
doc.addClass(prog_bar.ProgBar)
doc.addClass(doc_gen.DocGen)
| Python |
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest
import random
import math
from scipy.special import gammaln, psi, polygamma
from scipy import weave
from utils.start_cpp import start_cpp
# Provides various gamma-related functions...
gamma_code = start_cpp() + """
#ifndef GAMMA_CODE
#define GAMMA_CODE
#include <cmath>
// Returns the natural logarithm of the Gamma function...
// (Uses Lanczos's approximation.)
double lnGamma(double z)
{
static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};
if (z<0.5)
{
// Use reflection formula, as approximation doesn't work down here...
return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z);
}
else
{
double x = coeff[0];
for (int i=1;i<9;i++) x += coeff[i]/(z+i-1);
double t = z + 6.5;
return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x);
}
}
// Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values...
double digamma(double z)
{
static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point.
double ret = 0.0;
while (z<highVal)
{
ret -= 1.0/z;
z += 1.0;
}
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz4 = iz2*iz2;
double iz6 = iz4*iz2;
ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0;
return ret;
}
// Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically...
double trigamma(double z)
{
static const double highVal = 8.0;
double ret = 0.0;
while (z<highVal)
{
ret += 1.0/(z*z);
z += 1.0;
}
z -= 1.0;
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz3 = iz1*iz2;
double iz5 = iz3*iz2;
double iz7 = iz5*iz2;
double iz9 = iz7*iz2;
ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0;
return ret;
}
#endif
"""
def lnGamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function"""
code = start_cpp(gamma_code) + """
return_val = lnGamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def digamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function"""
code = start_cpp(gamma_code) + """
return_val = digamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def trigamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function"""
code = start_cpp(gamma_code) + """
return_val = trigamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
class TestFuncs(unittest.TestCase):
"""Test code for the assorted gamma-related functions."""
def test_compile(self):
code = start_cpp(gamma_code) + """
"""
weave.inline(code, support_code=gamma_code)
def test_error_lngamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = lnGamma(z)
good = gammaln(z)
assert(math.fabs(own-good)<1e-12)
def test_error_digamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = digamma(z)
good = psi(z)
assert(math.fabs(own-good)<1e-9)
def test_error_trigamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = trigamma(z)
good = polygamma(1,z)
assert(math.fabs(own-good)<1e-9)
# If this file is run do the unit tests...
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import inspect
import hashlib
def start_cpp(hash_str = None):
"""This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>"""
frame = inspect.currentframe().f_back
info = inspect.getframeinfo(frame)
if hash_str==None:
return '#line %i "%s"\n'%(info[1],info[0])
else:
h = hashlib.md5()
h.update(hash_str)
hash_val = h.hexdigest()
return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os.path
import tempfile
import shutil
from distutils.core import setup, Extension
import distutils.ccompiler
import distutils.dep_util
try:
__default_compiler = distutils.ccompiler.new_compiler()
except:
__default_compiler = None
def make_mod(name, base, source, openCL = False):
"""Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place."""
if __default_compiler==None: raise Exception('No compiler!')
# Work out the various file names - check if we actually need to do anything...
if not isinstance(source, list): source = [source]
source_path = map(lambda s: os.path.join(base, s), source)
library_path = os.path.join(base, __default_compiler.shared_object_filename(name))
if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)):
try:
print 'b'
# Backup the argv variable and create a temporary directory to do all work in...
old_argv = sys.argv[:]
temp_dir = tempfile.mkdtemp()
# Prepare the extension...
sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir]
comp_path = filter(lambda s: not s.endswith('.h'), source_path)
depends = filter(lambda s: s.endswith('.h'), source_path)
if openCL:
ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends)
else:
ext = Extension(name, comp_path, depends=depends)
# Compile...
setup(name=name, version='1.0.0', ext_modules=[ext])
finally:
# Cleanup the argv variable and the temporary directory...
sys.argv = old_argv
shutil.rmtree(temp_dir, True)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| Python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from ctypes import *
def setProcName(name):
"""Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases."""
# Call the process control function...
libc = cdll.LoadLibrary('libc.so.6')
libc.prctl(15, c_char_p(name), 0, 0, 0)
# Update argv...
charPP = POINTER(POINTER(c_char))
argv = charPP.in_dll(libc,'_dl_argv')
size = libc.strlen(argv[0])
libc.strncpy(argv[0],c_char_p(name),size)
if __name__=='__main__':
# Quick test that it works...
import os
ps1 = 'ps'
ps2 = 'ps -f'
os.system(ps1)
os.system(ps2)
setProcName('wibble_wobble')
os.system(ps1)
os.system(ps2)
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import multiprocessing as mp
import multiprocessing.synchronize # To make sure we have all the functionality.
import types
import marshal
import unittest
def repeat(x):
"""A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant."""
while True: yield x
def run_code(code,args):
"""Internal use function that does the work in each process."""
code = marshal.loads(code)
func = types.FunctionType(code, globals(), '_')
return func(*args)
def mp_map(func, *iters, **keywords):
"""A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity."""
if 'pool' in keywords: pool = keywords['pool']
else: pool = mp.Pool()
code = marshal.dumps(func.func_code)
jobs = []
for args in zip(*iters):
jobs.append(pool.apply_async(run_code,(code,args)))
for i in xrange(len(jobs)):
jobs[i] = jobs[i].get()
return jobs
class TestMpMap(unittest.TestCase):
def test_simple1(self):
data = ['a','b','c','d']
def noop(data):
return data
data_noop = mp_map(noop, data)
self.assertEqual(data, data_noop)
def test_simple2(self):
data = [x for x in xrange(1000)]
data_double = mp_map(lambda a: a*2, data)
self.assertEqual(map(lambda a: a*2,data), data_double)
def test_gen(self):
def gen():
for i in xrange(100): yield i
data_double = mp_map(lambda a: a*2, gen())
self.assertEqual(map(lambda a: a*2,gen()), data_double)
def test_repeat(self):
def mult(a,b):
return a*b
data = [x for x in xrange(50,5000,5)]
data_triple = mp_map(mult, data, repeat(3))
self.assertEqual(map(lambda a: a*3,data),data_triple)
def test_none(self):
data = []
data_sqr = mp_map(lambda x: x*x, data)
self.assertEqual([],data_sqr)
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Defines helper functions for accessing numpy arrays...
numpy_util_code = start_cpp() + """
#ifndef NUMPY_UTIL_CODE
#define NUMPY_UTIL_CODE
float & Float1D(PyArrayObject * arr, int index = 0)
{
return *(float*)(arr->data + index*arr->strides[0]);
}
float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
unsigned char & Byte1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index*arr->strides[0]);
}
unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
int & Int1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index*arr->strides[0]);
}
int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
#endif
"""
| Python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import cvarray
import mp_map
import prog_bar
import numpy_help_cpp
import python_obj_cpp
import matrix_cpp
import gamma_cpp
import setProcName
import start_cpp
import make
import doc_gen
# Setup...
doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.')
doc.addFile('readme.txt', 'Overview')
# Variables...
doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.')
doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.')
doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++')
doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++')
# Functions...
doc.addFunction(make.make_mod)
doc.addFunction(cvarray.cv2array)
doc.addFunction(cvarray.array2cv)
doc.addFunction(mp_map.repeat)
doc.addFunction(mp_map.mp_map)
doc.addFunction(setProcName.setProcName)
doc.addFunction(start_cpp.start_cpp)
doc.addFunction(make.make_mod)
# Classes...
doc.addClass(prog_bar.ProgBar)
doc.addClass(doc_gen.DocGen)
| Python |
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest
import random
import math
from scipy.special import gammaln, psi, polygamma
from scipy import weave
from utils.start_cpp import start_cpp
# Provides various gamma-related functions...
gamma_code = start_cpp() + """
#ifndef GAMMA_CODE
#define GAMMA_CODE
#include <cmath>
// Returns the natural logarithm of the Gamma function...
// (Uses Lanczos's approximation.)
double lnGamma(double z)
{
static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};
if (z<0.5)
{
// Use reflection formula, as approximation doesn't work down here...
return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z);
}
else
{
double x = coeff[0];
for (int i=1;i<9;i++) x += coeff[i]/(z+i-1);
double t = z + 6.5;
return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x);
}
}
// Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values...
double digamma(double z)
{
static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point.
double ret = 0.0;
while (z<highVal)
{
ret -= 1.0/z;
z += 1.0;
}
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz4 = iz2*iz2;
double iz6 = iz4*iz2;
ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0;
return ret;
}
// Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically...
double trigamma(double z)
{
static const double highVal = 8.0;
double ret = 0.0;
while (z<highVal)
{
ret += 1.0/(z*z);
z += 1.0;
}
z -= 1.0;
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz3 = iz1*iz2;
double iz5 = iz3*iz2;
double iz7 = iz5*iz2;
double iz9 = iz7*iz2;
ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0;
return ret;
}
#endif
"""
def lnGamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function"""
code = start_cpp(gamma_code) + """
return_val = lnGamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def digamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function"""
code = start_cpp(gamma_code) + """
return_val = digamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def trigamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function"""
code = start_cpp(gamma_code) + """
return_val = trigamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
class TestFuncs(unittest.TestCase):
"""Test code for the assorted gamma-related functions."""
def test_compile(self):
code = start_cpp(gamma_code) + """
"""
weave.inline(code, support_code=gamma_code)
def test_error_lngamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = lnGamma(z)
good = gammaln(z)
assert(math.fabs(own-good)<1e-12)
def test_error_digamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = digamma(z)
good = psi(z)
assert(math.fabs(own-good)<1e-9)
def test_error_trigamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = trigamma(z)
good = polygamma(1,z)
assert(math.fabs(own-good)<1e-9)
# If this file is run do the unit tests...
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import inspect
import hashlib
def start_cpp(hash_str = None):
"""This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>"""
frame = inspect.currentframe().f_back
info = inspect.getframeinfo(frame)
if hash_str==None:
return '#line %i "%s"\n'%(info[1],info[0])
else:
h = hashlib.md5()
h.update(hash_str)
hash_val = h.hexdigest()
return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os.path
import tempfile
import shutil
from distutils.core import setup, Extension
import distutils.ccompiler
import distutils.dep_util
try:
__default_compiler = distutils.ccompiler.new_compiler()
except:
__default_compiler = None
def make_mod(name, base, source, openCL = False):
"""Uses distutils to compile a python module - really just a set of hacks to allow this to be done 'on demand', so it only compiles if the module does not exist or is older than the current source, and after compilation the program can continue on its merry way, and immediatly import the just compiled module. Note that on failure erros can be thrown - its your choice to catch them or not. name is the modules name, i.e. what you want to use with the import statement. base is the base directory for the module, which contains the source file - often you would want to set this to 'os.path.dirname(__file__)', assuming the .py file that imports the module is in the same directory as the code. It is this directory that the module is output to. source is the filename of the source code to compile, or alternativly a list of filenames. openCL indicates if OpenCL is used by the module, in which case it does all the necesary setup - done like this so these setting can be kept centralised, so when they need to be different for a new platform they only have to be changed in one place."""
if __default_compiler==None: raise Exception('No compiler!')
# Work out the various file names - check if we actually need to do anything...
if not isinstance(source, list): source = [source]
source_path = map(lambda s: os.path.join(base, s), source)
library_path = os.path.join(base, __default_compiler.shared_object_filename(name))
if reduce(lambda a,b: a or b, map(lambda s: distutils.dep_util.newer(s, library_path), source_path)):
try:
print 'b'
# Backup the argv variable and create a temporary directory to do all work in...
old_argv = sys.argv[:]
temp_dir = tempfile.mkdtemp()
# Prepare the extension...
sys.argv = ['','build_ext','--build-lib', base, '--build-temp', temp_dir]
comp_path = filter(lambda s: not s.endswith('.h'), source_path)
depends = filter(lambda s: s.endswith('.h'), source_path)
if openCL:
ext = Extension(name, comp_path, include_dirs=['/usr/local/cuda/include', '/opt/AMDAPP/include'], libraries = ['OpenCL'], library_dirs = ['/usr/lib64/nvidia', '/opt/AMDAPP/lib/x86_64'], depends=depends)
else:
ext = Extension(name, comp_path, depends=depends)
# Compile...
setup(name=name, version='1.0.0', ext_modules=[ext])
finally:
# Cleanup the argv variable and the temporary directory...
sys.argv = old_argv
shutil.rmtree(temp_dir, True)
| Python |
# Copyright (c) 2012, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import pydoc
import inspect
class DocGen:
"""A helper class that is used to generate documentation for the system. Outputs multiple formats simultaneously, specifically html for local reading with a webbrowser and the markup used by the wiki system on Google code."""
def __init__(self, name, title = None, summary = None):
"""name is the module name - primarilly used for the file names. title is the title used as applicable - if not provide it just uses the name. summary is an optional line to go below the title."""
if title==None: title = name
if summary==None: summary = title
self.doc = pydoc.HTMLDoc()
self.html = open('%s.html'%name,'w')
self.html.write('<html>\n')
self.html.write('<head>\n')
self.html.write('<title>%s</title>\n'%title)
self.html.write('</head>\n')
self.html.write('<body>\n')
self.html_variables = ''
self.html_functions = ''
self.html_classes = ''
self.wiki = open('%s.wiki'%name,'w')
self.wiki.write('#summary %s\n\n'%summary)
self.wiki.write('= %s= \n\n'%title)
self.wiki_variables = ''
self.wiki_functions = ''
self.wiki_classes = ''
def __del__(self):
if self.html_variables!='':
self.html.write(self.doc.bigsection('Synonyms', '#ffffff', '#8d50ff', self.html_variables))
if self.html_functions!='':
self.html.write(self.doc.bigsection('Functions', '#ffffff', '#eeaa77', self.html_functions))
if self.html_classes!='':
self.html.write(self.doc.bigsection('Classes', '#ffffff', '#ee77aa', self.html_classes))
self.html.write('</body>\n')
self.html.write('</html>\n')
self.html.close()
if self.wiki_variables!='':
self.wiki.write('= Variables =\n\n')
self.wiki.write(self.wiki_variables)
self.wiki.write('\n')
if self.wiki_functions!='':
self.wiki.write('= Functions =\n\n')
self.wiki.write(self.wiki_functions)
self.wiki.write('\n')
if self.wiki_classes!='':
self.wiki.write('= Classes =\n\n')
self.wiki.write(self.wiki_classes)
self.wiki.write('\n')
self.wiki.close()
def addFile(self, fn, title, fls = True):
"""Given a filename and section title adds the contents of said file to the output. Various flags influence how this works."""
html = []
wiki = []
for i, line in enumerate(open(fn,'r').readlines()):
hl = line.replace('\n', '')
if i==0 and fls:
hl = '<strong>' + hl + '</strong>'
for ext in ['py','txt']:
if '.%s - '%ext in hl:
s = hl.split('.%s - '%ext, 1)
hl = '<i>' + s[0] + '.%s</i> - '%ext + s[1]
html.append(hl)
wl = line.strip()
if i==0 and fls:
wl = '*%s*'%wl
for ext in ['py','txt']:
if '.%s - '%ext in wl:
s = wl.split('.%s - '%ext, 1)
wl = '`' + s[0] + '.%s` - '%ext + s[1] + '\n'
wiki.append(wl)
self.html.write(self.doc.bigsection(title, '#ffffff', '#7799ee', '<br/>'.join(html)))
self.wiki.write('== %s ==\n'%title)
self.wiki.write('\n'.join(wiki))
self.wiki.write('----\n\n')
def addVariable(self, var, desc):
"""Adds a variable to the documentation. Given the nature of this you provide it as a pair of strings - one referencing the variable, the other some kind of description of its use etc.."""
self.html_variables += '<strong>%s</strong><br/>'%var
self.html_variables += '%s<br/><br/>\n'%desc
self.wiki_variables += '*`%s`*\n'%var
self.wiki_variables += ' %s\n\n'%desc
def addFunction(self, func):
"""Adds a function to the documentation. You provide the actual function instance."""
self.html_functions += self.doc.docroutine(func).replace(' ',' ')
self.html_functions += '\n'
name = func.__name__
args, varargs, keywords, defaults = inspect.getargspec(func)
doc = inspect.getdoc(func)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
self.wiki_functions += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_functions += ' %s\n\n'%doc
def addClass(self, cls):
"""Adds a class to the documentation. You provide the actual class object."""
self.html_classes += self.doc.docclass(cls).replace(' ',' ')
self.html_classes += '\n'
name = cls.__name__
parents = filter(lambda a: a!=cls, inspect.getmro(cls))
doc = inspect.getdoc(cls)
par_str = ''
if len(parents)!=0:
par_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda p: p.__name__, parents))
self.wiki_classes += '== %s(%s) ==\n'%(name, par_str)
self.wiki_classes += ' %s\n\n'%doc
methods = inspect.getmembers(cls, inspect.ismethod)
def method_key(pair):
if pair[0]=='__init__': return '___'
else: return pair[0]
methods.sort(key=method_key)
for name, method in methods:
if not name.startswith('_%s'%cls.__name__):
args, varargs, keywords, defaults = inspect.getargspec(method)
if defaults==None: defaults = list()
defaults = (len(args)-len(defaults)) * [None] + list(defaults)
arg_str = ''
if len(args)!=0:
arg_str += reduce(lambda a, b: '%s, %s'%(a,b), map(lambda arg, d: arg if d==None else '%s = %s'%(arg,d), args, defaults))
if varargs!=None:
arg_str += ', *%s'%varargs if arg_str!='' else '*%s'%varargs
if keywords!=None:
arg_str += ', **%s'%keywords if arg_str!='' else '**%s'%keywords
def fetch_doc(cls, name):
try:
method = getattr(cls, name)
if method.__doc__!=None: return inspect.getdoc(method)
except: pass
for parent in filter(lambda a: a!=cls, inspect.getmro(cls)):
ret = fetch_doc(parent, name)
if ret!=None: return ret
return None
doc = fetch_doc(cls, name)
self.wiki_classes += '*`%s(%s)`*\n'%(name, arg_str)
self.wiki_classes += ' %s\n\n'%doc
variables = inspect.getmembers(cls, lambda x: isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
self.wiki_classes += '*`%s`* = %s\n\n'%(name, str(var))
| Python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from ctypes import *
def setProcName(name):
"""Sets the process name, linux only - useful for those programs where you might want to do a killall, but don't want to slaughter all the other python processes. Note that there are multiple mechanisms, and that the given new name can be shortened by differing amounts in differing cases."""
# Call the process control function...
libc = cdll.LoadLibrary('libc.so.6')
libc.prctl(15, c_char_p(name), 0, 0, 0)
# Update argv...
charPP = POINTER(POINTER(c_char))
argv = charPP.in_dll(libc,'_dl_argv')
size = libc.strlen(argv[0])
libc.strncpy(argv[0],c_char_p(name),size)
if __name__=='__main__':
# Quick test that it works...
import os
ps1 = 'ps'
ps2 = 'ps -f'
os.system(ps1)
os.system(ps2)
setProcName('wibble_wobble')
os.system(ps1)
os.system(ps2)
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import multiprocessing as mp
import multiprocessing.synchronize # To make sure we have all the functionality.
import types
import marshal
import unittest
def repeat(x):
"""A generator that repeats the input forever - can be used with the mp_map function to give data to a function that is constant."""
while True: yield x
def run_code(code,args):
"""Internal use function that does the work in each process."""
code = marshal.loads(code)
func = types.FunctionType(code, globals(), '_')
return func(*args)
def mp_map(func, *iters, **keywords):
"""A multiprocess version of the map function. Note that func must limit itself to the data provided - if it accesses anything else (globals, locals to its definition.) it will fail. There is a repeat generator provided in this module to work around such issues. Note that, unlike map, this iterates the length of the shortest of inputs, rather than the longest - whilst this makes it not a perfect substitute it makes passing constant argumenmts easier as they can just repeat for infinity."""
if 'pool' in keywords: pool = keywords['pool']
else: pool = mp.Pool()
code = marshal.dumps(func.func_code)
jobs = []
for args in zip(*iters):
jobs.append(pool.apply_async(run_code,(code,args)))
for i in xrange(len(jobs)):
jobs[i] = jobs[i].get()
return jobs
class TestMpMap(unittest.TestCase):
def test_simple1(self):
data = ['a','b','c','d']
def noop(data):
return data
data_noop = mp_map(noop, data)
self.assertEqual(data, data_noop)
def test_simple2(self):
data = [x for x in xrange(1000)]
data_double = mp_map(lambda a: a*2, data)
self.assertEqual(map(lambda a: a*2,data), data_double)
def test_gen(self):
def gen():
for i in xrange(100): yield i
data_double = mp_map(lambda a: a*2, gen())
self.assertEqual(map(lambda a: a*2,gen()), data_double)
def test_repeat(self):
def mult(a,b):
return a*b
data = [x for x in xrange(50,5000,5)]
data_triple = mp_map(mult, data, repeat(3))
self.assertEqual(map(lambda a: a*3,data),data_triple)
def test_none(self):
data = []
data_sqr = mp_map(lambda x: x*x, data)
self.assertEqual([],data_sqr)
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from utils.start_cpp import start_cpp
# Defines helper functions for accessing numpy arrays...
numpy_util_code = start_cpp() + """
#ifndef NUMPY_UTIL_CODE
#define NUMPY_UTIL_CODE
float & Float1D(PyArrayObject * arr, int index = 0)
{
return *(float*)(arr->data + index*arr->strides[0]);
}
float & Float2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
float & Float3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
return *(float*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
unsigned char & Byte1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index*arr->strides[0]);
}
unsigned char & Byte2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
unsigned char & Byte3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(unsigned char));
return *(unsigned char*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
int & Int1D(PyArrayObject * arr, int index = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index*arr->strides[0]);
}
int & Int2D(PyArrayObject * arr, int index1 = 0, int index2 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1]);
}
int & Int3D(PyArrayObject * arr, int index1 = 0, int index2 = 0, int index3 = 0)
{
//assert(arr->strides[0]==sizeof(int));
return *(int*)(arr->data + index1*arr->strides[0] + index2*arr->strides[1] + index3*arr->strides[2]);
}
#endif
"""
| Python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import cvarray
import mp_map
import prog_bar
import numpy_help_cpp
import python_obj_cpp
import matrix_cpp
import gamma_cpp
import setProcName
import start_cpp
import make
import doc_gen
# Setup...
doc = doc_gen.DocGen('utils', 'Utilities/Miscellaneous', 'Library of miscellaneous stuff - most modules depend on this.')
doc.addFile('readme.txt', 'Overview')
# Variables...
doc.addVariable('numpy_help_cpp.numpy_util_code', 'Assorted utility functions for accessing numpy arrays within scipy.weave C++ code.')
doc.addVariable('python_obj_cpp.python_obj_code', 'Assorted utility functions for interfacing with python objects from scipy.weave C++ code.')
doc.addVariable('matrix_cpp.matrix_code', 'Matrix manipulation routines for use in scipy.weave C++')
doc.addVariable('gamma_cpp.gamma_code', 'Gamma and related functions for use in scipy.weave C++')
# Functions...
doc.addFunction(make.make_mod)
doc.addFunction(cvarray.cv2array)
doc.addFunction(cvarray.array2cv)
doc.addFunction(mp_map.repeat)
doc.addFunction(mp_map.mp_map)
doc.addFunction(setProcName.setProcName)
doc.addFunction(start_cpp.start_cpp)
doc.addFunction(make.make_mod)
# Classes...
doc.addClass(prog_bar.ProgBar)
doc.addClass(doc_gen.DocGen)
| Python |
# Copyright (c) 2011, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest
import random
import math
from scipy.special import gammaln, psi, polygamma
from scipy import weave
from utils.start_cpp import start_cpp
# Provides various gamma-related functions...
gamma_code = start_cpp() + """
#ifndef GAMMA_CODE
#define GAMMA_CODE
#include <cmath>
// Returns the natural logarithm of the Gamma function...
// (Uses Lanczos's approximation.)
double lnGamma(double z)
{
static const double coeff[9] = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};
if (z<0.5)
{
// Use reflection formula, as approximation doesn't work down here...
return log(M_PI) - log(sin(M_PI*z)) - lnGamma(1.0-z);
}
else
{
double x = coeff[0];
for (int i=1;i<9;i++) x += coeff[i]/(z+i-1);
double t = z + 6.5;
return log(sqrt(2.0*M_PI)) + (z-0.5)*log(t) - t + log(x);
}
}
// Calculates the Digamma function, i.e. the derivative of the log of the Gamma function - uses a partial expansion of an infinite series to 4 terms that is good for high values, and an identity to express lower values in terms of higher values...
double digamma(double z)
{
static const double highVal = 13.0; // A bit of fiddling shows that the last term with this is of the order 1e-10, so we can expect at least 9 digits of accuracy past the decimal point.
double ret = 0.0;
while (z<highVal)
{
ret -= 1.0/z;
z += 1.0;
}
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz4 = iz2*iz2;
double iz6 = iz4*iz2;
ret += log(z) - iz1/2.0 - iz2/12.0 + iz4/120.0 - iz6/252.0;
return ret;
}
// Calculates the trigamma function - uses a partial expansion of an infinite series that is accurate for large values, and then uses an identity to express lower values in terms of higher values - same approach as for the digamma function basically...
double trigamma(double z)
{
static const double highVal = 8.0;
double ret = 0.0;
while (z<highVal)
{
ret += 1.0/(z*z);
z += 1.0;
}
z -= 1.0;
double iz1 = 1.0/z;
double iz2 = iz1*iz1;
double iz3 = iz1*iz2;
double iz5 = iz3*iz2;
double iz7 = iz5*iz2;
double iz9 = iz7*iz2;
ret += iz1 - 0.5*iz2 + iz3/6.0 - iz5/30.0 + iz7/42.0 - iz9/30.0;
return ret;
}
#endif
"""
def lnGamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns the logorithm of the gamma function"""
code = start_cpp(gamma_code) + """
return_val = lnGamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def digamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the digamma function"""
code = start_cpp(gamma_code) + """
return_val = digamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
def trigamma(z):
"""Pointless as scipy, a library this is dependent on, defines this, but useful for testing. Returns an evaluation of the trigamma function"""
code = start_cpp(gamma_code) + """
return_val = trigamma(z);
"""
return weave.inline(code, ['z'], support_code=gamma_code)
class TestFuncs(unittest.TestCase):
"""Test code for the assorted gamma-related functions."""
def test_compile(self):
code = start_cpp(gamma_code) + """
"""
weave.inline(code, support_code=gamma_code)
def test_error_lngamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = lnGamma(z)
good = gammaln(z)
assert(math.fabs(own-good)<1e-12)
def test_error_digamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = digamma(z)
good = psi(z)
assert(math.fabs(own-good)<1e-9)
def test_error_trigamma(self):
for _ in xrange(1000):
z = random.uniform(0.01, 100.0)
own = trigamma(z)
good = polygamma(1,z)
assert(math.fabs(own-good)<1e-9)
# If this file is run do the unit tests...
if __name__ == '__main__':
unittest.main()
| Python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010, Tom SF Haines
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import inspect
import hashlib
def start_cpp(hash_str = None):
"""This method does two things - firstly it adds the correct line numbers to scipy.weave code (Good for debugging) and secondly it can optionaly inserts a hash code of some other code into the code. This latter feature is useful for working around the fact the scipy.weave only recompiles if the hash of the code changes, but ignores the support_code - passing the support_code into start_cpp avoids this problem by putting its hash into the code and forcing a recompile when that code changes. Usage is <code variable> = start_cpp([support_code variable]) + <3 quotations to start big comment with code in, typically going over many lines.>"""
frame = inspect.currentframe().f_back
info = inspect.getframeinfo(frame)
if hash_str==None:
return '#line %i "%s"\n'%(info[1],info[0])
else:
h = hashlib.md5()
h.update(hash_str)
hash_val = h.hexdigest()
return '#line %i "%s" // %s\n'%(info[1],info[0],hash_val)
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.