code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
# -*- 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 |
# -*- 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 |
# 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 |
# -*- 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 start_cpp import start_cpp
from 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) 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 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 |
#! /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 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
# This script file generates a kde_inc.html file, which contains all the information needed to use the system.
import kde_inc
from utils import doc_gen
# Setup...
doc = doc_gen.DocGen('kde_inc', 'Incrimental kernel density estimation', 'Kernel density estimation with Gaussian kernels and greedy merging beyond a cap')
doc.addFile('readme.txt', 'Overview')
# Classes...
doc.addClass(kde_inc.PrecisionLOO)
doc.addClass(kde_inc.SubsetPrecisionLOO)
doc.addClass(kde_inc.GMM)
doc.addClass(kde_inc.KDE_INC)
| 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 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) 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 |
# 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, lambda x: inspect.ismethod(x) or inspect.isbuiltin(x) or inspect.isroutine(x))
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__) and (not inspect.ismethod(method) and name[:2]!='__'):
if inspect.ismethod(method):
args, varargs, keywords, defaults = inspect.getargspec(method)
else:
args = ['?']
varargs = None
keywords = None
defaults = None
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: inspect.ismemberdescriptor(x) or isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
if hasattr(var, '__doc__'): d = var.__doc__
else: d = str(var)
self.wiki_classes += '*`%s`* = %s\n\n'%(name, d)
| 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 |
# -*- 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 |
# -*- 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 |
# 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 |
# -*- 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 start_cpp import start_cpp
from 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) 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 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 |
#! /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 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
import math
import random
import numpy
import scipy.weave as weave
from kmeans_shared import KMeansShared
class KMeans2(KMeansShared):
"""This version of kmeans gets clever with its initialisation, running k-means on a subset of points, repeatedly, then combining the various runs, before ultimatly only doing k-means on the full dataset just once. This optimisation is only valuable for large data sets, e.g. with at least 10k feature vectors, and will cause slow down for small data sets."""
def __kmeans(self, centres, data, minSize = 3, maxIters = 1024, assignOut = None):
"""Internal method - does k-means on the data set as it is treated internally. Given the initial set of centres and a data matrix - the centres matrix is then updated to the new positions."""
assignment = numpy.empty(data.shape[0], dtype=numpy.int_)
assignmentCount = numpy.empty(centres.shape[0], dtype=numpy.int_)
assignment[:] = -1
code = """
for (int i=0;i<maxIters;i++)
{
// Reassign features to clusters...
bool change = false;
for (int f=0;f<Ndata[0];f++)
{
int best = -1;
float bestDist = 1e100;
for (int c=0;c<Ncentres[0];c++)
{
float dist = 0.0;
for (int e=0;e<Ndata[1];e++)
{
float d = DATA2(f,e) - CENTRES2(c,e);
dist += d*d;
}
if (dist<bestDist)
{
best = c;
bestDist = dist;
}
}
if (best!=ASSIGNMENT1(f))
{
ASSIGNMENT1(f) = best;
change = true;
}
}
// If no reassignments happen break out early...
if (change==false) break;
// Recalculate cluster centres with an incrimental mean...
for (int c=0;c<Ncentres[0];c++)
{
for (int e=0;e<Ndata[1];e++) {CENTRES2(c,e) = 0.0;}
ASSIGNMENTCOUNT1(c) = 0;
}
for (int f=0;f<Ndata[0];f++)
{
int c = ASSIGNMENT1(f);
ASSIGNMENTCOUNT1(c) += 1;
float div = ASSIGNMENTCOUNT1(c);
for (int e=0;e<Ndata[1];e++)
{
CENTRES2(c,e) += (DATA2(f,e) - CENTRES2(c,e)) / div;
}
}
// Reassign puny clusters...
for (int c=0;c<Ncentres[0];c++)
{
if (ASSIGNMENTCOUNT1(c)<minSize)
{
int rf = rand() % Ndata[0];
for (int e=0;e<Ndata[1];e++)
{
CENTRES2(c,e) = DATA2(rf,e);
}
}
}
}
"""
weave.inline(code,['centres', 'assignment', 'assignmentCount','data','maxIters','minSize'])
if assignOut!=None: assignOut[:] = assignment
def doTrain(self, feats, clusters, callback = None, smallCount = 32, smallMult = 3, minSize = 2, maxIters = 256, assignOut = None):
"""Given a features data matrix this finds a good set of cluster centres. clusters is the number of clusters to create."""
if callback!=None:
callback(0,smallCount*2+2)
# Iterate through and create a set of centres derived from small samples...
smallSize = clusters * smallMult * minSize
startOptions = []
for i in xrange(smallCount):
if callback!=None:
callback(1+i,smallCount*2+2)
# Grab a small sample from the data matrix, in randomised order...
sample = feats[numpy.random.permutation(feats.shape[0])[:smallSize],:]
# Select the first 'clusters' rows as the initial centres - its already in random order so no point in more randomisation...
centres = sample[:clusters,:]
# Run k-means...
self.__kmeans(centres, sample, minSize, maxIters)
# Store the set of centres ready for the next bit...
startOptions.append(centres)
# Iterate through each of the centres calculated above, using them to initialise kmeans on all the centres combined; select the centres that have the minimum negative log likelihood on this limited data set as the intialisation for the final step (Use a value that is proportional rather than actually calculating -log likelihood.)...
allStarts = numpy.vstack(startOptions)
bestStart = None
bestScore = 1e100
for i,centres in enumerate(startOptions):
if callback!=None:
callback(1+smallCount+i,smallCount*2+2)
# Run k-means...
self.__kmeans(centres, allStarts, minSize, maxIters)
# Calculate the sum of distances from the nearest centres, which is proportional to the negative log likelihood of the model...
distSum = 0.0
for i in xrange(allStarts.shape[0]):
distSum += ((centres-allStarts[i])**2).sum(axis=1).min()
# If better then previous scores store it for use...
if distSum<bestScore:
bestStart = centres
bestScore = distSum
# Finally do k-means on the full data set, using the initialisation that has been calculated...
if callback!=None:
callback(1+smallCount*2,smallCount*2+2)
self.__kmeans(bestStart, feats, minSize, maxIters, assignOut)
self.means = bestStart
del callback # There is a bug in here somewhere and this fixes it. Fixing the actual bug might be wise, but I just can't see it. (Somehow the functions callspace is kept, but can't see how.)
| Python |
# -*- coding: utf-8 -*-
# Copyright 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
import math
import random
import numpy
import scipy.weave as weave
from kmeans_shared import KMeansShared
class KMeans1(KMeansShared):
"""The most basic implimentation of k-means possible - just brute force with multiple restarts."""
def doTrain(self, feats, clusters, maxIters = 512, restarts = 8, minSize = 4, callback = None, assignOut = None):
"""Given a large number of features as a data matrix this finds a good set of cluster centres. clusters is the number of clusters to create, maxIters is the maximum number of iterations for convergance of a cluster and restarts how many times to run - the most probable result is used. minSize is the smallest cluster size - if a cluster is smaller than this it is reinitialised."""
if callback!=None:
callback(0,restarts+1)
# Required data structures...
bestModelScore = None # Score of the model currently in self.means
centres = numpy.empty((clusters,feats.shape[1]), dtype=numpy.float_)
assignment = numpy.empty(feats.shape[0], dtype=numpy.int_)
assignmentCount = numpy.empty(clusters, dtype=numpy.int_)
# Iterate and run the algorithm from scratch a number of times, calculating the log likelihood of the model each time, so we can ultimatly select the best...
for r in xrange(restarts):
if callback!=None:
callback(1+r,restarts+1)
# Initialisation - fill in the matrix of cluster centres, where centres are initialised by randomly selecting a point from the data set (With duplication - we let the reinitalisation code deal with them.)...
for c in xrange(centres.shape[0]):
ri = random.randrange(feats.shape[0])
centres[c,:] = feats[ri,:]
assignment[:] = -1
try:
code = """
for (int i=0;i<maxIters;i++)
{
// Reassign features to clusters...
bool change = false;
for (int f=0;f<Nfeats[0];f++)
{
int best = -1;
float bestDist = 1e100;
for (int c=0;c<Ncentres[0];c++)
{
float dist = 0.0;
for (int e=0;e<Nfeats[1];e++)
{
float d = FEATS2(f,e) - CENTRES2(c,e);
dist += d*d;
}
if (dist<bestDist)
{
best = c;
bestDist = dist;
}
}
if (best!=ASSIGNMENT1(f))
{
ASSIGNMENT1(f) = best;
change = true;
}
}
// If no reassignments happen break out early...
if (change==false) break;
// Recalculate cluster centres with an incrimental mean...
for (int c=0;c<Ncentres[0];c++)
{
for (int e=0;e<Nfeats[1];e++) {CENTRES2(c,e) = 0.0;}
ASSIGNMENTCOUNT1(c) = 0;
}
for (int f=0;f<Nfeats[0];f++)
{
int c = ASSIGNMENT1(f);
ASSIGNMENTCOUNT1(c) += 1;
float div = ASSIGNMENTCOUNT1(c);
for (int e=0;e<Nfeats[1];e++)
{
CENTRES2(c,e) += (FEATS2(f,e) - CENTRES2(c,e)) / div;
}
}
// Reassign puny clusters...
for (int c=0;c<Ncentres[0];c++)
{
if (ASSIGNMENTCOUNT1(c)<minSize)
{
int rf = rand() % Nfeats[0];
for (int e=0;e<Nfeats[1];e++)
{
CENTRES2(c,e) = FEATS2(rf,e);
}
}
}
}
"""
weave.inline(code,['centres', 'assignment', 'assignmentCount','feats','maxIters','minSize'])
except:
# Iterate until convergance...
for i in xrange(maxIters):
# Re-assign features to clusters...
beenChange = False
for i in xrange(feats.shape[0]): # Slow bit
nearest = ((centres-feats[i,:])**2).sum(axis=1).argmin()
if nearest!=assignment[i]:
beenChange = True
assignment[i] = nearest
# If no reassignments happen break out early...
if beenChange==False: break
# Recalculate cluster centres (Incrimental mean used)...
centres[:] = 0.0
assignmentCount[:] = 0
for i in xrange(feats.shape[0]):
c = assignment[i]
assignmentCount[c] += 1
centres[c,:] += (feats[i,:]-centres[c,:])/float(assignmentCount[c])
# Find all puny clusters and reinitialise...
indices = numpy.argsort(assignmentCount)
for ic in xrange(indices.shape[0]):
c = indices[ic]
if assignmentCount[c]>=minSize:
break
ri = random.randrange(feats.shape[0])
centres[c,:] = feats[ri,:]
# Calculate the models negative log likelihood - if better than the current model replace it (This is done proportionally)...
if bestModelScore==None:
self.means = centres.copy()
else:
negLogLike = 0.0
for i in xrange(feats.shape[0]):
negLogLike += ((feats[i,:]-centres[assignment[i],:])**2).sum()
if negLogLike<bestModelScore:
self.means = centres.copy()
if assignOut!=None: assignOut[:] = assignment
| Python |
# -*- coding: utf-8 -*-
# Copyright 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
import math
import random
import numpy
import scipy.cluster.vq
from kmeans_shared import KMeansShared
class KMeans0(KMeansShared):
"""Wraps the kmeans implimentation provided by scipy with the same interface as provided by the other kmeans implimentations in the system. My experiance shows that this is insanely slow - not sure why, but even my brute force C implimentation is faster (Best guess is its coded in python, and not optimised in any way.)."""
def doTrain(self, feats, clusters, maxIters = 512, restarts = 8, assignOut = None):
"""Given a large number of features as a data matrix this finds a good set of cluster centres. clusters is the number of clusters to create, maxIters is the maximum number of iterations for convergance of a cluster and restarts how many times to run - the most probable result is used. minSize is the smallest cluster size - if a cluster is smaller than this it is reinitialised."""
self.means = numpy.empty((clusters, feats.shape[1]), dtype=numpy.float_)
self.means[:,:] = scipy.cluster.vq.kmeans(feats, clusters, restarts)[0]
if assignOut!=None: assignOut[:], _ = scipy.cluster.vq.vq(feats, centres)
| Python |
# -*- coding: utf-8 -*-
# Copyright 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
# Includes everything needed to use the module in a single namespace, for conveniance...
from kmeans import *
from isotropic import IsotropicGMM
from bic import modelSelectBIC
from kmeans_shared import KMeansShared
from mixture import Mixture
| Python |
# -*- coding: utf-8 -*-
# Copyright 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
import exceptions
import cPickle as pickle
import numpy
class Mixture:
"""Defines the basic interface to a mixture model - the methods to train, and then classify basically. Includes funky conversions to allow many forms of input/output, for conveniance."""
def clusterCount(self):
"""To be implimented by the inheriting class - returns how many elements the mixture has, i.e. the cluster count."""
raise exceptions.NotImplementedError()
def parameters(self):
"""To be implimented by the inheriting class - returns how many parameters the model has."""
raise exceptions.NotImplementedError()
def doTrain(self,feats,clusters):
"""To be implimented by the inheriting class, possibly with further implimentation specific parameters. Accepts a data matrix and a cluster count."""
raise exceptions.NotImplementedError()
def doGetWeight(self,feats):
"""To be implimented by the inheriting class. Given a data matrix returns a new matrix, where the feature vectors have been replaced by the probabilities of the feature being generated by each of the clusters."""
raise exceptions.NotImplementedError()
def doGetCluster(self,feats):
"""To be implimented by the inheriting class. Given a data matrix returns an integer vector, where each feature vector has assigned the cluster from which it most likelly comes."""
raise exceptions.NotImplementedError()
def doGetNLL(self,feats):
"""To be implimented by the inheriting class. Given a data matrix returns the negative log likelihood of the data comming from this model."""
raise exceptions.NotImplementedError()
def train(self,feats,clusters,*listArgs,**dictArgs):
"""Accepts as input the features, how many clusters to use and any further implimentation specific variables. The features can be represented as a data matrix, a list of vectors or as a list of tuples where the last entry is a feature vector. Will then train the model on the given data set."""
if isinstance(feats,numpy.ndarray):
# Numpy array - just pass through...
assert(len(feats.shape)==2)
self.doTrain(feats,clusters,*listArgs,**dictArgs)
elif isinstance(feats,list):
if isinstance(feats[0],numpy.ndarray):
# List of vectors - glue them all together to create a data matrix and pass on through...
data = numpy.vstack(feats)
self.doTrain(data,clusters,*listArgs,**dictArgs)
elif isinstance(feats[0],tuple):
# List of tuples where the last item should be a numpy.array as a feature vector...
vecs = map(lambda x:x[-1],feats)
data = numpy.vstack(vecs)
self.doTrain(data,clusters,*listArgs,**dictArgs)
else:
raise exceptions.TypeError('bad type for features - when given a list it must contain numpy.array vectors or tuples with the last element a vector')
else:
raise exceptions.TypeError('bad type for features - expects a numpy.array or a list')
def getWeight(self,feats):
"""Given a set of features returns for each feature the probability of having been generated by each mixture member - this vector will sum to one. Multiple input/output modes are supported. If a data matrix is input then the output will be a matrix where each row has been replaced by the mixing vector. If the input is a list of feature vectors the output will be a list of mixing vectors. If the input is a list of tuples with the last elements a feature vector the output will be identical, but with the feature vectors replaced with mixing vectors."""
if isinstance(feats,numpy.ndarray):
# Numpy array - just pass through...
assert(len(feats.shape)==2)
return self.doGetWeight(feats)
elif isinstance(feats,list):
if isinstance(feats[0],numpy.ndarray):
# List of vectors - glue them all together to create a data matrix and pass on through...
data = numpy.vstack(feats)
asMat = self.doGetWeight(data)
return map(lambda i:asMat[i,:],xrange(asMat.shape[0]))
elif isinstance(feats[0],tuple):
# List of tuples where the last item should be a numpy.array as a feature vector...
vecs = map(lambda x:x[-1],feats)
data = numpy.vstack(vecs)
asMat = self.doGetWeight(data)
return map(lambda i:feats[i][:-1] + (asMat[i,:],),xrange(asMat.shape[0]))
else:
raise exceptions.TypeError('bad type for features - when given a list it must contain numpy.array vectors or tuples with the last element a vector')
else:
raise exceptions.TypeError('bad type for features - expects a numpy.array or a list')
def getCluster(self,feats):
"""Given a set of features returns for each feature the cluster with the highest probability of having generated it. Multiple input/output modes are supported. If a data matrix is input then the output will be an integer vector of cluster indices. If the input is a list of feature vectors the output will be a list of cluster indices. If the input is a list of tuples with the last elements a feature vector the output will be identical, but with the feature vectors replaced by cluster integers."""
if isinstance(feats,numpy.ndarray):
# Numpy array - just pass through...
assert(len(feats.shape)==2)
return self.doGetCluster(feats)
elif isinstance(feats,list):
if isinstance(feats[0],numpy.ndarray):
# List of vectors - glue them all together to create a data matrix and pass on through...
data = numpy.vstack(feats)
asVec = self.doGetCluster(data)
return map(lambda i:asVec[i],xrange(asVec.shape[0]))
elif isinstance(feats[0],tuple):
# List of tuples where the last item should be a numpy.array as a feature vector...
vecs = map(lambda x:x[-1],feats)
data = numpy.vstack(vecs)
asVec = self.doGetCluster(data)
return map(lambda i:feats[i][:-1] + (asVec[i],),xrange(asVec.shape[0]))
else:
raise exceptions.TypeError('bad type for features - when given a list it must contain numpy.array vectors or tuples with the last element a vector')
else:
raise exceptions.TypeError('bad type for features - expects a numpy.array or a list')
def getNLL(self,feats):
"""Given a set of features returns the negative log likelihood of the given features being generated by the model."""
if isinstance(feats,numpy.ndarray):
# Numpy array - just pass through...
assert(len(feats.shape)==2)
return self.doGetNLL(feats)
elif isinstance(feats,list):
if isinstance(feats[0],numpy.ndarray):
# List of vectors - glue them all together to create a data matrix and pass on through...
data = numpy.vstack(feats)
return self.doGetNLL(data)
elif isinstance(feats[0],tuple):
# List of tuples where the last item should be a numpy.array as a feature vector...
vecs = map(lambda x:x[-1],feats)
data = numpy.vstack(vecs)
return self.doGetNLL(data)
else:
raise exceptions.TypeError('bad type for features - when given a list it must contain numpy.array vectors or tuples with the last element a vector')
else:
raise exceptions.TypeError('bad type for features - expects a numpy.array or a list')
def getData(self):
"""Returns the data contained within, so it can be serialised with other data. (You can of course serialise this class directly if you want, but the returned object is a tuple of numpy arrays, so less likely to be an issue for any program that loads it.)"""
raise exceptions.NotImplementedError()
def setData(self,data):
"""Sets the data for the object, should be same form as returned from getData."""
raise exceptions.NotImplementedError()
| Python |
# -*- coding: utf-8 -*-
# Copyright 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
# Simple file that imports the various implimentations and provides a default implimentation of kmeans, which happens to be the most sophisticated version...
from kmeans0 import KMeans0
from kmeans1 import KMeans1
from kmeans2 import KMeans2
from kmeans3 import KMeans3
KMeansShort = KMeans1
KMeans = KMeans3
| Python |
# -*- coding: utf-8 -*-
# Copyright 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
import math
import random
import numpy
import scipy.weave as weave
from kmeans import KMeans
from mixture import Mixture
class IsotropicGMM(Mixture):
"""Fits a gaussian mixture model to a data set, using isotropic Gaussians, i.e. so each is parameterised by only a single standard deviation, in addition to position and weight."""
def __init__(self):
self.mix = None # Vector of mixing probabilities.
self.mean = None # 2D array where each row is the mean of a distribution.
self.sd = None # Vector of standard deviations.
def clusterCount(self):
"""Returns how many clusters it has been fitted with, or 0 if it is yet to be trainned."""
if self.mix!=None: return self.mix.shape[0]
else: return 0
def parameters(self):
"""Returns how many parameters the currently fitted model has, used for model selection."""
return self.mean.shape[0]*(self.mean.shape[1]+2)
def getMix(self,i):
"""Returns the mixing weight for the given cluster."""
return self.mix[i]
def getCentre(self,i):
"""Returns the mean/centre of the given cluster."""
return self.mean[i,:]
def getSD(self,i):
"""Returns the standard deviation for the given cluster."""
return self.sd[i]
def doTrain(self, feats, clusters, maxIters = 1024, epsilon = 1e-4):
# Initialise using kmeans...
km = KMeans()
kmAssignment = numpy.empty(feats.shape[0],dtype=numpy.float_)
km.train(feats,clusters,assignOut = kmAssignment)
# Create the assorted data structures needed...
mix = numpy.ones(clusters,dtype=numpy.float_)/float(clusters)
mean = numpy.empty((clusters,feats.shape[1]),dtype=numpy.float_)
for c in xrange(clusters): mean[c,:] = km.getCentre(c)
sd = numpy.zeros(clusters,dtype=numpy.float_)
tempCount = numpy.zeros(clusters,dtype=numpy.int_)
for f in xrange(feats.shape[0]):
c = kmAssignment[f]
dist = ((feats[f,:] - mean[c,:])**2).sum()
tempCount[c] += 1
sd += (dist-sd)/float(tempCount[c])
sd = numpy.sqrt(sd/float(feats.shape[1]))
wv = numpy.ones((feats.shape[0],clusters),dtype=numpy.float_) # Weight vectors calculated in e-step.
pwv = numpy.empty(clusters,dtype=numpy.float_) # For convergance detection.
norms = numpy.empty(clusters,dtype=numpy.float_) # Normalising constants for the distributions, to save repeated calculation.
sqrt2pi = math.sqrt(2.0*math.pi)
# The code...
code = """
for (int iter=0;iter<maxIters;iter++)
{
// e-step - for all features calculate the weight vector (Also do convergance detection.)...
for (int c=0;c<Nmean[0];c++)
{
norms[c] = pow(sqrt2pi*sd[c], Nmean[1]);
}
bool done = true;
for (int f=0;f<Nfeats[0];f++)
{
float sum = 0.0;
for (int c=0;c<Nmean[0];c++)
{
float distSqr = 0.0;
for (int i=0;i<Nmean[1];i++)
{
float diff = FEATS2(f,i) - MEAN2(c,i);
distSqr += diff*diff;
}
pwv[c] = WV2(f,c);
float core = -0.5*distSqr / (sd[c]*sd[c]);
WV2(f,c) = mix[c]*exp(core); // Unnormalised.
WV2(f,c) /= norms[c]; // Normalisation
sum += WV2(f,c);
}
for (int c=0;c<Nmean[0];c++)
{
WV2(f,c) /= sum;
done = done && (fabs(WV2(f,c)-pwv[c])<epsilon);
}
}
if (done) break;
// Zero out mix,mean and sd, ready for filling...
for (int c=0;c<Nmean[0];c++)
{
mix[c] = 0.0;
for (int i=0;i<Nmean[1];i++) MEAN2(c,i) = 0.0;
sd[c] = 0.0;
}
// m-step - update the mixing vector, means and sd...
// *Calculate mean and mixing vector incrimentally...
for (int f=0;f<Nfeats[0];f++)
{
for (int c=0;c<Nmean[0];c++)
{
mix[c] += WV2(f,c);
if (WV2(f,c)>1e-6) // Msut not update if value is too low due to division in update - NaN avoidance.
{
for (int i=0;i<Nmean[1];i++)
{
MEAN2(c,i) += WV2(f,c) * (FEATS2(f,i) - MEAN2(c,i)) / mix[c];
}
}
}
}
// prevent the mix of any given component getting too low - will cause the algorithm to NaN...
for (int c=0;c<Nmean[0];c++)
{
if (mix[c]<1e-6) mix[c] = 1e-6;
}
// *Calculate the sd simply, initial calculation is sum of squared differences...
for (int f=0;f<Nfeats[0];f++)
{
for (int c=0;c<Nmean[0];c++)
{
float distSqr = 0.0;
for (int i=0;i<Nmean[1];i++)
{
float delta = FEATS2(f,i) - MEAN2(c,i);
distSqr += delta*delta;
}
sd[c] += WV2(f,c) * distSqr;
}
}
// *Final adjustments for the new state...
float mixSum = 0.0;
for (int c=0;c<Nmean[0];c++)
{
sd[c] = sqrt(sd[c]/(mix[c]*float(Nfeats[1])));
mixSum += mix[c];
}
for (int c=0;c<Nmean[0];c++) mix[c] /= mixSum;
}
"""
# Weave it...
weave.inline(code,['feats', 'maxIters', 'epsilon', 'mix', 'mean', 'sd', 'wv', 'pwv', 'norms', 'sqrt2pi'])
# Store result...
self.mix = mix
self.mean = mean
self.sd = sd
def doGetUnnormWeight(self,feats):
ret = numpy.empty((feats.shape[0],self.mix.shape[0]),dtype=numpy.float_)
norms = numpy.empty(self.mix.shape[0],dtype=numpy.float_) # Normalising constants for the distributions, to save repeated calculation.
sqrt2pi = math.sqrt(2.0*math.pi)
code = """
for (int c=0;c<Nmean[0];c++) norms[c] = pow(sqrt2pi*sd[c],Nmean[1]);
for (int f=0;f<Nfeats[0];f++)
{
float sum = 0.0;
for (int c=0;c<Nmean[0];c++)
{
float distSqr = 0.0;
for (int i=0;i<Nmean[1];i++)
{
float diff = FEATS2(f,i) - MEAN2(c,i);
distSqr += diff*diff;
}
RET2(f,c) = mix[c]*exp(-0.5*distSqr/(sd[c]*sd[c])); // Unnormalised.
RET2(f,c) /= norms[c]; // Normalisation
}
}
"""
mix = self.mix
mean = self.mean
sd = self.sd
weave.inline(code,['feats', 'ret', 'mix', 'mean', 'sd', 'norms', 'sqrt2pi'])
return ret
def doGetWeight(self,feats):
"""Returns the probability of it being drawn from each of the clusters, as a vector. It will obviously sum to one."""
ret = self.doGetUnnormWeight(feats)
ret = (ret.T/ret.sum(axis=1)).T
return ret
def doGetCluster(self,feats):
"""Returns the cluster it is, with greatest probability, a member of."""
return self.doGetUnnormWeight(feats).argmax(axis=1)
def doGetNLL(self,feats):
"""returns the negative log likelihood of the given set of features being drawn from the model."""
return -numpy.log(self.doGetUnnormWeight(feats).sum(axis=1)).sum()
def getData(self):
"""Returns the data contained within, so it can be serialised with other data. (You can of course serialise this class directly if you want, but the returned object is a tuple of numpy arrays, so less likely to be an issue for any program that loads it.)"""
return (self.mix,self.mean,self.sd)
def setData(self,data):
"""Sets the data for the object, should be same form as returned from getData."""
self.mix = data[0]
self.mean = data[1]
self.sd = data[2]
| Python |
# -*- coding: utf-8 -*-
# Copyright 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
import math
import random
import numpy
import scipy.weave as weave
from kmeans1 import KMeans1
from kmeans2 import KMeans2
class KMeans3(KMeans2):
"""Takes the initialisation improvememnts of KMeans2 and additionally makes improvements to the kmeans implimentation. Specifically it presumes that distance computations are expensive and avoids doing them where possible, by additionally storing how far each cluster centre moved since the last step. This allows a lot of such computations to be pruned, especially later on when cluster centres are not moving. It does not work if distance computations are cheap however, so only worth it for long feature vectors."""
def __kmeans(self, centres, data, minSize = 3, maxIters = 1024, assignOut = None):
"""Internal method - does k-means on the data set as it is treated internally. Given the initial set of centres and a data matrix - the centres matrix is then updated to the new positions."""
assignment = numpy.empty(data.shape[0], dtype=numpy.int_)
assignmentDist = numpy.empty(data.shape[0], dtype=numpy.float_) # Distance squared
assignment[:] = -1
assignmentDist[:] = 0.0
assignmentCount = numpy.empty(centres.shape[0], dtype=numpy.int_)
motion = numpy.empty(centres.shape[0], dtype=numpy.float_) # This is distance, rather than distance squared, unlike for assignments.
motion[:] = 1e100
tempCentres = numpy.empty(centres.shape, dtype=numpy.float_)
code = """
for (int i=0;i<maxIters;i++)
{
// Reassign features to clusters...
bool change = false;
for (int f=0;f<Ndata[0];f++)
{
// Initialise the best to the previous best...
int best = ASSIGNMENT1(f);
float bestDist; // Squared distance.
if (best==-1) bestDist = 1e100;
else
{
if (MOTION1(best)<1e-6) bestDist = ASSIGNMENTDIST1(f);
else
{
bestDist = 0.0;
for (int e=0;e<Ndata[1];e++)
{
float d = DATA2(f,e) - CENTRES2(best,e);
bestDist += d*d;
}
}
}
// Check all the centres to see if they are better than the current best...
float rad = sqrt(ASSIGNMENTDIST1(f)); // Distance to closest center from *previous* iteration - all other centers must of been further away in this iteration.
for (int c=0;c<Ncentres[0];c++)
{
if (c==ASSIGNMENT1(f)) continue;
// Only do the distance calculation if the node could actually suceded..
float optDist = rad - MOTION1(c);
optDist *= optDist; // Distance -> distance squared.
if (optDist<bestDist)
{
// Node stands a chance - do the full calculation...
float dist = 0.0;
for (int e=0;e<Ndata[1];e++)
{
float d = DATA2(f,e) - CENTRES2(c,e);
dist += d*d;
}
if (dist<bestDist)
{
best = c;
bestDist = dist;
}
}
}
change |= (best!=ASSIGNMENT1(f));
ASSIGNMENT1(f) = best;
ASSIGNMENTDIST1(f) = bestDist;
}
// If no reassignments happen break out early...
if (change==false) break;
// Recalculate cluster centres with an incrimental mean...
for (int c=0;c<Ncentres[0];c++)
{
for (int e=0;e<Ndata[1];e++) {TEMPCENTRES2(c,e) = 0.0;}
ASSIGNMENTCOUNT1(c) = 0;
}
for (int f=0;f<Ndata[0];f++)
{
int c = ASSIGNMENT1(f);
ASSIGNMENTCOUNT1(c) += 1;
float div = ASSIGNMENTCOUNT1(c);
for (int e=0;e<Ndata[1];e++)
{
TEMPCENTRES2(c,e) += (DATA2(f,e) - TEMPCENTRES2(c,e)) / div;
}
}
// Transfer over, storing the motion vectors...
for (int c=0;c<Ncentres[0];c++)
{
MOTION1(c) = 0.0;
for (int e=0;e<Ndata[1];e++)
{
float delta = TEMPCENTRES2(c,e) - CENTRES2(c,e);
MOTION1(c) += delta*delta;
CENTRES2(c,e) = TEMPCENTRES2(c,e);
}
MOTION1(c) = sqrt(MOTION1(c));
}
// Reassign puny clusters...
for (int c=0;c<Ncentres[0];c++)
{
if (ASSIGNMENTCOUNT1(c)<minSize)
{
int rf = rand() % Ndata[0];
for (int e=0;e<Ndata[1];e++)
{
CENTRES2(c,e) = DATA2(rf,e);
}
MOTION1(c) = 1e100;
}
}
}
"""
weave.inline(code,['centres', 'assignment', 'assignmentDist', 'assignmentCount', 'motion', 'data', 'tempCentres', 'maxIters', 'minSize'])
if assignOut!=None: assignOut[:] = assignment
| Python |
# -*- coding: utf-8 -*-
# Copyright 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
import math
import exceptions
import cPickle as pickle
import numpy
class KMeansShared:
"""Provides a standard interface for k-means, so that all implimentations provide the same one. key issue is that features can be provided in 3 ways - an array where each row is a feature, a list of feature vectors, a list of tuples where the last entry of each tuple is the feature vector. These are then passed through to return values, but the actual implimentation only has to deal with one interface."""
def __init__(self):
self.means = None # Matrix of mean points, where each row is the coordinate of the centre of a cluster.
def parameters(self):
"""Returns how many parameters the currently fitted model has, used for model selection."""
return self.means.shape[0]*self.means.shape[1]
def clusterCount(self):
"""returns how many clusters it has been trained with, returns 0 if it has not been trainned."""
if self.means!=None: return self.means.shape[0]
else: return 0
def getCentre(self, i):
"""Returns the centre of the indexed cluster."""
return self.means[i,:]
def doTrain(self, feats, clusters):
"""Should train the model given a data matrix, where each row is a feature."""
raise exceptions.NotImplementedError()
def doGetCluster(self, feats):
"""feats should arrive as a 2D array, where each row is a feature - should return an integer vector of which cluster each array is assigned to. Default implimentation uses brute force, which is typically fast enough assuming a reasonable number of clusters."""
ret = numpy.empty(feats.shape[0],dtype=numpy.int_)
for i in xrange(feats.shape[0]):
ret[i] = ((self.means-feats[i,:])**2).sum(axis=1).argmin()
return ret
def train(self, feats, clusters, *listArgs, **dictArgs):
"""Given the features and number of clusters, plus any implimentation specific arguments, this trains the model. Features can be provided as a data matrix, as a list of feature vectors or as a list of tuples where the last entry of each tuple is a feature vector."""
if isinstance(feats,numpy.ndarray):
# Numpy array - just pass through...
assert(len(feats.shape)==2)
self.doTrain(feats,clusters,*listArgs,**dictArgs)
del listArgs,dictArgs
elif isinstance(feats,list):
if isinstance(feats[0],numpy.ndarray):
# List of vectors - glue them all together to create a data matrix and pass on through...
data = numpy.vstack(feats)
self.doTrain(data,clusters,*listArgs,**dictArgs)
del listArgs,dictArgs
elif isinstance(feats[0],tuple):
# List of tuples where the last item should be a numpy.array as a feature vector...
vecs = map(lambda x:x[-1],feats)
data = numpy.vstack(vecs)
self.doTrain(data,clusters,*listArgs,**dictArgs)
del listArgs,dictArgs
else:
raise exceptions.TypeError('bad type for features - when given a list it must contain numpy.array vectors or tuples with the last element a vector')
else:
raise exceptions.TypeError('bad type for features - expects a numpy.array or a list')
def getCluster(self, feats):
"""Converts the feature vectors of the input into integers, which represent the cluster which each feature is most likelly a member of. Output will be the same form as the input, but with the features converted to integers. In the case of a feature matrix it will become a vector of integers. For a list of feature vectors it will become a list of integers. For a list of tuples with the last element a feature vector it will return a list of tuples where the last element has been replaced with an integer."""
if isinstance(feats,numpy.ndarray):
# Numpy array - just pass through...
assert(len(feats.shape)==2)
return self.doGetCluster(feats)
elif isinstance(feats,list):
if isinstance(feats[0],numpy.ndarray):
# List of vectors - glue them all together to create a data matrix and pass on through...
data = numpy.vstack(feats)
asVec = self.doGetCluster(data)
return map(lambda i:asVec[i],xrange(asVec.shape[0]))
elif isinstance(feats[0],tuple):
# List of tuples where the last item should be a numpy.array as a feature vector...
vecs = map(lambda x:x[-1],feats)
data = numpy.vstack(vecs)
asVec = self.doGetCluster(data)
return map(lambda i:feats[i][:-1] + (asVec[i],),xrange(asVec.shape[0]))
else:
raise exceptions.TypeError('bad type for features - when given a list it must contain numpy.array vectors or tuples with the last element a vector')
else:
raise exceptions.TypeError('bad type for features - expects a numpy.array or a list')
def doGetNLL(self, feats):
"""Takes feats as a 2D data matrix and calculates the negative log likelihood of those features comming from the model, noting that it assumes a symmetric Gaussian for each centre and calculates the standard deviation using the provided features."""
# Record each features distance from its nearest cluster centre...
distSqr = numpy.empty(feats.shape[0], dtype=numpy.float_)
cat = numpy.empty(feats.shape[0], dtype=numpy.int_)
for i in xrange(feats.shape[0]):
distsSqr = ((self.means-feats[i,:].reshape((1,-1)))**2).sum(axis=1)
cat[i] = distsSqr.argmin()
distSqr[i] = distsSqr.min()
# Calculate the standard deviation to use for all clusters...
var = distSqr.sum() / (feats.shape[0] - self.means.shape[0])
# Sum up the log likelihood for all features...
mult = -0.5/var
norm = numpy.log(numpy.bincount(cat))
norm -= numpy.log(feats.shape[0])
norm -= 0.5 * (numpy.log(2.0*numpy.pi) + self.means.shape[1]*numpy.log(var))
ll = (distSqr*mult).sum()
ll += norm[cat].sum()
# Return the negative ll...
return -ll
def getNLL(self, feats):
"""Given a set of features returns the negative log likelihood of the given features being generated by the model. Note that as the k-means model is not probabilistic this is technically wrong, but it hacks it by treating each cluster as a symmetric Gaussian with a standard deviation calculated using the provided features, with equal probability of selecting each cluster."""
if isinstance(feats,numpy.ndarray):
# Numpy array - just pass through...
assert(len(feats.shape)==2)
return self.doGetNLL(feats)
elif isinstance(feats,list):
if isinstance(feats[0],numpy.ndarray):
# List of vectors - glue them all together to create a data matrix and pass on through...
data = numpy.vstack(feats)
return self.doGetNLL(data)
elif isinstance(feats[0],tuple):
# List of tuples where the last item should be a numpy.array as a feature vector...
vecs = map(lambda x:x[-1],feats)
data = numpy.vstack(vecs)
return self.doGetNLL(data)
else:
raise exceptions.TypeError('bad type for features - when given a list it must contain numpy.array vectors or tuples with the last element a vector')
else:
raise exceptions.TypeError('bad type for features - expects a numpy.array or a list')
def save(self, filename):
"""Saves the learned parameters to a file."""
pickle.dump(self.means, open(filename,'wb'), pickle.HIGHEST_PROTOCOL)
def load(self, filename):
"""Loads the learned parameters from a file."""
self.means = pickle.load(open(filename,'rb'))
def getData(self):
"""Returns the data contained within, so it can be serialised with other data. (You can of course serialise this class directly if you want, but the returned object is a numpy array, so less likely to be an issue for any program that loads it.)"""
return self.means
def setData(self,data):
"""Sets the data for the object, should be same form as returned from getData."""
self.means = data
| Python |
# -*- coding: utf-8 -*-
| Python |
# -*- coding: utf-8 -*-
# Copyright 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
import math
import numpy
def modelSelectBIC(feats, model, maxCount=-1):
"""Provides model selection, i.e. selection of the number of clusters, using the bayesian information criterion (BIC). You provide it with the features, and a model to train with (It just reuses it.) and the maximum size to consider (It starts at 2.). When it returns the given model will be left trained with the optimal result. If maxSize is less than 2, the default, it goes up to twice the logarithm of the feature vector count, rounded up and inclusive. if this is 2 or less you will get back the model trained with just two clusters."""
if isinstance(feats,numpy.ndarray): size = feats.shape[0]
else: size = len(feats)
if maxCount<2:
maxCount = int(math.ceil(2.0*math.log(size)))
if maxCount<2: maxCount = 2
best = None
bestScore = None
for c in xrange(2,maxCount+1):
model.train(feats,c)
score = 2.0*model.getNLL(feats) + model.parameters()*math.log(size)
if bestScore==None or bestScore>score:
bestScore = score
best = model.getData()
model.setData(best)
| 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 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) 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 |
# 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, lambda x: inspect.ismethod(x) or inspect.isbuiltin(x) or inspect.isroutine(x))
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__) and (not inspect.ismethod(method) and name[:2]!='__'):
if inspect.ismethod(method):
args, varargs, keywords, defaults = inspect.getargspec(method)
else:
args = ['?']
varargs = None
keywords = None
defaults = None
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: inspect.ismemberdescriptor(x) or isinstance(x, int) or isinstance(x, str) or isinstance(x, float))
for name, var in variables:
if not name.startswith('__'):
if hasattr(var, '__doc__'): d = var.__doc__
else: d = str(var)
self.wiki_classes += '*`%s`* = %s\n\n'%(name, d)
| 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 |
# -*- 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 |
# -*- 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 |
# 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 |
# -*- 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 start_cpp import start_cpp
from 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) 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 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 |
#! /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 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2011 Tom SF Haines
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
import gmm
from utils import doc_gen
# Setup...
doc = doc_gen.DocGen('gmm', 'Gaussian Mixture Model (plus K-means)', 'Gaussian mixture model, with EM, plus assorted k-means implimentations')
doc.addFile('readme.txt', 'Overview')
# Function that removes the methods that start with 'do' from a class - to hide them in the documentation...
def pruneClassOfDo(cls):
methods = dir(cls)
for method in methods:
if method[:2]=='do':
delattr(cls, method)
pruneClassOfDo(gmm.KMeansShared)
pruneClassOfDo(gmm.KMeans0)
pruneClassOfDo(gmm.KMeans1)
pruneClassOfDo(gmm.KMeans2)
pruneClassOfDo(gmm.KMeans3)
pruneClassOfDo(gmm.Mixture)
pruneClassOfDo(gmm.IsotropicGMM)
# Variables...
doc.addVariable('KMeans', 'The prefered k-means implimentation can be referenced as KMeans')
doc.addVariable('KMeansShort', 'The prefered k-means implimentation is choosen on the assumption of long feature vectors - if the feature vectors are in fact short then this is a synonym of a more appropriate fitter. (By short think less than 20, though this is somewhat computer dependent.)')
# Functions...
doc.addFunction(gmm.modelSelectBIC)
# Classes...
doc.addClass(gmm.KMeansShared)
doc.addClass(gmm.KMeans0)
doc.addClass(gmm.KMeans1)
doc.addClass(gmm.KMeans2)
doc.addClass(gmm.KMeans3)
doc.addClass(gmm.Mixture)
doc.addClass(gmm.IsotropicGMM)
| Python |
#!/usr/bin/python
#
# Copyright (c) 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
"""Utility method to import a diff from codereview.appspot.com and also apply hg renames."""
import urllib
import subprocess
import re
import sys
import os.path
file_name_re = re.compile('^Index: (\S+)$')
deleted_re = re.compile('^deleted file mode \S+$')
fp = re.compile('^rename from (\S+)$')
tp = re.compile('^rename to (\S+)$')
fcp = re.compile('^copy from (\S+)$')
tcp = re.compile('^copy to (\S+)$')
hg_cmd = 'hg'
if len(sys.argv) == 1:
print 'missing codereview.appspot.com URL'
sys.exit(1)
if not os.path.exists('.hg'):
print 'must be run from the root directory of the hg workspace'
sys.exit(1)
if '-f' == sys.argv[1]:
i = 2
force = ['-f']
else:
i = 1
force = []
url = sys.argv[i]
subprocess.check_call([hg_cmd, 'import'] + force + ['--no-commit', url])
webFile = urllib.urlopen(url)
for line in webFile.readlines():
# detect file name
m = file_name_re.search(line)
if m:
file_name = m.group(1)
print '___ %s' % file_name
# detect deleted file
m = deleted_re.search(line)
if m:
subprocess.check_call([hg_cmd, 'rm', '-f', file_name])
# detect moved file
m = fp.search(line)
if m:
hg_from = m.group(1)
m = tp.search(line)
if m:
hg_to = m.group(1)
subprocess.check_call([hg_cmd, 'mv', '-f', hg_from, hg_to])
# detect copied file
m = fcp.search(line)
if m:
hg_from = m.group(1)
m = tcp.search(line)
if m:
hg_to = m.group(1)
subprocess.check_call([hg_cmd, 'cp', hg_from, hg_to])
subprocess.check_call([hg_cmd, 'revert', '--no-backup', hg_from])
webFile.close()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
import urllib
import sys, pickle, logging
from cStringIO import StringIO
import conf
def encrypt(pword):
return 'S'.join(map(lambda x: '%2x'%ord(x), pword))
def decrypt(pword):
return ''.join(map(lambda x: chr(int(x, 16)), pword.split('S')))
class LoginDialog(wx.Dialog):
def __init__(self, parent, id, title):
wx.Dialog.__init__(self, parent, id, title, size=(250, 210))
(user, pword) = conf.loadConf()
self.user = user
self.password = pword
panel = wx.Panel(self, -1)
vbox = wx.BoxSizer(wx.VERTICAL)
vbox.Add(panel)
self.addInput(vbox, u'学号', user, 0, self.onUser)
self.addInput(vbox, u'密码', pword, wx.TE_PASSWORD, self.onPassword)
hbox = wx.BoxSizer(wx.HORIZONTAL)
btnOk = wx.Button(self, wx.ID_OK, u'登陆')
btnOk.SetDefault()
btnCancel = wx.Button(self, wx.ID_CANCEL, u'退出')
hbox.Add(btnOk, 1)
hbox.Add(btnCancel, 1, wx.LEFT, 5)
vbox.Add(hbox, 1, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 10)
self.SetSizer(vbox)
def addInput(self, vbox, label, text, style, hook):
hbox = wx.BoxSizer(wx.HORIZONTAL)
hbox.Add(wx.StaticText(self, -1, label), 0, wx.ALIGN_CENTER | wx.ALL, 5)
text = wx.TextCtrl(self, -1, text, size = (80, -1), style = style)
text.Bind(wx.EVT_TEXT, hook)
hbox.Add(text, 1, wx.ALIGN_CENTER | wx.ALL, 5)
vbox.Add(hbox, 0, wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
def onUser(self, event):
self.user = event.GetString()
def onPassword(self, event):
self.password = event.GetString()
def getValue(self):
return (self.user, self.password)
class TestFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(550,500))
panel = wx.Panel(self, -1)
wx.Button(panel, 1, 'Show', (100, 100))
self.Bind(wx.EVT_BUTTON, self.OnShowDialog, id=1)
def OnShowDialog(self, event):
dia = LoginDialog(self, -1, u'登陆')
if dia.ShowModal() == wx.ID_OK:
conf.saveConf(dia.getValue())
dia.Destroy()
if __name__ == '__main__':
app = wx.App()
frame = TestFrame(None, -1, 'dialog.py')
frame.Show(True)
frame.Centre()
app.MainLoop()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib, cookielib, urllib2
import sys, logging, os
from sgmllib import SGMLParser
loginURL = "https://uis1.fudan.edu.cn/amserver/UI/Login?goto=http://www.urp.fudan.edu.cn/index.portal"
scoreURL = "http://www.urp.fudan.edu.cn:84/epstar/app/fudan/ScoreManger/ScoreViewer/Student/Course.jsp"
logoutURL = "http://www.urp.fudan.edu.cn/logout.jsp"
def getHTML(user, passwd, captcha = None):
sys.stdout.flush()
cookie = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
urllib2.install_opener(opener)
str = urllib.urlencode({'IDToken1': user, 'IDToken2': passwd})
sock1 = urllib2.urlopen(loginURL, str)
loginHTML = sock1.read()
logging.debug(loginHTML)
sock1.close()
sock2 = urllib2.urlopen(scoreURL)
scoreHTML = sock2.read()
logging.debug(scoreHTML)
sock2.close()
sock3 = urllib2.urlopen(logoutURL)
sock3.close()
return scoreHTML
class URPParser(SGMLParser):
def reset(self):
self.tdOpen = False
self.strongOpen = False
self.list = []
self.started = True
SGMLParser.reset(self)
def start_strong(self, attrs):
self.strongOpen = True
def end_strong(self):
self.strongOpen = False
def start_tr(self, attrs):
self.row = []
def end_tr(self):
if self.started and self.row != []:
self.list.append(self.row)
self.row = []
def start_td(self, attrs):
for (k, v) in attrs:
if (k == "align"):
self.tdOpen = True
break
def end_td(self):
self.tdOpen = False
def handle_data(self, text):
if (self.tdOpen):
if (len(text.strip()) > 0):
self.row.append(text.strip())
def result(self):
return self.list
if __name__ == '__main__':
if os.path.exists('gpa.html'):
f = open('gpa.html', 'r')
html = f.read()
f.close()
else:
user = raw_input('username: ')
pword = raw_input('password: ')
html = getHTML(user, pword)
open('gpa.html', 'w').write(html)
parser = URPParser()
parser.feed(html)
result = parser.result()
for line in result:
print ", ".join(str.decode('utf-8').encode('gbk') for str in line) | Python |
from distutils.core import setup
import py2exe
setup(
name = 'gpa',
console = ['main.py'],
author = 'Wang Yuanxuan',
)
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
import wx.grid as gridlib
import logging, conf
useLocalData = False
data = []
grade = []
class MyDataTable(gridlib.PyGridTableBase):
def __init__(self, log):
gridlib.PyGridTableBase.__init__(self)
initGrade()
initTags()
self.colLabels = ['序号', '学期', '选课号', '课程代码', '课程名称',
'学分', '成绩', '专业课']
self.dataTypes = [gridlib.GRID_VALUE_STRING] * 8
self.data = []
for line in data[1:]:
dline = line[:]
while len(self.data) > 1 and len(dline) < len(self.data[0]) - 1:
dline.append('')
dline.append('')
self.data.append(dline)
def GetNumberRows(self):
return len(self.data) + 1
def GetNumberCols(self):
return len(self.data[0])
def IsEmptyCell(self, row, col):
try:
return not self.data[row][col]
except IndexError:
return True
def GetValue(self, row, col):
try:
return self.data[row][col].decode('utf-8')
except UnicodeEncodeError:
if not self.data[row][col]:
return ''
return self.data[row][col]
except AttributeError:
return ''
except IndexError:
return ''
def SetValue(self, row, col, value):
def innerSetValue(row, col, value):
try:
self.data[row][col] = value
except IndexError:
# add a new row
self.data.append([''] * self.GetNumberCols())
innerSetValue(row, col, value)
# tell the grid we've added a row
msg = gridlib.GridTableMessage(self, # The table
gridlib.GRIDTABLE_NOTIFY_ROWS_APPENDED, # what we did to it
1 # how many
)
self.GetView().ProcessTableMessage(msg)
innerSetValue(row, col, value)
def GetColLabelValue(self, col):
try:
return self.colLabels[col].decode('utf-8')
except:
return self.colLabels[col]
def GetTypeName(self, row, col):
return self.dataTypes[col]
def CanGetValueAs(self, row, col, typeName):
colType = self.dataTypes[col].split(':')[0]
if typeName == colType:
return True
else:
return False
def CanSetValueAs(self, row, col, typeName):
return self.CanGetValueAs(row, col, typeName)
class MyTableGrid(gridlib.Grid):
def __init__(self, parent, log, frame):
gridlib.Grid.__init__(self, parent, -1)
self.sortBy = 0
self.frame = frame
table = self.table = MyDataTable(log)
self.SetTable(table, True)
self.SetRowLabelSize(0)
self.SetMargins(0, 0)
self.AutoSizeColumns(False)
width = (50, 170, 120, 120, 150, 50, 50, 50)
for i, w in enumerate(width):
self.SetColSize(i, w)
self.colors = [(wx.WHITE, wx.GREEN), (wx.BLACK, wx.WHITE), (wx.CYAN, wx.WHITE),
(wx.BLUE, wx.WHITE), (wx.RED, wx.WHITE), (wx.BLACK, wx.WHITE)]
self.resetColor()
gridlib.EVT_GRID_CELL_LEFT_CLICK(self, self.OnLeftClick)
gridlib.EVT_GRID_LABEL_LEFT_CLICK(self, self.OnLabelClick)
def OnLabelClick(self, evt):
col = evt.GetCol()
if self.sortBy % 100 == col:
self.sortBy = (self.sortBy + 100) % 200
else:
self.sortBy = col
logging.debug('Label %d clicked, sortBy = %d' % (evt.GetCol(), self.sortBy))
reverse = 1 if self.sortBy >= 100 else -1
self.table.data.sort(lambda x, y: reverse * cmp(x[col], y[col]))
self.resetColor()
def OnLeftClick(self, evt):
row = evt.GetRow()
col = evt.GetCol()
col = self.table.GetNumberCols() - 1
if col == self.table.GetNumberCols() - 1:
if self.GetCellValue(row, col) == '':
self.SetCellValue(row, col, u'是')
else:
self.SetCellValue(row, col, '')
self.frame.refreshDisplay()
def resetColor(self, evt = None):
''' Reset row colors. attrlist is rebuilt at each call, since if we remove
the rebuilding routines there will be exceptions
'''
try:
grade = map(lambda x: conf.letterToPoint(x[6]), self.table.data)
except Exception, e:
logging.error(e)
attrlist = []
for i, (fg, bg) in enumerate(self.colors):
attr = gridlib.GridCellAttr()
attr.SetBackgroundColour(bg)
attr.SetTextColour(fg)
attrlist.append(attr)
if self.frame.cbxColor.IsChecked():
for i, y in enumerate(grade):
if y < 0:
continue
else:
self.SetRowAttr(i, attrlist[int(y + 0.5)])
else:
for i, y in enumerate(grade):
if y < 0:
continue
else:
self.SetRowAttr(i, attrlist[-1])
self.Refresh()
class MyFrame(wx.Frame):
def __init__(self, parent, log):
wx.Frame.__init__(self, parent, -1, u'绩点查询工具 %s' % conf.version, size=(900, 640))
p = wx.Panel(self, -1, style = 0)
self.cbxColor = wx.CheckBox(p, -1, u'颜色区别')
self.cbxColor.SetValue(False)
grid = self.grid = MyTableGrid(p, log, self)
bsLeft = wx.BoxSizer(wx.VERTICAL)
bsRight = wx.BoxSizer(wx.VERTICAL)
bs = wx.BoxSizer(wx.HORIZONTAL)
fontLabel = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName=u'楷体_GB2312')
fontScore = wx.Font(14, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
fontAuthor = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
lblGPA = wx.StaticText(p, -1, u'总绩点')
lblGPA.SetFont(fontLabel)
lblGPAS = wx.StaticText(p, -1, u'专业课绩点')
lblGPAS.SetFont(fontLabel)
lblCredit = wx.StaticText(p, -1, u'总学分')
lblCredit.SetFont(fontLabel)
lblCreditS = wx.StaticText(p, -1, u'专业课学分')
lblCreditS.SetFont(fontLabel)
txtPointAll = self.txtPointAll = wx.StaticText(p, -1, '')
txtPointAll.SetFont(fontScore)
txtPointAll.SetForegroundColour('red')
txtPointSpec = self.txtPointSpec = wx.StaticText(p, -1, '')
txtPointSpec.SetFont(fontScore)
txtPointSpec.SetForegroundColour('red')
txtCredit = self.txtCredit = wx.StaticText(p, -1, '')
txtCredit.SetFont(fontScore)
txtCredit.SetForegroundColour('red')
txtCreditS = self.txtCreditS = wx.StaticText(p, -1, '')
txtCreditS.SetFont(fontScore)
txtCreditS.SetForegroundColour('red')
txtLabel3 = wx.StaticText(p, -1, u'批量选择')
btnSelectAll = wx.Button(p, -1, u'全选')
btnDeselectAll = wx.Button(p, -1, u'取消选择')
txtLabel4 = wx.StaticText(p, -1, 'by ZelluX')
txtLabel4.SetFont(fontAuthor)
bsLeft.Add(grid, 1, wx.EXPAND, 5)
bsRight.Add(lblGPA)
bsRight.Add(txtPointAll)
bsRight.Add(lblGPAS)
bsRight.Add(txtPointSpec)
bsRight.Add(lblCredit)
bsRight.Add(txtCredit)
bsRight.Add(lblCreditS)
bsRight.Add(txtCreditS)
bsRight.Add(wx.StaticLine(p), 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 5)
bsRight.Add(self.cbxColor)
bsRight.Add(wx.StaticLine(p), 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 5)
bsRight.Add(txtLabel3)
bsRight.Add(btnSelectAll)
bsRight.Add(btnDeselectAll)
btnTags = []
for tag in initTags():
btnTags.append(wx.Button(p, -1, tag))
bsRight.Add(btnTags[-1])
self.Bind(wx.EVT_BUTTON, self.selectTag(tag), btnTags[-1])
bsRight.Add(wx.StaticLine(p), 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 5)
bsRight.Add(txtLabel4)
bs.Add(bsLeft, 2, wx.GROW|wx.ALL)
bs.Add(bsRight)
p.SetSizer(bs)
self.Bind(wx.EVT_BUTTON, self.selectAll(True), btnSelectAll)
self.Bind(wx.EVT_BUTTON, self.selectAll(False), btnDeselectAll)
self.Bind(wx.EVT_CHECKBOX, grid.resetColor, self.cbxColor)
self.refreshDisplay()
def refreshDisplay(self):
self.txtPointAll.SetLabel("%.3f" % (calculate(range(len(grade)))))
slist = []
credit = creditS = 0
for i in xrange(len(grade)):
credit += int(float(self.grid.GetCellValue(i, 5)))
if self.grid.GetCellValue(i, self.grid.GetNumberCols() - 1) != '':
slist.append(int(self.grid.GetCellValue(i,0)) - 1)
creditS += int(float(self.grid.GetCellValue(i, 5)) + 0.5)
logging.debug(slist)
self.txtPointSpec.SetLabel("%.3f" % (calculate(slist)))
self.txtCredit.SetLabel("%d" % credit)
self.txtCreditS.SetLabel("%d" % creditS)
def selectAll(self, selected):
if selected:
value = u'是'
else:
value = ''
def select(evt):
col = self.grid.table.GetNumberCols() - 1
for i in xrange(len(grade)):
self.grid.SetCellValue(i, col, value)
self.refreshDisplay()
return select
def selectTag(self, tag):
def select(evt):
col = self.grid.table.GetNumberCols() - 1
for i, line in enumerate(self.grid.table.data):
if line[3].upper().startswith(tag):
self.grid.SetCellValue(i, col, u'是')
self.refreshDisplay()
return select
def initGrade():
for i, line in enumerate(data[1:]):
x = float(line[5])
y = conf.letterToPoint(line[-1])
grade.append((x, y))
def initTags():
tags = set()
for line in data[1:]:
lesson = line[3].upper()
lesson = filter(str.isalpha, lesson)
if len(lesson) > 1:
tags.add(lesson)
return tags
def calculate(list): # Poor performance, but we don't care
scores = 0.0
credits = 0.0
for i in list:
if grade[i][1] < 0: continue
scores += grade[i][0] * grade[i][1]
credits += grade[i][0]
if abs(credits) < 0.05:
return 0
return scores / credits
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pickle
import logging
logging.basicConfig(filename="debug.log", level=logging.DEBUG, filemode='w')
scores = {'A': 4, 'A-': 3.7, 'B+': 3.3, 'B': 3, 'B-': 2.7, 'C+': 2.3,
'C': 2, 'C-': 1.7, 'D': 1.3, 'D-': 1, 'F': 0, 'P': 4}
version = 'v0.3.20100217'
def encrypt(pword):
return 'S'.join(map(lambda x: '%2x'%ord(x), pword))
def decrypt(pword):
return ''.join(map(lambda x: chr(int(x, 16)), pword.split('S')))
def letterToPoint(letter):
if scores.has_key(letter):
return scores[letter]
else:
return -1
def saveConf(pair, filename='user.pickle'):
f = open(filename, 'w')
(user, pword) = pair
pickle.dump((user, encrypt(pword)), f)
f.close()
def loadConf(filename='user.pickle'):
try:
f = open(filename, 'r')
(user, pword) = pickle.load(f)
pword = decrypt(pword)
logging.debug('Load from pickle, (user, password) = ' + user + ',' + pword)
f.close()
return (user, pword)
except:
return ('', '')
| Python |
print "Hello" | Python |
import sys
sys.path.append("..")
import testutil
testutil.test() | Python |
from fdk.util import *
class ForEachFileHandler:
def handle(self, fileName, filePath):
print "fileName: %s"%fileName
print "filePath: %s"%filePath
def test():
print tabStr(2, "2 tab in front")
print "lower1stChar(AbC)=%s"%lower1stChar("AbC")
print "lower1stChar(abc)=%s"%lower1stChar("abc")
print "lower1stChar('')=%s|EOS"%lower1stChar('')
print "getFileNameFromPath(abc.txt)=%s"%getFileNameFromPath("abc.txt")
print "getFileNameFromPath(abc.txt,False)=%s"%getFileNameFromPath("abc.txt",False)
print "getFileNameFromPath(123\\abc.txt)=%s"%getFileNameFromPath("abc.txt")
print "getFileNameFromPath(123/abc.txt)=%s"%getFileNameFromPath("abc.txt")
s = "<node>\"1&&2 message\"</node>"
print "xmlEncode(%s)=%s"%(s,xmlEncode(s))
print "++++++++forEachFile++++++++"
forEachFileHandler = ForEachFileHandler()
forEachFile("C:\\Windows\\System32\\drivers\\etc", forEachFileHandler, False)
print "--------forEachFile--------" | Python |
# -*- coding: utf8 -*-
import os
# tab字符填充
def tabStr(tabnum,format,*args):
i=0
f=""
while i< tabnum:
f += "\t"
i += 1
f += format
return f % args
# 首字母小写
def lower1stChar(s):
return s[0:1].lower() + s[1:]
# 从路径中获得文件名
def getFileNameFromPath(path, hasExt=True):
index1 = path.rfind("/")
index2 = path.rfind("\\")
index = index1
if index2 > index:
index = index2
if hasExt:
return path[index+1:]
else:
return path[index+1:-4]
_XML_ENCODES = \
{
"<" :"<",
">" :">",
"&" :"&",
"'" :"'",
"\"":""",
}
def xmlEncode(text):
res = ""
length=len(text)
index = 0
while index < length:
substr = text[index:index+1]
if _XML_ENCODES.has_key(substr):
res += _XML_ENCODES[substr]
else:
res += substr
index += 1
return res
# 一般的文件写入标记
def _getFileWriteFlag():
o_flag = os.O_WRONLY|os.O_CREAT|os.O_TRUNC
try:
o_flag |= os.O_BINARY
except AttributeError:
pass
return o_flag
# 把字符串写入文件(覆盖式)
def writeFile(filePath, s):
fd = os.open(filePath, _getFileWriteFlag())
os.write(fd, s)
os.close(fd)
# 遍历文件夹下所有文件
def forEachFile(dir, handler, recursive=True):
for fileName in os.listdir(dir):
filePath = dir + '\\' + fileName
if os.path.isdir(filePath):
if recursive:
forEachFile(filePath, handler, recursive)
else:
handler.handle(fileName, filePath)
| Python |
import pygame
import data
def initsounds():
pygame.mixer.set_num_channels(4)
def loadsound(filename):
return pygame.mixer.Sound(data.load(filename))
def play_bgmusic(filename):
'plays filename as music in the background on repeat until told to stop.'
if pygame.mixer.music.get_busy():
pygame.mixer.music.fadeout(100)
pygame.mixer.music.load(data.filepath(filename))
pygame.mixer.music.play(-1)
def play_sfx(filename):
'plays a sound effect once only.'
sfx = pygame.mixer.find_channel(False)
sound = loadsound(filename)
sfx.play(sound)
| Python |
import pygame
import constants as c
import data
class Turbinepole(pygame.sprite.Sprite):
def __init__(self, x, y):
''' Creates a turbinepole, given its x and y coordinates'''
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = data.load_image("pole.png", None)
self.rect.midtop = (x, y)
def update(self, time_diff):
pass
| Python |
screen_size = (640, 480)
flags = 0
frame_time = 50
import os, sys
from os.path import dirname as d
import pygame
pygame.init()
from pygame.locals import *
import data
import albow
from albow.screen import Screen
from albow.text_screen import TextScreen
from albow.shell import Shell
from albow.resource import get_font, get_image
from albow.controls import Label, Button, Image
from albow.layout import Row, Column, Grid
class CommsException(Exception):
"used for passing information from menu."
class LevelScreen(Screen):
def __init__(self, shell, bg, levels):
Screen.__init__(self, shell)
self.shell = shell
f1 = get_font(24, 'Vera.ttf')
title = Label('*Levels*', font=f1)
def execute(text):
return Button(text, action=lambda:self.quit(text))
menu = Column([execute(name) for name, l in levels] + [
Button("Back", action=self.go_back),
], align='l')
contents = Column([title, menu,], align='l', spacing=20)
self.add_centered(contents)
contents.topleft = (300, 300)
self.bg = bg
def go_back(self):
self.parent.show_menu()
def quit(self, payload):
raise CommsException(payload)
def draw(self, surface):
surface.blit(self.bg, (0,0))
class MenuScreen(Screen):
def __init__(self, shell, bg):
Screen.__init__(self, shell)
self.shell = shell
f1 = get_font(24, 'Vera.ttf')
title = Label("*featherinyourcap*", font=f1)
def menu_button(text, screen):
return Button(text, action=lambda:shell.show_screen(screen))
menu = Column([
menu_button("Play", shell.level_menu),
menu_button("Help", shell.text_screen),
Button("Quit", action=lambda:self.quit('quit')),
], align='l')
contents = Column([title, menu,
], align='l', spacing=20)
self.add_centered(contents)
contents.topleft = (300, 300)
self.bg = bg
def draw(self, surface):
surface.blit(self.bg, (0,0))
def quit(self, payload):
raise CommsException(payload)
class DemoShell(Shell):
def __init__(self, display, bg, levels):
Shell.__init__(self, display)
self.level_menu = LevelScreen(self, bg, levels)
self.text_screen = TextScreen(self, "instruction.txt")
self.text_screen._draw = self.text_screen.draw
helpbg, _ = data.load_image('bg.png', None)
def draw(surface):
display = pygame.display.get_surface()
newbg = helpbg.copy()
display.blit(newbg, (0, 0))
self.text_screen._draw(newbg)
surface.blit(newbg, (0, 0))
self.text_screen.draw = draw
self.menu_screen = MenuScreen(self, bg)
self.set_timer(frame_time)
self.show_menu()
def show_menu(self):
self.show_screen(self.menu_screen)
def main(display, bg, levels):
shell = DemoShell(display, bg, levels)
shell.run()
| Python |
"""
levels.py
contains the definition of all the game's levels.
we can have a level generator in this file should we want random levels
generated rather than in the mainline code.
Concept for levels:
* Turbines produce X MWs (power) each
* Over the course of a level, T time, sum of turbines produce MWh (energy).
* Seagulls hitting turbines stop them spinning proportional to the momentum.
* a stopped turbine doesn't produce MWh, and hence you will have low score.
* also using the fan uses MWh, reducing your score."""
import bird
class Level(object):
turbines = [] # turbines is a list of x, y pairs for turbines.
birds = {} # a map of bird name to (SeagullType, number_in_wave).
target_percent = 0 # the target capacity percent actualoutput / maxoutput.
timelimit = 0 # the cumulative time in (s) for the level.
# first level is actually quite hard.
l1 = Level()
l1.name = 'Level 1 - Single Turbine'
l1.turbines = [(300, 300)]
l1.birds = {'seagull': (bird.Seagull, 30)}
l1.target_percent = 85
l1.timelimit = 20
l1.max_ontarget = 0
# second level could be easiest?
l2 = Level()
l2.name = 'Level 2 - Control'
l2.turbines = [(200, 200), (400, 400)]
l2.birds = {'seagull': (bird.Seagull, 30)}
l2.target_percent = 93
l2.timelimit = 20
l2.max_ontarget = 3
# Level 3. A hard level!
l3 = Level()
l3.name = 'Level 3 - Conflict'
l3.turbines = [(100, 100), (300, 200), (500, 400)]
l3.birds = {'seagull': (bird.Seagull, 30),
'parrot': (bird.Parrot, 100)}
l3.target_percent = 93
l3.timelimit = 40
l3.max_ontarget = 3
# Level 4. new birds.
l4 = Level()
l4.name = 'Level 4 - Hallet WF'
l4.turbines = ([(x*100, 100) for x in range(1, 3)]
+ [(100, 350), (450, 400)])
l4.birds = {'seagull': (bird.Seagull, 40),
'parrot': (bird.Parrot, 100),
'black swan': (bird.BlackSwan, 400)}
l4.target_percent = 94
l4.timelimit = 40
l4.max_ontarget = 3
levels = [l1, l2, l3, l4]
| Python |
"""
A rudimentary bird.
Aims:
* Get the bird to animate a 'flapping' motion.
* Make it not look like all the bloody birds flap in unision.
* on a collision \w air the bird's accy is increased up or down.
* need some fancy trickery to make this a temporary accel.
perhap some time delayed update?
"""
import pygame
from pygame.locals import *
import data
import math
import constants as c
import air
import animation as anim
import sounds
class Bird(pygame.sprite.Sprite):
def __init__(self, x, y, animgroup):
'''initial position and initial velocity in x and y dir.
initial acceleration is assumed to be 0'''
pygame.sprite.Sprite.__init__(self)
self.rect = self.img_up.get_rect()
# set some transparency.
transparent = self.img_up.get_at((0, 0))
self.img_up.set_colorkey(transparent)
transparent = self.img_down.get_at((0, 0))
self.img_down.set_colorkey(transparent)
# set the current and next image. This means we can only
# have a two part flap (not say a series of 10.)
self.image = self.img_up
self.x, self.y = (x, y)
self.rect.topleft = (self.x, self.y)
self._nxt_image = self.img_down
# set initial velocities.
self.velx, self.vely = self.v[0]/1000.0, self.v[1]/1000.0
self.vely_orig = self.vely
self._updates = {'time': self._timeupdate}
# keep a count of how many frames have passed.
# for updating bird flaps.
self._frames = 0
self._animgroup = animgroup
def update(self, kwargs):
'''bird accepts an update each frame.
after a certain number of frames, bird changes image.'''
# check if the bird image needs to change.
self._frames = (self._frames + 1) % c.BIRD_FLAPUPDATE
if not self._frames:
# if it is time for a new flap. use this dirty round
# robin to change the images over.
temp = self.image
self.image = self._nxt_image
self._nxt_image = temp
# a register construct. I keep a map of all the functions
# and update keywords in _updates. Then I run any of the
# update functions for which a keyword was sent...
#
# example.. I called update: bird.update({'time': 0.1})
# this would call the function registered in _updates
# under 'time' and run it with 0.1 as the argument.
for kw, value in kwargs.items():
fn = self._updates.get(kw, self._default)
fn(value)
def kill(self):
"override kill to create an animation."
pos = self.rect.topleft
pygame.sprite.Sprite.kill(self)
death_anim = anim.Animation('bird_die.png', pos, 100)
self._animgroup.add(death_anim)
def _default(self, *args):
' a do nothing function. harmless'
pass
def _timeupdate(self, time):
# calculate change in x position.
self.x = self.x + time * self.velx
# calculate change in y position, allowing for air resistance
# proportional to velocity
self.y = self.y + time * self.vely
self.vely = self.vely - c.MU * (self.vely - self.vely_orig)
# apply the change
self.rect.topleft = (self.x, self.y)
def collide(self, other):
'bird has collided with another object. air or windfarm'
if isinstance(other, air.Air):
# collided with the air, elastic collision
self.vely = self.vely + other.m*other.v/self.m
sounds.play_sfx('bird_hit.wav')
class Seagull(Bird):
def __init__(self, *args, **kws):
self.m = 9.0
self.v = -100, 0
ld_img = data.load_image
self.img_up = ld_img("bird_flap_up.png", None)[0]
self.img_down = ld_img("bird_flap_down.png", None)[0]
Bird.__init__(self, *args, **kws)
def make_birdclass(mass, velocity, colour, alpha):
class GenericBird(Bird):
def __init__(self, *args, **kws):
self.m = mass
self.v = velocity
ld_img = data.load_image
self.img_up = ld_img("bird_flap_up.png", None)[0]
self.img_down, rect = ld_img("bird_flap_down.png", None)
mask = self.img_up.copy()
mask.fill(colour)
mask.set_alpha(alpha)
self.img_up.blit(mask, (0, 0))
self.img_down.blit(mask, (0, 0))
Bird.__init__(self, *args, **kws)
return GenericBird
Eagle = make_birdclass(15.0, (-100, 0), (200, 170, 149), 200)
Parrot = make_birdclass(5.0, (-130, 0), (190, 10, 0), 200)
BlackSwan = make_birdclass(13.0, (-150, 0), (0, 0, 0), 100)
| Python |
'''
featherinyourcap
A game by Karl Urdevics and Jervis Whitley.
Released under the MIT license (see README.txt for details, tnx.)
havfunbye.
'''
import sys
import data
import pygame
pygame.mixer.pre_init(44100, -16, 2, 1024*3)
from pygame.locals import *
from random import randint, choice
import random
import math
import constants as c
import fan
import air
import bird
import scorebar
import animation as anim
import levels
import turbine
import turbinepole
import menu
import popup
import sounds
import thebonus
def main():
pygame.init()
sounds.play_bgmusic('enemy.xm')
# set up a hello world screen and background
display = pygame.display.set_mode(c.RESOLUTION)
pygame.display.set_caption('featherinyourcap')
pygame.mouse.set_visible(1)
# a list of levels located in the levels module.
level_list = [(l.name, l) for l in levels.levels]
menubg, _= data.load_image("menu_bg.png", None)
# show the menu screen.
while True:
# reset game stats if someone presses quit!
gamestats = GameStats()
try:
menu.main(display, menubg, level_list)
except menu.CommsException:
# user has selected something.
msg = get_msg_from_last_exception()
try:
index = list(zip(*level_list)[0]).index(msg)
except ValueError: # user may have entered 'quit' - not a level.
break
completed = []
for name, level in level_list[index:]:
running = True
attempts = 0
while running:
try:
output, stats = runlevel(level, display).next()
attempts += 1
try:
stats.attempts = attempts
except AttributeError:
pass
except StopIteration:
# user really wants to quit!!
return
# now check the type of bloody output.
if output == 'success':
bonuses = gamestats.update(stats, True)
stats.bonus = bonuses
popup.success_or_fail(display, True, stats)
if not name in completed:
completed.append(name)
break
elif output == 'quit':
# some kind of 'are u sure' crap here.
running = False
elif output == 'failure':
bonuses = gamestats.update(stats, False)
stats.bonus = bonuses
popup.success_or_fail(display, False, stats)
# retry the level sonny!!
continue
else:
raise Exception("WHAT is %s" % output)
if not running:
break
if running and len(completed) == len(level_list):
# user completed the game in one sitting!
#sounds.play_bgmusic('ateam.ogg')
popup.game_completed(display)
def runlevel(config, display):
"""run each of the levels.
config should define.
* number of birds. dictionary of birdtypes and numbers
* (x, y) of turbines in a list.
* number to die for failure.
game is essentially...
put turbines in their place.
make bird of given type until no more required.
track birds that have died.
exit when too many birds died.
"""
background, background_rect = data.load_image("bg.png", None)
# set up our status text message
if pygame.font:
# some monkey patching for exe
if 'python' not in sys.executable and not hasattr(pygame.font, '_Font'):
pygame.font._Font = pygame.font.Font
def f(item, size):
pth = data.filepath('Vera.ttf')
return pygame.font._Font(item or pth, size-10)
pygame.font.Font = f
font = pygame.font.Font(None, 36)
# the initial filling default black to the background.
pygame.display.flip()
# a clock to limit our FPS.
clk = pygame.time.Clock()
# generic sprite group.
fans = pygame.sprite.Group()
# bird group.
birds = pygame.sprite.Group()
# air group
airs = pygame.sprite.Group()
# bird group.
birds = pygame.sprite.Group()
# turbine group
turbines = pygame.sprite.Group()
# turbinepoles group
turbinepoles = pygame.sprite.Group()
# a default screen sprite for collision (i.e is sprite on screen.)
screen_sprite = pygame.sprite.Sprite()
screen_sprite.rect = display.get_rect()
# the top bar of the screen for showing score etc..
scores = pygame.sprite.Group()
showscore = pygame.sprite.Group()
scoresprite = scorebar.Scorebar()
# a hidden bottom bar for stopping birds too low.
_bottombar = scorebar.Scorebar()
_bottombar.rect.topleft = (0, c.YMAX - 1)
scores.add(scoresprite)
showscore.add(scoresprite)
scores.add(_bottombar)
# for animations.
animations = pygame.sprite.Group()
# created a fan class and added it to the sprite group.
myfan = fan.Fan()
fans.add(myfan)
# a local copy of the birddict from config.
levelbirds = config.birds.copy()
def make_turbines(group, turbine_coords):
for x, y in turbine_coords:
group.add(turbine.Turbine(x, y))
make_turbines(turbines, config.turbines)
# create turbinepole sprites
for t in turbines:
turbinepoles.add(turbinepole.Turbinepole(t.rect.centerx,
t.rect.centery))
# create a timer to set off events for birds to update.
pygame.time.set_timer(c.BIRDUPDATE, c.BIRDRATE)
# game data.
saved = 0
dead = 0
kWh = 0
total_time = 0
# targetkWh calculate theoretical maximum first.
maxkWh = config.timelimit * c.TURBINE_kW * len(turbines) / 3600.0
target_kWh = round(maxkWh * config.target_percent / 100.0, 1)
config.target_kWh = target_kWh
# create a popup to show the user the level instructions.
popup.popup(display, config)
time_last = pygame.time.get_ticks()
running = True
# main game loop.
while running:
# slow the frame rate to FPS - FPS too high = bad results
clk.tick(c.FPS)
# update teh time difference
time_current = pygame.time.get_ticks()
time_diff = time_current - time_last
time_last = time_current
total_time += time_diff
# dirtily erase the entire screen, only to reblit things later.
display.blit(background, (0, 0))
# handle events
# this is the NUTS AND GUTS of the game
airs_made = 0
for event in pygame.event.get():
if event.type == QUIT:
running = False
break
if event.type == KEYDOWN:
if event.key == K_q:
yield 'quit', None
if event.type == MOUSEBUTTONDOWN:
for f in fans:
fan_ready = f.click(event.button)
if event.button == 1:
airs.add(air.Air(c.BLOW, 0.0, 400.0, 10.0))
elif event.button == 3:
airs.add(air.Air(c.SUCK, 0.0, 400.0, 10.0))
airs_made += 1
if event.type == c.BIRDUPDATE:
birds.update({})
if event.type == c.EVENT_FAN_TIMEOUT:
myfan.timeout()
# handle updating sprites.
# step 1. update the fan with mouse position.
fans.update(time_diff)
birds.update({'time': time_diff})
airs.update(time_diff)
scores.update({'dead birds': dead,
'saved birds': saved,
'time elapsed': str(round(total_time/1000.0, 1)),
'kWh generated': str(round(kWh, 1))})
animations.update({'time': time_diff})
turbines.update(time_diff)
# make a random bird up to the limit specified in the config.
try:
# this next random.choice raises IndexError when no birds left.
birdname = random.choice(levelbirds.keys())
# how many birds on target.
badbirds = ontarget(birds, turbines)
if badbirds > config.max_ontarget:
raise IndexError("Too many birds on target, no more!")
except IndexError:
# no more birds left to make!!
pass
else:
BirdType, birdchance = levelbirds[birdname]
y = make_bird(birds, animations, BirdType, birdchance)
if y:
# check the if the y is in line with a turbine.
# and credit with a bonus to allow a single shot to save bird.
kWh += sum(t.rect.top < y and t.rect.bottom > y
for t in turbines) * c.BIRD_BONUS
# remove sprites that are no longer on the screen.
saved += remove_offscreen_sprites(screen_sprite, birds)
remove_offscreen_sprites(screen_sprite, airs)
bounce_topscreen_sprites(scores, birds)
dead += handle_collision(birds, turbines, perpixel=True)
# update the kWh this will be replaced with something more robust soon.
for t in turbines:
kWh += time_diff / 1000.0 / 3600 * t.output
# subtract an amount for the airs created.
kWh -= airs_made * c.AIRS_COST
class Gameobj:pass
'if we need to expand this stats concept this class will need to move.'
g = Gameobj()
g.target_kWh = target_kWh
g.total_kWh = round(kWh, 1)
g.saved = saved
g.dead = dead
g.bonus = []
if (round(kWh, 1) >= round(target_kWh)
and total_time / 1000.0 > config.timelimit):
yield 'success', g
# failure is when no time remaining already checked the kWh.
if total_time / 1000.0 > config.timelimit:
yield 'failure', g
handle_collision(birds, airs)
# draw fps to display.
#handle_fps(time_diff, scoresprite)
# dirty way to draw everything directly to the main display.
for group in [turbinepoles, fans, airs, birds,
showscore, animations, turbines]:
group.draw(display)
# now show.
pygame.display.flip()
def handle_collision(birds, other, perpixel=None):
'handle collisions between birds and some other group.'
hitmap = pygame.sprite.groupcollide(birds, other, False, False)
dead = []
for bird, others in hitmap.items():
if perpixel:
# now find the things that bird hit on a perpixel basis.
collide_mask = pygame.sprite.collide_mask
hit = pygame.sprite.spritecollide(bird, others, False, collide_mask)
else:
hit = others
for o in hit:
dead.append(o)
bird.collide(o)
o.collide(bird)
return len(dead)
def bounce_topscreen_sprites(other, group):
'sprites have elastic collision with other (assumed to be walls).'
hitmap = pygame.sprite.groupcollide(other, group, False, False)
for wall, birds in hitmap.items():
for bird in birds:
# perfect elastic collision with infinite mass object (wall).
bird.vely = -bird.vely
def remove_offscreen_sprites(screen, group):
onscreen = pygame.sprite.spritecollide(screen, group, dokill=False)
# find those that are not in the onscreen group.
offscreen = set(onscreen) ^ set(group)
group.remove(offscreen)
return len(offscreen)
def make_bird(birds, animgroup, BirdType, birdchance):
'a random chance to make a bird and place in the birds group.'
if not randint(0, birdchance):
# make a bird with 1 in 101 chance.
x = c.XMAX - 100
y = randint(100, c.YMAX / 2)
birds.add(BirdType(x, y, animgroup))
return y
return None
def ontarget(birds, turbines):
'how many birds are on target to hit turbine .. roughly..'
willcollide = 0
for b in birds:
willcollide += sum(t.rect.top < b.y and t.rect.bottom > b.y
for t in turbines)
return willcollide
class GameStats(object):
'just a holder for all our end game stats. used as singleton'
total_kWh = 0
bonuses = []
dead = 0
saved = 0
attempts = 0
def update(self, stats, success):
'update our internal stats with some new ones.'
if success:
self.total_kWh += getattr(stats, 'total_kWh', 0)
self.bonuses += getattr(stats, 'bonus', [])
self.dead += getattr(stats, 'dead', 0)
self.saved += getattr(stats, 'saved', 0)
self.attempts += getattr(stats, 'attempts', 1)
# did the user get a bonus?
return thebonus.get_bonuses(self, stats)
def get_msg_from_last_exception():
return sys.exc_info()[1].args[0]
| Python |
import sys
from pygame import Rect, draw
from pygame.locals import K_RETURN, K_KP_ENTER, K_ESCAPE, K_TAB
from pygame.mouse import set_cursor
from pygame.cursors import arrow as arrow_cursor
from vectors import add, subtract
from utils import frame_rect
import theme
from theme import ThemeProperty, FontProperty
debug_rect = False
debug_tab = True
root_widget = None
current_cursor = None
def overridable_property(name, doc = None):
"""Creates a property which calls methods get_xxx and set_xxx of
the underlying object to get and set the property value, so that
the property's behaviour may be easily overridden by subclasses."""
getter_name = intern('get_' + name)
setter_name = intern('set_' + name)
return property(
lambda self: getattr(self, getter_name)(),
lambda self, value: getattr(self, setter_name)(value),
None,
doc)
def rect_property(name):
def get(self):
return getattr(self._rect, name)
def set(self, value):
r = self._rect
old_size = r.size
setattr(r, name, value)
new_size = r.size
if old_size <> new_size:
self._resized(old_size)
return property(get, set)
class Widget(object):
# rect Rect bounds in parent's coordinates
# parent Widget containing widget
# subwidgets [Widget] contained widgets
# focus_switch Widget subwidget to receive key events
# fg_color color or None to inherit from parent
# bg_color color to fill background, or None
# visible boolean
# border_width int width of border to draw around widget, or None
# border_color color or None to use widget foreground color
# tab_stop boolean stop on this widget when tabbing
# anchor string of 'ltrb'
font = FontProperty('font')
fg_color = ThemeProperty('fg_color')
bg_color = ThemeProperty('bg_color')
border_width = ThemeProperty('border_width')
border_color = ThemeProperty('border_color')
sel_color = ThemeProperty('sel_color')
margin = ThemeProperty('margin')
_visible = True
tab_stop = False
enter_response = None
cancel_response = None
anchor = 'lt'
debug_resize = False
def __init__(self, rect = None, **kwds):
if rect and not isinstance(rect, Rect):
raise TypeError("Widget rect not a pygame.Rect")
self._rect = Rect(rect or (0, 0, 100, 100))
self.parent = None
self.subwidgets = []
self.focus_switch = None
self.is_modal = False
self.set(**kwds)
def set(self, **kwds):
for name, value in kwds.iteritems():
if not hasattr(self, name) and not name in dir(self):
raise TypeError("Unexpected keyword argument '%s'" % name)
setattr(self, name, value)
def get_rect(self):
return self._rect
def set_rect(self, x):
old_size = self._rect.size
self._rect = Rect(x)
self._resized(old_size)
# def get_anchor(self):
# if self.hstretch:
# chars ='lr'
# elif self.hmove:
# chars = 'r'
# else:
# chars = 'l'
# if self.vstretch:
# chars += 'tb'
# elif self.vmove:
# chars += 'b'
# else:
# chars += 't'
# return chars
#
# def set_anchor(self, chars):
# self.hmove = 'r' in chars and not 'l' in chars
# self.vmove = 'b' in chars and not 't' in chars
# self.hstretch = 'r' in chars and 'l' in chars
# self.vstretch = 'b' in chars and 't' in chars
#
# anchor = property(get_anchor, set_anchor)
resizing_axes = {'h': 'lr', 'v': 'tb'}
resizing_values = {'': [0], 'm': [1], 's': [0, 1]}
def set_resizing(self, axis, value):
chars = self.resizing_axes[axis]
anchor = self.anchor
for c in chars:
anchor = anchor.replace(c, '')
for i in self.resizing_values[value]:
anchor += chars[i]
self.anchor = anchor + value
def _resized(self, (old_width, old_height)):
new_width, new_height = self._rect.size
dw = new_width - old_width
dh = new_height - old_height
if dw or dh:
self.resized(dw, dh)
def resized(self, dw, dh):
if self.debug_resize:
print "Widget.resized:", self, "by", (dw, dh), "to", self.size
for widget in self.subwidgets:
widget.parent_resized(dw, dh)
def parent_resized(self, dw, dh):
debug_resize = self.debug_resize or self.parent.debug_resize
if debug_resize:
print "Widget.parent_resized:", self, "by", (dw, dh)
left, top, width, height = self._rect
move = False
resize = False
anchor = self.anchor
if dw and 'r' in anchor:
if 'l' in anchor:
resize = True
width += dw
else:
move = True
left += dw
if dh and 'b' in anchor:
if 't' in anchor:
resize = True
height += dh
else:
move = True
top += dh
if resize:
if debug_resize:
print "Widget.parent_resized: changing rect to", (left, top, width, height)
self.rect = (left, top, width, height)
elif move:
if debug_resize:
print "Widget.parent_resized: moving to", (left, top)
self._rect.topleft = (left, top)
rect = property(get_rect, set_rect)
left = rect_property('left')
right = rect_property('right')
top = rect_property('top')
bottom = rect_property('bottom')
width = rect_property('width')
height = rect_property('height')
size = rect_property('size')
topleft = rect_property('topleft')
topright = rect_property('topright')
bottomleft = rect_property('bottomleft')
bottomright = rect_property('bottomright')
midleft = rect_property('midleft')
midright = rect_property('midright')
midtop = rect_property('midtop')
midbottom = rect_property('midbottom')
center = rect_property('center')
centerx = rect_property('centerx')
centery = rect_property('centery')
def get_visible(self):
return self._visible
def set_visible(self, x):
self._visible = x
visible = overridable_property('visible')
def add(self, arg):
if arg:
if isinstance(arg, Widget):
arg.set_parent(self)
else:
for item in arg:
self.add(item)
def add_centered(self, widget):
w, h = self.size
widget.center = w // 2, h // 2
self.add(widget)
def remove(self, widget):
if widget in self.subwidgets:
widget.set_parent(None)
def set_parent(self, parent):
if parent is not self.parent:
if self.parent:
self.parent._remove(self)
self.parent = parent
if parent:
parent._add(self)
def _add(self, widget):
self.subwidgets.append(widget)
def _remove(self, widget):
self.subwidgets.remove(widget)
if self.focus_switch is widget:
self.focus_switch = None
def draw_all(self, surface):
if self.visible:
bg = self.bg_color
if bg:
surface.fill(bg)
self.draw(surface)
bw = self.border_width
if bw:
bc = self.border_color or self.fg_color
r = surface.get_rect()
#r.inflate_ip(1 - bw, 1 - bw)
#draw.rect(surface, bc, r, bw)
frame_rect(surface, bc, r, bw)
surf_rect = surface.get_rect()
for widget in self.subwidgets:
sub_rect = widget.rect
if debug_rect:
print "Widget: Drawing subwidget %s of %s with rect %s" % (
widget, self, sub_rect)
sub_rect = surf_rect.clip(sub_rect)
if sub_rect.width > 0 and sub_rect.height > 0:
try:
sub = surface.subsurface(sub_rect)
except ValueError, e:
if str(e) == "subsurface rectangle outside surface area":
self.diagnose_subsurface_problem(surface, widget)
else:
raise
else:
widget.draw_all(sub)
self.draw_over(surface)
def diagnose_subsurface_problem(self, surface, widget):
mess = "Widget %s %s outside parent surface %s %s" % (
widget, widget.rect, self, surface.get_rect())
sys.stderr.write("%s\n" % mess)
surface.fill((255, 0, 0), widget.rect)
def draw(self, surface):
pass
def draw_over(self, surface):
pass
def find_widget(self, pos):
for widget in self.subwidgets[::-1]:
if widget.visible:
r = widget.rect
if r.collidepoint(pos):
return widget.find_widget(subtract(pos, r.topleft))
return self
def handle_mouse(self, name, event):
event.dict['local'] = self.global_to_local(event.pos)
self.call_handler(name, event)
self.setup_cursor(event)
def setup_cursor(self, event):
global current_cursor
cursor = self.get_cursor(event) or arrow_cursor
if cursor is not current_cursor:
set_cursor(*cursor)
current_cursor = cursor
def dispatch_key(self, name, event):
if self.visible:
widget = self.focus_switch
if widget:
widget.dispatch_key(name, event)
else:
self.call_handler(name, event)
else:
self.call_parent_handler(name, event)
def get_focus(self):
widget = self
while 1:
focus = widget.focus_switch
if not focus:
break
widget = focus
return widget
def notify_attention_loss(self):
widget = self
while 1:
if widget.is_modal:
break
parent = widget.parent
if not parent:
break
focus = parent.focus_switch
if focus and focus is not widget:
focus.dispatch_attention_loss()
widget = parent
def dispatch_attention_loss(self):
widget = self
while widget:
widget.attention_lost()
widget = widget.focus_switch
def attention_lost(self):
pass
def call_handler(self, name, *args):
method = getattr(self, name, None)
if method:
return method(*args)
else:
return 'pass'
def call_parent_handler(self, name, *args):
if not self.is_modal:
parent = self.parent
if parent:
parent.call_handler(name, *args)
def global_to_local(self, p):
return subtract(p, self.local_to_global_offset())
def local_to_global(self, p):
return add(p, self.local_to_global_offset())
def local_to_global_offset(self):
d = self.topleft
parent = self.parent
if parent:
d = add(d, parent.local_to_global_offset())
return d
def key_down(self, event):
k = event.key
#print "Widget.key_down:", k ###
if k == K_RETURN or k == K_KP_ENTER:
if self.enter_response is not None:
self.dismiss(self.enter_response)
return
elif k == K_ESCAPE:
if self.cancel_response is not None:
self.dismiss(self.cancel_response)
return
elif k == K_TAB:
self.tab_to_next()
return
self.call_parent_handler('key_down', event)
def key_up(self, event):
self.call_parent_handler('key_up', event)
def is_inside(self, container):
widget = self
while widget:
if widget is container:
return True
widget = widget.parent
return False
def present(self, centered = True):
#print "Widget: presenting with rect", self.rect
root = self.get_root()
if centered:
self.center = root.center
root.add(self)
root.run_modal(self)
self.dispatch_attention_loss()
root.remove(self)
#print "Widget.present: returning", self.modal_result
return self.modal_result
def dismiss(self, value = True):
self.modal_result = value
def get_root(self):
return root_widget
def get_top_widget(self):
top = self
while top.parent and not top.is_modal:
top = top.parent
return top
def focus(self):
if not self.is_modal:
parent = self.parent
if parent:
parent.focus_on(self)
def focus_on(self, subwidget):
old_focus = self.focus_switch
if old_focus is not subwidget:
if old_focus:
old_focus.dispatch_attention_loss()
self.focus_switch = subwidget
self.focus()
def has_focus(self):
return self.is_modal or (self.parent and self.parent.focused_on(self))
def focused_on(self, widget):
return self.focus_switch is widget and self.has_focus()
def shrink_wrap(self):
contents = self.subwidgets
if contents:
rects = [widget.rect for widget in contents]
#rmax = Rect.unionall(rects) # broken in PyGame 1.7.1
rmax = rects.pop()
for r in rects:
rmax = rmax.union(r)
self._rect.size = add(rmax.topleft, rmax.bottomright)
def invalidate(self):
root = self.get_root()
if root:
root.do_draw = True
def get_cursor(self, event):
return arrow_cursor
def predict(self, kwds, name):
try:
return kwds[name]
except KeyError:
return theme.root.get(self.__class__, name)
def predict_attr(self, kwds, name):
try:
return kwds[name]
except KeyError:
return getattr(self, name)
def init_attr(self, kwds, name):
try:
return kwds.pop(name)
except KeyError:
return getattr(self, name)
def predict_font(self, kwds, name = 'font'):
return kwds.get(name) or theme.root.get_font(self.__class__, name)
def get_margin_rect(self):
r = Rect((0, 0), self.size)
d = -2 * self.margin
r.inflate_ip(d, d)
return r
def set_size_for_text(self, width, nlines = 1):
if width is not None:
font = self.font
d = 2 * self.margin
if isinstance(width, basestring):
width, height = font.size(width)
width += d
else:
height = font.size("X")[1]
self.size = (width, height * nlines + d)
def tab_to_first(self):
chain = self.get_tab_order()
if chain:
chain[0].focus()
def tab_to_next(self):
top = self.get_top_widget()
chain = top.get_tab_order()
try:
i = chain.index(self)
except ValueError:
return
target = chain[(i + 1) % len(chain)]
target.focus()
def get_tab_order(self):
result = []
self.collect_tab_order(result)
return result
def collect_tab_order(self, result):
if self.tab_stop:
result.append(self)
for child in self.subwidgets:
child.collect_tab_order(result)
# def tab_to_first(self, start = None):
# if debug_tab:
# print "Enter Widget.tab_to_first:", self ###
# print "...start =", start ###
# if not self.visible:
# if debug_tab: print "...invisible" ###
# self.tab_to_next_in_parent(start)
# elif self.tab_stop:
# if debug_tab: print "...stopping here" ###
# self.focus()
# else:
# if debug_tab: print "...tabbing to next" ###
# self.tab_to_next(start or self)
# if debug_tab: print "Exit Widget.tab_to_first:", self ###
#
# def tab_to_next(self, start = None):
# if debug_tab:
# print "Enter Widget.tab_to_next:", self ###
# print "...start =", start ###
# sub = self.subwidgets
# if sub:
# if debug_tab: print "...tabbing to first subwidget" ###
# sub[0].tab_to_first(start or self)
# else:
# if debug_tab: print "...tabbing to next in parent" ###
# self.tab_to_next_in_parent(start)
# if debug_tab: print "Exit Widget.tab_to_next:", self ###
#
# def tab_to_next_in_parent(self, start):
# if debug_tab:
# print "Enter Widget.tab_to_next_in_parent:", self ###
# print "...start =", start ###
# parent = self.parent
# if parent and not self.is_modal:
# if debug_tab: print "...telling parent to tab to next" ###
# parent.tab_to_next_after(self, start)
# else:
# if self is not start:
# if debug_tab: print "...wrapping back to first" ###
# self.tab_to_first(start)
# if debug_tab: print "Exit Widget.tab_to_next_in_parent:", self ###
#
# def tab_to_next_after(self, last, start):
# if debug_tab:
# print "Enter Widget.tab_to_next_after:", self, last ###
# print "...start =", start ###
# sub = self.subwidgets
# i = sub.index(last) + 1
# if debug_tab: print "...next index =", i, "of", len(sub) ###
# if i < len(sub):
# if debug_tab: print "...tabbing there" ###
# sub[i].tab_to_first(start)
# else:
# if debug_tab: print "...tabbing to next in parent" ###
# self.tab_to_next_in_parent(start)
# if debug_tab: print "Exit Widget.tab_to_next_after:", self, last ###
def inherited(self, attribute):
value = getattr(self, attribute)
if value is not None:
return value
else:
parent = self.parent
if parent and not self.is_modal:
return parent.inherited(attribute)
def __contains__(self, event):
r = Rect(self._rect)
r.left = 0
r.top = 0
p = self.global_to_local(event.pos)
return r.collidepoint(p)
def get_mouse(self):
root = self.get_root()
return root.get_mouse_for(self)
| Python |
import os, sys
import pygame
from pygame.locals import RLEACCEL
#default_font_name = "Vera.ttf"
optimize_images = True
run_length_encode = False
def find_resource_dir():
if not 'python' in sys.executable:
path = os.path.dirname(sys.executable)
else:
path = os.path.dirname(sys.argv[0])
dir = os.path.join(path, 'gamelib')
while 1:
path = os.path.join(dir, "Resources")
if os.path.exists(path):
return path
parent = os.path.dirname(dir)
if parent == dir:
raise SystemError("albow: Unable to find Resources directory")
dir = parent
resource_dir = find_resource_dir()
image_cache = {}
font_cache = {}
sound_cache = {}
text_cache = {}
cursor_cache = {}
def resource_path(*names):
return os.path.join(resource_dir, *names)
def get_image(name, border = 0, optimize = optimize_images, noalpha = False,
rle = run_length_encode, prefix = "images"):
key = (prefix, name)
image = image_cache.get(key)
if not image:
image = pygame.image.load(resource_path(prefix, name))
if noalpha:
image = image.convert(24)
elif optimize:
image = image.convert_alpha()
if rle:
image.set_alpha(255, RLEACCEL)
if border:
w, h = image.get_size()
b = border
d = 2 * border
image = image.subsurface(b, b, w - d, h - d)
image_cache[key] = image
return image
def get_font(size, name):
key = (name, size)
font = font_cache.get(key)
if not font:
path = resource_path("fonts", name)
font = pygame.font.Font(path, size)
font_cache[key] = font
return font
class DummySound(object):
def fadeout(self, x): pass
def get_length(self): return 0.0
def get_num_channels(self): return 0
def get_volume(self): return 0.0
def play(self, *args): pass
def set_volume(self, x): pass
def stop(self): pass
dummy_sound = DummySound()
def get_sound(name):
if sound_cache is None:
return dummy_sound
sound = sound_cache.get(name)
if not sound:
try:
from pygame.mixer import Sound
except ImportError, e:
no_sound(e)
return dummy_sound
path = resource_path("sounds", name)
try:
sound = Sound(path)
except pygame.error, e:
missing_sound(e, name)
return dummy_sound
sound_cache[name] = sound
return sound
def no_sound(e):
global sound_cache
print "albow.resource.get_sound: %s" % e
print "albow.resource.get_sound: Sound not available, continuing without it"
sound_cache = None
def missing_sound(e, name):
print "albow.resource.get_sound: %s: %s" % (name, e)
def get_text(name):
text = text_cache.get(name)
if text is None:
path = resource_path("text", name)
text = open(path, "rU").read()
text_cache[name] = text
return text
#def get_default_font():
# return get_font(12)
def load_cursor(name):
image = get_image(name, prefix = "cursors")
width, height = image.get_size()
hot = (0, 0)
data = []
mask = []
rowbytes = (width + 7) // 8
xr = xrange(width)
yr = xrange(height)
for y in yr:
bit = 0x80
db = mb = 0
for x in xr:
r, g, b, a = image.get_at((x, y))
if a >= 128:
mb |= bit
if r + g + b < 383:
db |= bit
if r == 0 and b == 255:
hot = (x, y)
bit >>= 1
if not bit:
data.append(db)
mask.append(mb)
db = mb = 0
bit = 0x80
if bit <> 0x80:
data.append(db)
mask.append(mb)
return ((8 * rowbytes, height), hot, data, mask)
def get_cursor(name):
cursor = cursor_cache.get(name)
if cursor is None:
cursor = load_cursor(name)
cursor_cache[name] = cursor
return cursor
| Python |
from pygame import draw, Surface
from pygame.locals import SRCALPHA
def frame_rect(surface, color, rect, thick = 1):
surface.fill(color, (rect.left, rect.top, rect.width, thick))
surface.fill(color, (rect.left, rect.bottom - thick, rect.width, thick))
surface.fill(color, (rect.left, rect.top, thick, rect.height))
surface.fill(color, (rect.right - thick, rect.top, thick, rect.height))
def blit_tinted(surface, image, pos, tint, src_rect = None):
from Numeric import array, add, minimum
from pygame.surfarray import array3d, pixels3d
if src_rect:
image = image.subsurface(src_rect)
buf = Surface(image.get_size(), SRCALPHA, 32)
buf.blit(image, (0, 0))
src_rgb = array3d(image)
buf_rgb = pixels3d(buf)
buf_rgb[...] = minimum(255, add(tint, src_rgb)).astype('b')
buf_rgb = None
surface.blit(buf, pos)
def blit_in_rect(dst, src, frame, align = 'tl', margin = 0):
r = src.get_rect()
align_rect(r, frame, align, margin)
dst.blit(src, r)
def align_rect(r, frame, align = 'tl', margin = 0):
if 'l' in align:
r.left = frame.left + margin
elif 'r' in align:
r.right = frame.right - margin
else:
r.centerx = frame.centerx
if 't' in align:
r.top = frame.top + margin
elif 'b' in align:
r.bottom = frame.bottom - margin
else:
r.centery = frame.centery
def brighten(rgb, factor):
return [min(255, int(round(factor * c))) for c in rgb]
| Python |
################################################################
#
# Albow - Tab Panel
#
################################################################
from pygame import Rect
from widget import Widget
from theme import ThemeProperty, FontProperty
from utils import brighten
class TabPanel(Widget):
# pages [Widget]
# current_page Widget
tab_font = FontProperty('tab_font')
tab_height = ThemeProperty('tab_height')
tab_border_width = ThemeProperty('tab_border_width')
tab_spacing = ThemeProperty('tab_spacing')
tab_margin = ThemeProperty('tab_margin')
tab_fg_color = ThemeProperty('tab_fg_color')
default_tab_bg_color = ThemeProperty('default_tab_bg_color')
tab_area_bg_color = ThemeProperty('tab_area_bg_color')
tab_dimming = ThemeProperty('tab_dimming')
#use_page_bg_color_for_tabs = ThemeProperty('use_page_bg_color_for_tabs')
def __init__(self, pages = None, **kwds):
Widget.__init__(self, **kwds)
self.pages = []
self.current_page = None
if pages:
w = h = 0
for title, page in pages:
w = max(w, page.width)
h = max(h, page.height)
self._add_page(title, page)
self.size = (w, h)
self.show_page(pages[0][1])
def content_size(self):
return (self.width, self.height - self.tab_height)
def content_rect(self):
return Rect((0, self.tab_height), self.content_size())
def page_height(self):
return self.height - self.tab_height
def add_page(self, title, page):
self._add_page(title, page)
if not self.current_page:
self.show_page(page)
def _add_page(self, title, page):
page.tab_title = title
page.anchor = 'ltrb'
self.pages.append(page)
def remove_page(self, page):
try:
i = self.pages.index(page)
del self.pages[i]
except IndexError:
pass
if page is self.current_page:
self.show_page(None)
def show_page(self, page):
if self.current_page:
self.remove(self.current_page)
self.current_page = page
if page:
th = self.tab_height
page.rect = Rect(0, th, self.width, self.height - th)
self.add(page)
page.focus()
def draw(self, surf):
self.draw_tab_area_bg(surf)
self.draw_tabs(surf)
def draw_tab_area_bg(self, surf):
bg = self.tab_area_bg_color
if bg:
surf.fill(bg, (0, 0, self.width, self.tab_height))
def draw_tabs(self, surf):
font = self.tab_font
fg = self.tab_fg_color
b = self.tab_border_width
if b:
surf.fill(fg, (0, self.tab_height - b, self.width, b))
for i, title, page, selected, rect in self.iter_tabs():
x0 = rect.left
w = rect.width
h = rect.height
r = rect
if not selected:
r = Rect(r)
r.bottom -= b
self.draw_tab_bg(surf, page, selected, r)
if b:
surf.fill(fg, (x0, 0, b, h))
surf.fill(fg, (x0 + b, 0, w - 2 * b, b))
surf.fill(fg, (x0 + w - b, 0, b, h))
buf = font.render(title, True, page.fg_color or fg)
r = buf.get_rect()
r.center = (x0 + w // 2, h // 2)
surf.blit(buf, r)
def iter_tabs(self):
pages = self.pages
current_page = self.current_page
n = len(pages)
b = self.tab_border_width
s = self.tab_spacing
h = self.tab_height
m = self.tab_margin
width = self.width - 2 * m + s - b
x0 = m
for i, page in enumerate(pages):
x1 = m + (i + 1) * width // n #self.tab_boundary(i + 1)
selected = page is current_page
yield i, page.tab_title, page, selected, Rect(x0, 0, x1 - x0 - s + b, h)
x0 = x1
def draw_tab_bg(self, surf, page, selected, rect):
bg = self.tab_bg_color_for_page(page)
if not selected:
bg = brighten(bg, self.tab_dimming)
surf.fill(bg, rect)
def tab_bg_color_for_page(self, page):
return getattr(page, 'tab_bg_color', None) \
or page.bg_color \
or self.default_tab_bg_color
def mouse_down(self, e):
x, y = e.local
if y < self.tab_height:
i = self.tab_number_containing_x(x)
if i is not None:
self.show_page(self.pages[i])
def tab_number_containing_x(self, x):
n = len(self.pages)
m = self.tab_margin
width = self.width - 2 * m + self.tab_spacing - self.tab_border_width
i = (x - m) * n // width
if 0 <= i < n:
return i
| Python |
#
# Albow - Sound utilities
#
import pygame
from pygame import mixer
def pause_sound():
try:
mixer.pause()
except pygame.error:
pass
def resume_sound():
try:
mixer.unpause()
except pygame.error:
pass
def stop_sound():
try:
mixer.stop()
except pygame.error:
pass
| Python |
#
# Albow - Fields
#
from pygame import draw
from pygame.locals import K_LEFT, K_RIGHT, K_TAB
from widget import Widget
from controls import Control
#---------------------------------------------------------------------------
class TextEditor(Widget):
upper = False
tab_stop = True
_text = ""
def __init__(self, width, upper = None, **kwds):
Widget.__init__(self, **kwds)
self.set_size_for_text(width)
if upper is not None:
self.upper = upper
self.insertion_point = None
def get_text(self):
return self._text
def set_text(self, text):
self._text = text
text = property(get_text, set_text)
def draw(self, surface):
frame = self.get_margin_rect()
fg = self.fg_color
font = self.font
focused = self.has_focus()
text, i = self.get_text_and_insertion_point()
if focused and i is None:
surface.fill(self.sel_color, frame)
image = font.render(text, True, fg)
surface.blit(image, frame)
if focused and i is not None:
x, h = font.size(text[:i])
x += frame.left
y = frame.top
draw.line(surface, fg, (x, y), (x, y + h - 1))
def key_down(self, event):
k = event.key
if k == K_LEFT:
self.move_insertion_point(-1)
return
if k == K_RIGHT:
self.move_insertion_point(1)
return
if k == K_TAB:
self.attention_lost()
self.tab_to_next()
return
try:
c = event.unicode
except ValueError:
c = ""
if self.insert_char(c) == 'pass':
self.call_parent_handler('key_down', event)
def get_text_and_insertion_point(self):
text = self.get_text()
i = self.insertion_point
if i is not None:
i = max(0, min(i, len(text)))
return text, i
def move_insertion_point(self, d):
text, i = self.get_text_and_insertion_point()
if i is None:
if d > 0:
i = len(text)
else:
i = 0
else:
i = max(0, min(i + d, len(text)))
self.insertion_point = i
def insert_char(self, c):
if self.upper:
c = c.upper()
if c <= "\x7f":
if c == "\x08" or c == "\x7f":
text, i = self.get_text_and_insertion_point()
if i is None:
text = ""
i = 0
else:
text = text[:i-1] + text[i:]
i -= 1
self.change_text(text)
self.insertion_point = i
return
elif c == "\r" or c == "\x03":
return self.call_handler('enter_action')
elif c == "\x1b":
return self.call_handler('escape_action')
elif c >= "\x20":
if self.allow_char(c):
text, i = self.get_text_and_insertion_point()
if i is None:
text = c
i = 1
else:
text = text[:i] + c + text[i:]
i += 1
self.change_text(text)
self.insertion_point = i
return
return 'pass'
def allow_char(self, c):
return True
def mouse_down(self, e):
self.focus()
x, y = e.local
text = self.get_text()
font = self.font
n = len(text)
def width(i):
return font.size(text[:i])[0]
i1 = 0
i2 = len(text)
x1 = 0
x2 = width(i2)
while i2 - i1 > 1:
i3 = (i1 + i2) // 2
x3 = width(i3)
if x > x3:
i1, x1 = i3, x3
else:
i2, x2 = i3, x3
if x - x1 > (x2 - x1) // 2:
i = i2
else:
i = i1
self.insertion_point = i
def change_text(self, text):
self.set_text(text)
self.call_handler('change_action')
#---------------------------------------------------------------------------
class Field(Control, TextEditor):
# type func(string) -> value
# editing boolean
empty = NotImplemented
format = "%s"
min = None
max = None
def __init__(self, width = None, **kwds):
min = self.predict_attr(kwds, 'min')
max = self.predict_attr(kwds, 'max')
if 'format' in kwds:
self.format = kwds.pop('format')
if 'empty' in kwds:
self.empty = kwds.pop('empty')
self.editing = False
if width is None:
w1 = w2 = ""
if min is not None:
w1 = self.format_value(min)
if max is not None:
w2 = self.format_value(max)
if w2:
if len(w1) > len(w2):
width = w1
else:
width = w2
if width is None:
width = 100
TextEditor.__init__(self, width, **kwds)
def format_value(self, x):
if x == self.empty:
return ""
else:
return self.format % x
def get_text(self):
if self.editing:
return self._text
else:
return self.format_value(self.value)
def set_text(self, text):
self.editing = True
self._text = text
def enter_action(self):
if self.editing:
self.commit()
else:
return 'pass'
def escape_action(self):
if self.editing:
self.editing = False
self.insertion_point = None
else:
return 'pass'
def attention_lost(self):
self.commit()
def commit(self):
if self.editing:
text = self._text
if text:
try:
value = self.type(text)
except ValueError:
return
if self.min is not None:
value = max(self.min, value)
if self.max is not None:
value = min(self.max, value)
else:
value = self.empty
if value is NotImplemented:
return
self.value = value
self.editing = False
self.insertion_point = None
else:
self.insertion_point = None
# def get_value(self):
# self.commit()
# return Control.get_value(self)
#
# def set_value(self, x):
# Control.set_value(self, x)
# self.editing = False
#---------------------------------------------------------------------------
class TextField(Field):
type = str
class IntField(Field):
type = int
class FloatField(Field):
type = float
#---------------------------------------------------------------------------
| Python |
#
# Albow - Text Screen
#
from pygame import Rect
from pygame.locals import *
from screen import Screen
from theme import FontProperty
from resource import get_image, get_font, get_text
from vectors import add, maximum
from controls import Button
#------------------------------------------------------------------------------
class Page(object):
def __init__(self, text_screen, heading, lines):
self.text_screen = text_screen
self.heading = heading
self.lines = lines
width, height = text_screen.heading_font.size(heading)
for line in lines:
w, h = text_screen.font.size(line)
width = max(width, w)
height += h
self.size = (width, height)
def draw(self, surface, color, pos):
heading_font = self.text_screen.heading_font
text_font = self.text_screen.font
x, y = pos
buf = heading_font.render(self.heading, True, color)
surface.blit(buf, (x, y))
y += buf.get_rect().height
for line in self.lines:
buf = text_font.render(line, True, color)
surface.blit(buf, (x, y))
y += buf.get_rect().height
#------------------------------------------------------------------------------
class TextScreen(Screen):
# bg_color = (0, 0, 0)
# fg_color = (255, 255, 255)
# border = 20
heading_font = FontProperty('heading_font')
button_font = FontProperty('button_font')
def __init__(self, shell, filename, **kwds):
text = get_text(filename)
text_pages = text.split("\nPAGE\n")
pages = []
page_size = (0, 0)
for text_page in text_pages:
lines = text_page.strip().split("\n")
page = Page(self, lines[0], lines[1:])
pages.append(page)
page_size = maximum(page_size, page.size)
self.pages = pages
bf = self.button_font
b1 = Button("Prev Page", font = bf, action = self.prev_page)
b2 = Button("Menu", font = bf, action = self.go_back)
b3 = Button("Next Page", font = bf, action = self.next_page)
b = self.margin
page_rect = Rect((b, b), page_size)
gap = (0, 18)
b1.topleft = add(page_rect.bottomleft, gap)
b2.midtop = add(page_rect.midbottom, gap)
b3.topright = add(page_rect.bottomright, gap)
Screen.__init__(self, shell, **kwds)
self.size = add(b3.bottomright, (b, b))
self.add(b1)
self.add(b2)
self.add(b3)
self.prev_button = b1
self.next_button = b3
self.set_current_page(0)
def draw(self, surface):
b = self.margin
self.pages[self.current_page].draw(surface, self.fg_color, (b, b))
def at_first_page(self):
return self.current_page == 0
def at_last_page(self):
return self.current_page == len(self.pages) - 1
def set_current_page(self, n):
self.current_page = n
self.prev_button.enabled = not self.at_first_page()
self.next_button.enabled = not self.at_last_page()
def prev_page(self):
if not self.at_first_page():
self.set_current_page(self.current_page - 1)
def next_page(self):
if not self.at_last_page():
self.set_current_page(self.current_page + 1)
def go_back(self):
self.parent.show_menu()
| Python |
from pygame import Rect
from widget import Widget
class GridView(Widget):
# cell_size (width, height) size of each cell
#
# Abstract methods:
#
# num_rows() --> no. of rows
# num_cols() --> no. of columns
# draw_cell(surface, row, col, rect)
# click_cell(row, col, event)
def __init__(self, cell_size, nrows, ncols, **kwds):
"""nrows, ncols are for calculating initial size of widget"""
Widget.__init__(self, **kwds)
self.cell_size = cell_size
w, h = cell_size
d = 2 * self.margin
self.size = (w * ncols + d, h * nrows + d)
self.cell_size = cell_size
def draw(self, surface):
for row in xrange(self.num_rows()):
for col in xrange(self.num_cols()):
r = self.cell_rect(row, col)
self.draw_cell(surface, row, col, r)
def cell_rect(self, row, col):
w, h = self.cell_size
d = self.margin
x = col * w + d
y = row * h + d
return Rect(x, y, w, h)
def draw_cell(self, surface, row, col, rect):
pass
def mouse_down(self, event):
x, y = event.local
w, h = self.cell_size
W, H = self.size
d = self.margin
if d <= x < W - d and d <= y < H - d:
row = (y - d) // h
col = (x - d) // w
self.click_cell(row, col, event)
def click_cell(self, row, col, event):
pass
| Python |
#
# Albow - Screen
#
from widget import Widget
#------------------------------------------------------------------------------
class Screen(Widget):
def __init__(self, shell, **kwds):
Widget.__init__(self, shell.rect, **kwds)
self.shell = shell
self.center = shell.center
def begin_frame(self):
pass
def enter_screen(self):
pass
def leave_screen(self):
pass
| Python |
try:
from Numeric import add, subtract, maximum
except ImportError:
import operator
def add(x, y):
return map(operator.add, x, y)
def subtract(x, y):
return map(operator.sub, x, y)
def maximum(*args):
result = args[0]
for x in args[1:]:
result = map(max, result, x)
return result
| Python |
#
# Albow - Shell
#
from root import RootWidget
#------------------------------------------------------------------------------
class Shell(RootWidget):
def __init__(self, surface, **kwds):
RootWidget.__init__(self, surface, **kwds)
self.current_screen = None
def show_screen(self, new_screen):
old_screen = self.current_screen
if old_screen is not new_screen:
if old_screen:
old_screen.leave_screen()
self.remove(old_screen)
self.add(new_screen)
self.current_screen = new_screen
if new_screen:
new_screen.focus()
new_screen.enter_screen()
def begin_frame(self):
screen = self.current_screen
if screen:
screen.begin_frame()
| Python |
from pygame import Rect
from albow.resource import get_image
class ImageArray(object):
def __init__(self, image, shape):
self.image = image
self.shape = shape
if isinstance(shape, tuple):
self.nrows, self.ncols = shape
else:
self.nrows = 1
self.ncols = shape
iwidth, iheight = image.get_size()
self.size = iwidth // self.ncols, iheight // self.nrows
def __len__(self):
return self.shape
def __getitem__(self, index):
image = self.image
nrows = self.nrows
ncols = self.ncols
if nrows == 1:
row = 0
col = index
else:
row, col = index
#left = iwidth * col // ncols
#top = iheight * row // nrows
#width = iwidth // ncols
#height = iheight // nrows
width, height = self.size
left = width * col
top = height * row
return image.subsurface(left, top, width, height)
def get_rect(self):
return Rect((0, 0), self.size)
image_array_cache = {}
def get_image_array(name, shape, **kwds):
result = image_array_cache.get(name)
if not result:
result = ImageArray(get_image(name, **kwds), shape)
image_array_cache[name] = result
return result
| Python |
#
# Albow - Controls
#
from pygame import Rect, draw
from widget import Widget, overridable_property
from theme import ThemeProperty
from utils import blit_in_rect, frame_rect
import resource
#---------------------------------------------------------------------------
class Control(object):
highlighted = overridable_property('highlighted')
enabled = overridable_property('enabled')
value = overridable_property('value')
enable = None
ref = None
_highlighted = False
_enabled = True
_value = None
def get_value(self):
ref = self.ref
if ref:
return ref.get()
else:
return self._value
def set_value(self, x):
ref = self.ref
if ref:
ref.set(x)
else:
self._value = x
#---------------------------------------------------------------------------
class AttrRef(object):
def __init__(self, obj, attr):
self.obj = obj
self.attr = attr
def get(self):
return getattr(self.obj, self.attr)
def set(self, x):
setattr(self.obj, self.attr, x)
#---------------------------------------------------------------------------
class ItemRef(object):
def __init__(self, obj, item):
self.obj = obj
self.item = item
def get(self):
return self.obj[item]
def set(self, x):
self.obj[item] = x
#---------------------------------------------------------------------------
class Label(Widget):
align = 'l'
highlight_color = ThemeProperty('highlight_color')
disabled_color = ThemeProperty('disabled_color')
highlight_bg_color = ThemeProperty('highlight_bg_color')
enabled_bg_color = ThemeProperty('enabled_bg_color')
disabled_bg_color = ThemeProperty('disabled_bg_color')
enabled = True
highlighted = False
def __init__(self, text, width = None, **kwds):
Widget.__init__(self, **kwds)
font = self.font
lines = text.split("\n")
tw, th = 0, 0
for line in lines:
w, h = font.size(line)
tw = max(tw, w)
th += h
if width is not None:
tw = width
else:
tw = max(1, tw)
d = 2 * self.margin
self.size = (tw + d, th + d)
self.text = text
def draw(self, surface):
if not self.enabled:
fg = self.disabled_color
bg = self.disabled_bg_color
elif self.highlighted:
fg = self.highlight_color
bg = self.highlight_bg_color
else:
fg = self.fg_color
bg = self.enabled_bg_color
self.draw_with(surface, fg, bg)
def draw_with(self, surface, fg, bg = None):
if bg:
r = surface.get_rect()
b = self.border_width
if b:
e = - 2 * b
r.inflate_ip(e, e)
surface.fill(bg, r)
m = self.margin
align = self.align
width = surface.get_width()
y = m
lines = self.text.split("\n")
font = self.font
dy = font.get_linesize()
for line in lines:
image = font.render(line, True, fg)
r = image.get_rect()
r.top = y
if align == 'l':
r.left = m
elif align == 'r':
r.right = width - m
else:
r.centerx = width // 2
surface.blit(image, r)
y += dy
#---------------------------------------------------------------------------
class ButtonBase(Control):
align = 'c'
action = None
def mouse_down(self, event):
if self.enabled:
self._highlighted = True
def mouse_drag(self, event):
state = event in self
if state <> self._highlighted:
self._highlighted = state
self.invalidate()
def mouse_up(self, event):
if event in self:
self._highlighted = False
if self.enabled:
self.call_handler('action')
def get_highlighted(self):
return self._highlighted
def get_enabled(self):
enable = self.enable
if enable:
return enable()
else:
return self._enabled
def set_enabled(self, x):
self._enabled = x
#---------------------------------------------------------------------------
class Button(ButtonBase, Label):
def __init__(self, text, action = None, enable = None, **kwds):
Label.__init__(self, text, action = action, enable = enable, **kwds)
#---------------------------------------------------------------------------
class Image(Widget):
# image Image to display
highlight_color = ThemeProperty('highlight_color')
image = overridable_property('image')
highlighted = False
def __init__(self, image = None, rect = None, **kwds):
Widget.__init__(self, rect, **kwds)
if image:
if isinstance(image, basestring):
image = resource.get_image(image)
w, h = image.get_size()
d = 2 * self.margin
self.size = w + d, h + d
self._image = image
def get_image(self):
return self._image
def set_image(self, x):
self._image = x
def draw(self, surf):
frame = surf.get_rect()
if self.highlighted:
surf.fill(self.highlight_color)
image = self.image
r = image.get_rect()
r.center = frame.center
surf.blit(image, r)
# def draw(self, surf):
# frame = self.get_margin_rect()
# surf.blit(self.image, frame)
#---------------------------------------------------------------------------
class ImageButton(ButtonBase, Image):
pass
#---------------------------------------------------------------------------
class ValueDisplay(Control, Widget):
format = "%s"
align = 'l'
def __init__(self, width = 100, **kwds):
Widget.__init__(self, **kwds)
self.set_size_for_text(width)
def draw(self, surf):
value = self.value
text = self.format_value(value)
buf = self.font.render(text, True, self.fg_color)
frame = surf.get_rect()
blit_in_rect(surf, buf, frame, self.align, self.margin)
def format_value(self, value):
if value is not None:
return self.format % value
else:
return ""
#---------------------------------------------------------------------------
class CheckControl(Control):
def mouse_down(self, e):
self.value = not self.value
def get_highlighted(self):
return self.value
#---------------------------------------------------------------------------
class CheckWidget(Widget):
default_size = (16, 16)
margin = 4
border_width = 1
check_mark_tweak = 2
def __init__(self, **kwds):
Widget.__init__(self, Rect((0, 0), self.default_size), **kwds)
def draw(self, surf):
if self.highlighted:
r = self.get_margin_rect()
fg = self.fg_color
d = self.check_mark_tweak
p1 = (r.left, r.centery - d)
p2 = (r.centerx - d, r.bottom)
p3 = (r.right, r.top - d)
#draw.aalines(surf, fg, False, [p1, p2, p3])
draw.lines(surf, fg, False, [p1, p2, p3])
#---------------------------------------------------------------------------
class CheckBox(CheckControl, CheckWidget):
pass
#---------------------------------------------------------------------------
class RadioControl(Control):
setting = None
def get_highlighted(self):
return self.value == self.setting
def mouse_down(self, e):
self.value = self.setting
#---------------------------------------------------------------------------
class RadioButton(RadioControl, CheckWidget):
pass
| Python |
version = (2, 0, 0)
| Python |
#
# Albow - Themes
#
import resource
debug_theme = False
class ThemeProperty(object):
def __init__(self, name):
self.name = name
self.cache_name = intern("_" + name)
def __get__(self, obj, owner):
if debug_theme:
print "%s(%r).__get__(%r)" % (self.__class__.__name__, self.name, obj)
try: ###
cache_name = self.cache_name
try:
return getattr(obj, cache_name)
except AttributeError, e:
if debug_theme:
print e
value = self.get_from_theme(obj.__class__, self.name)
obj.__dict__[cache_name] = value
return value
except: ###
if debug_theme:
import traceback
traceback.print_exc()
print "-------------------------------------------------------"
raise ###
def __set__(self, obj, value):
if debug_theme:
print "Setting %r.%s = %r" % (obj, self.cache_name, value) ###
obj.__dict__[self.cache_name] = value
def get_from_theme(self, cls, name):
return root.get(cls, name)
class FontProperty(ThemeProperty):
def get_from_theme(self, cls, name):
return root.get_font(cls, name)
class ThemeError(Exception):
pass
class Theme(object):
# name string Name of theme, for debugging
# base Theme or None Theme on which this theme is based
def __init__(self, name, base = None):
self.name = name
self.base = base
def get(self, cls, name):
try:
return self.lookup(cls, name)
except ThemeError:
raise AttributeError("No value found in theme %s for '%s' of %s.%s" %
(self.name, name, cls.__module__, cls.__name__))
def lookup(self, cls, name):
if debug_theme:
print "Theme(%r).lookup(%r, %r)" % (self.name, cls, name)
for base_class in cls.__mro__:
class_theme = getattr(self, base_class.__name__, None)
if class_theme:
try:
return class_theme.lookup(cls, name)
except ThemeError:
pass
else:
try:
return getattr(self, name)
except AttributeError:
base_theme = self.base
if base_theme:
return base_theme.lookup(cls, name)
else:
raise ThemeError
def get_font(self, cls, name):
if debug_theme:
print "Theme.get_font(%r, %r)" % (cls, name)
spec = self.get(cls, name)
if spec:
if debug_theme:
print "font spec =", spec
return resource.get_font(*spec)
root = Theme('root')
root.font = (15, "Vera.ttf")
root.fg_color = (255, 255, 255)
root.bg_color = None
root.border_width = 0
root.border_color = None
root.margin = 0
root.tab_bg_color = None
root.sel_color = (0, 128, 255)
root.highlight_color = None
root.disabled_color = None
root.highlight_bg_color = None
root.enabled_bg_color = None
root.disabled_bg_color = None
root.RootWidget = Theme('RootWidget')
root.RootWidget.bg_color = (0, 0, 0)
root.Button = Theme('Button')
root.Button.font = (18, "VeraBd.ttf")
root.Button.fg_color = (255, 255, 0)
root.Button.highlight_color = (255, 0, 0)
root.Button.disabled_color = (64, 64, 64)
root.Button.highlight_bg_color = None
root.Button.enabled_bg_color = None
root.Button.disabled_bg_color = None
root.ImageButton = Theme('ImageButton')
root.ImageButton.highlight_color = (0, 128, 255)
framed = Theme('framed')
framed.border_width = 1
framed.margin = 3
root.Field = Theme('Field', base = framed)
root.Dialog = Theme('Dialog')
root.Dialog.bg_color = (128, 128, 128)
root.Dialog.border_width = 2
root.Dialog.margin = 15
root.DirPathView = Theme('DirPathView', base = framed)
root.FileListView = Theme('FileListView', base = framed)
root.FileListView.scroll_button_color = (255, 255, 0)
root.FileDialog = Theme("FileDialog")
root.FileDialog.up_button_text = "<-"
root.PaletteView = Theme('PaletteView')
root.PaletteView.sel_width = 2
root.PaletteView.scroll_button_size = 16
root.PaletteView.scroll_button_color = (0, 128, 255)
root.PaletteView.highlight_style = 'frame'
root.TextScreen = Theme('TextScreen')
root.TextScreen.heading_font = (24, "VeraBd.ttf")
root.TextScreen.button_font = (18, "VeraBd.ttf")
root.TextScreen.margin = 20
root.TabPanel = Theme('TabPanel')
root.TabPanel.tab_font = (18, "Vera.ttf")
root.TabPanel.tab_height = 24
root.TabPanel.tab_border_width = 0
root.TabPanel.tab_spacing = 4
root.TabPanel.tab_margin = 0
root.TabPanel.tab_fg_color = root.fg_color
root.TabPanel.default_tab_bg_color = (128, 128, 128)
root.TabPanel.tab_area_bg_color = None
root.TabPanel.tab_dimming = 0.5
#root.TabPanel.use_page_bg_color_for_tabs = True
| Python |
#
# Albow - Layout widgets
#
from pygame import Rect
from widget import Widget
class RowOrColumn(Widget):
def __init__(self, size, items, kwds):
align = kwds.pop('align', 'c')
spacing = kwds.pop('spacing', 10)
expand = kwds.pop('expand', None)
if isinstance(expand, int):
expand = items[expand]
#if kwds:
# raise TypeError("Unexpected keyword arguments to Row or Column: %s"
# % kwds.keys())
Widget.__init__(self, **kwds)
#print "albow.controls: RowOrColumn: size =", size, "expand =", expand ###
d = self.d
longways = self.longways
crossways = self.crossways
axis = self.axis
k, attr2, attr3 = self.align_map[align]
w = 0
length = 0
if isinstance(expand, int):
expand = items[expand]
elif not expand:
expand = items[-1]
move = ''
for item in items:
r = item.rect
w = max(w, getattr(r, crossways))
if item is expand:
item.set_resizing(axis, 's')
move = 'm'
else:
item.set_resizing(axis, move)
length += getattr(r, longways)
if size is not None:
n = len(items)
if n > 1:
length += spacing * (n - 1)
#print "albow.controls: expanding size from", length, "to", size ###
setattr(expand.rect, longways, max(1, size - length))
h = w * k // 2
m = self.margin
px = h * d[1] + m
py = h * d[0] + m
sx = spacing * d[0]
sy = spacing * d[1]
for item in items:
setattr(item.rect, attr2, (px, py))
self.add(item)
p = getattr(item.rect, attr3)
px = p[0] + sx
py = p[1] + sy
self.shrink_wrap()
#---------------------------------------------------------------------------
class Row(RowOrColumn):
d = (1, 0)
axis = 'h'
longways = 'width'
crossways = 'height'
align_map = {
't': (0, 'topleft', 'topright'),
'c': (1, 'midleft', 'midright'),
'b': (2, 'bottomleft', 'bottomright'),
}
def __init__(self, items, width = None, **kwds):
"""
Row(items, align = alignment, spacing = 10, width = None, expand = None)
align = 't', 'c' or 'b'
"""
RowOrColumn.__init__(self, width, items, kwds)
#---------------------------------------------------------------------------
class Column(RowOrColumn):
d = (0, 1)
axis = 'v'
longways = 'height'
crossways = 'width'
align_map = {
'l': (0, 'topleft', 'bottomleft'),
'c': (1, 'midtop', 'midbottom'),
'r': (2, 'topright', 'bottomright'),
}
def __init__(self, items, height = None, **kwds):
"""
Column(items, align = alignment, spacing = 10, height = None, expand = None)
align = 'l', 'c' or 'r'
"""
RowOrColumn.__init__(self, height, items, kwds)
#---------------------------------------------------------------------------
class Grid(Widget):
def __init__(self, rows, row_spacing = 10, column_spacing = 10, **kwds):
col_widths = [0] * len(rows[0])
row_heights = [0] * len(rows)
for j, row in enumerate(rows):
for i, widget in enumerate(row):
if widget:
col_widths[i] = max(col_widths[i], widget.width)
row_heights[j] = max(row_heights[j], widget.height)
row_top = 0
for j, row in enumerate(rows):
h = row_heights[j]
y = row_top + h // 2
col_left = 0
for i, widget in enumerate(row):
if widget:
w = col_widths[i]
x = col_left
widget.midleft = (x, y)
col_left += w + column_spacing
row_top += h + row_spacing
width = max(1, col_left - column_spacing)
height = max(1, row_top - row_spacing)
r = Rect(0, 0, width, height)
#print "albow.controls.Grid: r =", r ###
#print "...col_widths =", col_widths ###
#print "...row_heights =", row_heights ###
Widget.__init__(self, r, **kwds)
self.add(rows)
#---------------------------------------------------------------------------
class Frame(Widget):
# margin int spacing between border and widget
border_width = 1
margin = 2
def __init__(self, client, border_spacing = None, **kwds):
Widget.__init__(self, **kwds)
self.client = client
if border_spacing is not None:
self.margin = self.border_width + border_spacing
d = self.margin
w, h = client.size
self.size = (w + 2 * d, h + 2 * d)
client.topleft = (d, d)
self.add(client)
| Python |
"""ALBOW - A Little Bit of Widgetry for PyGame
by Gregory Ewing
greg.ewing@canterbury.ac.nz
"""
from version import version
| Python |
import textwrap
from pygame import Rect
from pygame.locals import *
from widget import Widget
from controls import Label, Button
from layout import Row, Column
from fields import TextField
class Modal(object):
enter_response = True
cancel_response = False
def ok(self):
self.dismiss(True)
def cancel(self):
self.dismiss(False)
class Dialog(Modal, Widget):
click_outside_response = None
def __init__(self, client = None, responses = None,
default = 0, cancel = -1, **kwds):
Widget.__init__(self, **kwds)
if client or responses:
rows = []
w1 = 0
w2 = 0
if client:
rows.append(client)
w1 = client.width
if responses:
buttons = Row([
Button(text, action = lambda t=text: self.dismiss(t))
for text in responses])
rows.append(buttons)
w2 = buttons.width
if w1 < w2:
a = 'l'
else:
a = 'r'
contents = Column(rows, align = a)
m = self.margin
contents.topleft = (m, m)
self.add(contents)
self.shrink_wrap()
if responses and default is not None:
self.enter_response = responses[default]
if responses and cancel is not None:
self.cancel_response = responses[cancel]
def mouse_down(self, e):
if not e in self:
response = self.click_outside_response
if response is not None:
self.dismiss(response)
def wrapped_label(text, wrap_width, **kwds):
paras = text.split("\n\n")
text = "\n".join([textwrap.fill(para, wrap_width) for para in paras])
return Label(text, **kwds)
def alert(mess, wrap_width = 60, **kwds):
box = Dialog(**kwds)
d = box.margin
lb = wrapped_label(mess, wrap_width)
lb.topleft = (d, d)
box.add(lb)
box.shrink_wrap()
return box.present()
def alert(mess, **kwds):
ask(mess, ["OK"], **kwds)
def ask(mess, responses = ["OK", "Cancel"], default = 0, cancel = -1,
wrap_width = 60, **kwds):
box = Dialog(**kwds)
d = box.margin
lb = wrapped_label(mess, wrap_width)
lb.topleft = (d, d)
buts = []
for caption in responses:
but = Button(caption, action = lambda x = caption: box.dismiss(x))
buts.append(but)
brow = Row(buts, spacing = d)
lb.width = max(lb.width, brow.width)
col = Column([lb, brow], spacing = d, align ='r')
col.topleft = (d, d)
if default is not None:
box.enter_response = responses[default]
else:
box.enter_response = None
if cancel is not None:
box.cancel_response = responses[cancel]
else:
box.cancel_response = None
box.add(col)
box.shrink_wrap()
return box.present()
def input_text(prompt, width, initial = None, **kwds):
box = Dialog(**kwds)
d = box.margin
def ok():
box.dismiss(True)
def cancel():
box.dismiss(False)
lb = Label(prompt)
lb.topleft = (d, d)
tf = TextField(width)
if initial:
tf.set_text(initial)
tf.enter_action = ok
tf.escape_action = cancel
tf.top = lb.top
tf.left = lb.right + 5
box.add(lb)
box.add(tf)
tf.focus()
box.shrink_wrap()
if box.present():
return tf.get_text()
else:
return None
| Python |
import sys
import pygame
from pygame.locals import *
from pygame.time import get_ticks
from pygame.event import Event
import widget
from widget import Widget
mod_cmd = KMOD_LCTRL | KMOD_RCTRL | KMOD_LMETA | KMOD_RMETA
double_click_time = 300 # milliseconds
modifiers = dict(
shift = False,
ctrl = False,
alt = False,
meta = False,
)
modkeys = {
K_LSHIFT: 'shift', K_RSHIFT: 'shift',
K_LCTRL: 'ctrl', K_RCTRL: 'ctrl',
K_LALT: 'alt', K_RALT: 'alt',
K_LMETA: 'meta', K_RMETA: 'meta',
}
last_mouse_event = Event(0, pos = (0, 0), local = (0, 0))
last_mouse_event_handler = None
class Cancel(Exception):
pass
def set_modifier(key, value):
attr = modkeys.get(key)
if attr:
modifiers[attr] = value
def add_modifiers(event):
d = event.dict
d.update(modifiers)
d['cmd'] = event.ctrl or event.meta
class RootWidget(Widget):
redraw_every_frame = False
do_draw = False
def __init__(self, surface):
Widget.__init__(self, surface.get_rect())
self.surface = surface
widget.root_widget = self
def set_timer(self, ms):
pygame.time.set_timer(USEREVENT, ms)
def run(self):
self.run_modal(None)
def run_modal(self, modal_widget):
global last_mouse_event, last_mouse_event_handler
is_modal = modal_widget is not None
modal_widget = modal_widget or self
was_modal = modal_widget.is_modal
modal_widget.is_modal = True
modal_widget.modal_result = None
if not modal_widget.focus_switch:
modal_widget.tab_to_first()
mouse_widget = None
clicked_widget = None
num_clicks = 0
last_click_time = 0
self.do_draw = True
while modal_widget.modal_result is None:
try:
if self.do_draw:
self.draw_all(self.surface)
self.do_draw = False
pygame.display.flip()
events = [pygame.event.wait()]
events.extend(pygame.event.get())
for event in events:
type = event.type
if type == QUIT:
self.quit()
elif type == MOUSEBUTTONDOWN:
self.do_draw = True
t = get_ticks()
if t - last_click_time <= double_click_time:
num_clicks += 1
else:
num_clicks = 1
last_click_time = t
event.dict['num_clicks'] = num_clicks
add_modifiers(event)
mouse_widget = self.find_widget(event.pos)
if not mouse_widget.is_inside(modal_widget):
mouse_widget = modal_widget
clicked_widget = mouse_widget
last_mouse_event_handler = mouse_widget
last_mouse_event = event
mouse_widget.notify_attention_loss()
mouse_widget.handle_mouse('mouse_down', event)
elif type == MOUSEMOTION:
add_modifiers(event)
modal_widget.dispatch_key('mouse_delta', event)
mouse_widget = self.find_widget(event.pos)
last_mouse_event = event
if clicked_widget:
last_mouse_event_handler = mouse_widget
clicked_widget.handle_mouse('mouse_drag', event)
else:
if not mouse_widget.is_inside(modal_widget):
mouse_widget = modal_widget
last_mouse_event_handler = mouse_widget
mouse_widget.handle_mouse('mouse_move', event)
elif type == MOUSEBUTTONUP:
add_modifiers(event)
self.do_draw = True
mouse_widget = self.find_widget(event.pos)
if clicked_widget:
last_mouse_event_handler = clicked_widget
last_mouse_event = event
clicked_widget = None
last_mouse_event_handler.handle_mouse('mouse_up', event)
elif type == KEYDOWN:
key = event.key
set_modifier(key, True)
self.do_draw = True
self.send_key(modal_widget, 'key_down', event)
if last_mouse_event_handler:
event.dict['pos'] = last_mouse_event.pos
event.dict['local'] = last_mouse_event.local
last_mouse_event_handler.setup_cursor(event)
elif type == KEYUP:
key = event.key
set_modifier(key, False)
self.do_draw = True
self.send_key(modal_widget, 'key_up', event)
if last_mouse_event_handler:
event.dict['pos'] = last_mouse_event.pos
event.dict['local'] = last_mouse_event.local
last_mouse_event_handler.setup_cursor(event)
elif type == USEREVENT:
if not is_modal:
self.do_draw = self.redraw_every_frame
if last_mouse_event_handler:
event.dict['pos'] = last_mouse_event.pos
event.dict['local'] = last_mouse_event.local
add_modifiers(event)
last_mouse_event_handler.setup_cursor(event)
self.begin_frame()
except Cancel:
pass
modal_widget.is_modal = was_modal
#modal_widget.dispatch_attention_loss()
def send_key(self, widget, name, event):
add_modifiers(event)
widget.dispatch_key(name, event)
def begin_frame(self):
pass
def get_root(self):
return self
def has_focus(self):
return True
def quit(self):
if self.confirm_quit():
sys.exit(0)
def confirm_quit(self):
return True
def get_mouse_for(self, widget):
last = last_mouse_event
event = Event(0, last.dict)
event.dict['local'] = widget.global_to_local(event.pos)
add_modifiers(event)
return event
| Python |
#
# Albow - File Dialogs
#
import os
from pygame import draw, Rect
from albow.widget import Widget
from albow.dialogs import Dialog, ask, alert
from albow.controls import Label, Button
from albow.fields import TextField
from albow.layout import Row, Column
from albow.palette_view import PaletteView
from albow.theme import ThemeProperty
class DirPathView(Widget):
def __init__(self, width, client, **kwds):
Widget.__init__(self, **kwds)
self.set_size_for_text(width)
self.client = client
def draw(self, surf):
frame = self.get_margin_rect()
image = self.font.render(self.client.directory, True, self.fg_color)
tw = image.get_width()
mw = frame.width
if tw <= mw:
x = 0
else:
x = mw - tw
surf.blit(image, (frame.left + x, frame.top))
class FileListView(PaletteView):
#scroll_button_color = (255, 255, 0)
def __init__(self, width, client, **kwds):
font = self.predict_font(kwds)
h = font.get_linesize()
d = 2 * self.predict(kwds, 'margin')
PaletteView.__init__(self, (width - d, h), 10, 1, scrolling = True, **kwds)
self.client = client
self.selection = None
self.names = []
def update(self):
client = self.client
dir = client.directory
suffixes = client.suffixes
def filter(name):
path = os.path.join(dir, name)
return os.path.isdir(path) or self.client.filter(path)
try:
names = [name for name in os.listdir(dir)
if not name.startswith(".") and filter(name)]
except EnvironmentError, e:
alert("%s: %s" % (dir, e))
names = []
self.names = names
self.selection = None
def num_items(self):
return len(self.names)
#def draw_prehighlight(self, surf, item_no, rect):
# draw.rect(surf, self.sel_color, rect)
def draw_item(self, surf, item_no, rect):
font = self.font
color = self.fg_color
buf = self.font.render(self.names[item_no], True, color)
surf.blit(buf, rect)
def click_item(self, item_no, e):
self.selection = item_no
self.client.dir_box_click(e.num_clicks == 2)
def item_is_selected(self, item_no):
return item_no == self.selection
def get_selected_name(self):
sel = self.selection
if sel is not None:
return self.names[sel]
else:
return ""
class FileDialog(Dialog):
box_width = 250
default_prompt = None
up_button_text = ThemeProperty("up_button_text")
def __init__(self, prompt = None, suffixes = None, **kwds):
Dialog.__init__(self, **kwds)
label = None
d = self.margin
self.suffixes = suffixes
up_button = Button(self.up_button_text, action = self.go_up)
dir_box = DirPathView(self.box_width - up_button.width - 10, self)
self.dir_box = dir_box
top_row = Row([dir_box, up_button])
list_box = FileListView(self.box_width - 16, self)
self.list_box = list_box
ctrls = [top_row, list_box]
prompt = prompt or self.default_prompt
if prompt:
label = Label(prompt)
if self.saving:
filename_box = TextField(self.box_width)
filename_box.change_action = self.update
self.filename_box = filename_box
ctrls.append(Column([label, filename_box], align = 'l', spacing = 0))
else:
if label:
ctrls.insert(0, label)
ok_button = Button(self.ok_label, action = self.ok, enable = self.ok_enable)
self.ok_button = ok_button
cancel_button = Button("Cancel", action = self.cancel)
vbox = Column(ctrls, align = 'l', spacing = d)
vbox.topleft = (d, d)
y = vbox.bottom + d
ok_button.topleft = (vbox.left, y)
cancel_button.topright = (vbox.right, y)
self.add(vbox)
self.add(ok_button)
self.add(cancel_button)
self.shrink_wrap()
self._directory = None
self.directory = os.getcwd()
#print "FileDialog: cwd =", repr(self.directory) ###
if self.saving:
filename_box.focus()
def get_directory(self):
return self._directory
def set_directory(self, x):
if self._directory <> x:
self._directory = os.path.abspath(x)
self.list_box.update()
self.update()
directory = property(get_directory, set_directory)
def filter(self, path):
suffixes = self.suffixes
if not suffixes:
return os.path.isfile(path)
for suffix in suffixes:
if path.endswith(suffix):
return True
def update(self):
pass
def go_up(self):
self.directory = os.path.dirname(self.directory)
def dir_box_click(self, double):
if double:
name = self.list_box.get_selected_name()
path = os.path.join(self.directory, name)
if os.path.isdir(path):
self.directory = path
else:
self.double_click_file(name)
self.update()
def ok(self):
self.dismiss(True)
def cancel(self):
self.dismiss(False)
class FileSaveDialog(FileDialog):
saving = True
default_prompt = "Save as:"
ok_label = "Save"
def get_filename(self):
return self.filename_box.get_text()
def set_filename(self, x):
dsuf = self.suffixes[0]
if x.endswith(dsuf):
x = x[:-len(dsuf)]
self.filename_box.set_text(x)
filename = property(get_filename, set_filename)
def get_pathname(self):
path = os.path.join(self.directory, self.filename_box.get_text())
suffixes = self.suffixes
if suffixes and not path.endswith(suffixes[0]):
path = path + suffixes[0]
return path
pathname = property(get_pathname)
def double_click_file(self, name):
self.filename_box.set_text(name)
def ok(self):
path = self.pathname
if os.path.exists(path):
answer = ask("Replace existing '%s'?" % os.path.basename(path))
if answer <> "OK":
return
FileDialog.ok(self)
def update(self):
FileDialog.update(self)
name = self.filename_box.get_text()
#self.ok_button.enabled = name <> ""
def ok_enable(self):
return self.filename_box.get_text() <> ""
class FileOpenDialog(FileDialog):
saving = False
ok_label = "Open"
def get_pathname(self):
name = self.list_box.get_selected_name()
if name:
return os.path.join(self.directory, name)
else:
return None
pathname = property(get_pathname)
#def update(self):
# FileDialog.update(self)
def ok_enable(self):
path = self.pathname
enabled = self.item_is_choosable(path)
return enabled
def item_is_choosable(self, path):
return bool(path) and self.filter(path)
def double_click_file(self, name):
self.ok()
class LookForFileDialog(FileOpenDialog):
target = None
def __init__(self, target, **kwds):
FileOpenDialog.__init__(self, **kwds)
self.target = target
def item_is_choosable(self, path):
return path and os.path.basename(path) == self.target
def filter(self, name):
return name and os.path.basename(name) == self.target
def request_new_filename(prompt = None, suffix = None, extra_suffixes = None,
directory = None, filename = None, pathname = None):
if pathname:
directory, filename = os.path.split(pathname)
if extra_suffixes:
suffixes = extra_suffixes
else:
suffixes = []
if suffix:
suffixes = [suffix] + suffixes
dlog = FileSaveDialog(prompt = prompt, suffixes = suffixes)
if directory:
dlog.directory = directory
if filename:
dlog.filename = filename
if dlog.present():
return dlog.pathname
else:
return None
def request_old_filename(suffixes = None, directory = None):
dlog = FileOpenDialog(suffixes = suffixes)
if directory:
dlog.directory = directory
if dlog.present():
return dlog.pathname
else:
return None
def look_for_file_or_directory(target, prompt = None, directory = None):
dlog = LookForFileDialog(target = target, prompt = prompt)
if directory:
dlog.directory = directory
if dlog.present():
return dlog.pathname
else:
return None
| Python |
from pygame import Rect, draw
from grid_view import GridView
from utils import frame_rect
from theme import ThemeProperty
class PaletteView(GridView):
# nrows int No. of displayed rows
# ncols int No. of displayed columns
#
# Abstract methods:
#
# num_items() --> no. of items
# draw_item(surface, item_no, rect)
# click_item(item_no, event)
# item_is_selected(item_no) --> bool
sel_width = ThemeProperty('sel_width')
scroll_button_size = ThemeProperty('scroll_button_size')
scroll_button_color = ThemeProperty('scroll_button_color')
highlight_style = ThemeProperty('highlight_style')
# 'frame' or 'fill' or 'reverse' or None
def __init__(self, cell_size, nrows, ncols, scrolling = False, **kwds):
GridView.__init__(self, cell_size, nrows, ncols, **kwds)
self.scrolling = scrolling
if scrolling:
d = self.scroll_button_size
#l = self.width
#b = self.height
self.width += d
#self.scroll_up_rect = Rect(l, 0, d, d).inflate(-4, -4)
#self.scroll_down_rect = Rect(l, b - d, d, d).inflate(-4, -4)
self.scroll = 0
def scroll_up_rect(self):
d = self.scroll_button_size
r = Rect(0, 0, d, d)
m = self.margin
r.top = m
r.right = self.width - m
r.inflate_ip(-4, -4)
return r
def scroll_down_rect(self):
d = self.scroll_button_size
r = Rect(0, 0, d, d)
m = self.margin
r.bottom = self.height - m
r.right = self.width - m
r.inflate_ip(-4, -4)
return r
def draw(self, surface):
GridView.draw(self, surface)
if self.can_scroll_up():
self.draw_scroll_up_button(surface)
if self.can_scroll_down():
self.draw_scroll_down_button(surface)
def draw_scroll_up_button(self, surface):
r = self.scroll_up_rect()
c = self.scroll_button_color
draw.polygon(surface, c, [r.bottomleft, r.midtop, r.bottomright])
def draw_scroll_down_button(self, surface):
r = self.scroll_down_rect()
c = self.scroll_button_color
draw.polygon(surface, c, [r.topleft, r.midbottom, r.topright])
def draw_cell(self, surface, row, col, rect):
i = self.cell_to_item_no(row, col)
if i is not None:
highlight = self.item_is_selected(i)
self.draw_item_and_highlight(surface, i, rect, highlight)
def draw_item_and_highlight(self, surface, i, rect, highlight):
if highlight:
self.draw_prehighlight(surface, i, rect)
if highlight and self.highlight_style == 'reverse':
fg = self.inherited('bg_color') or self.sel_color
else:
fg = self.fg_color
self.draw_item_with(surface, i, rect, fg)
if highlight:
self.draw_posthighlight(surface, i, rect)
def draw_item_with(self, surface, i, rect, fg):
old_fg = self.fg_color
self.fg_color = fg
try:
self.draw_item(surface, i, rect)
finally:
self.fg_color = old_fg
def draw_prehighlight(self, surface, i, rect):
if self.highlight_style == 'reverse':
color = self.fg_color
else:
color = self.sel_color
self.draw_prehighlight_with(surface, i, rect, color)
def draw_prehighlight_with(self, surface, i, rect, color):
style = self.highlight_style
if style == 'frame':
frame_rect(surface, color, rect, self.sel_width)
elif style == 'fill' or style == 'reverse':
surface.fill(color, rect)
def draw_posthighlight(self, surface, i, rect):
pass
def mouse_down(self, event):
if self.scrolling:
p = event.local
if self.scroll_up_rect().collidepoint(p):
self.scroll_up()
return
elif self.scroll_down_rect().collidepoint(p):
self.scroll_down()
return
GridView.mouse_down(self, event)
def scroll_up(self):
if self.can_scroll_up():
self.scroll -= self.items_per_page()
def scroll_down(self):
if self.can_scroll_down():
self.scroll += self.items_per_page()
def scroll_to_item(self, n):
i = max(0, min(n, self.num_items() - 1))
p = self.items_per_page()
self.scroll = p * (i // p)
def can_scroll_up(self):
return self.scrolling and self.scroll > 0
def can_scroll_down(self):
return self.scrolling and self.scroll + self.items_per_page() < self.num_items()
def items_per_page(self):
return self.num_rows() * self.num_cols()
def click_cell(self, row, col, event):
i = self.cell_to_item_no(row, col)
if i is not None:
self.click_item(i, event)
def cell_to_item_no(self, row, col):
i = self.scroll + row * self.num_cols() + col
if 0 <= i < self.num_items():
return i
else:
return None
def num_rows(self):
ch = self.cell_size[1]
if ch:
return self.height // ch
else:
return 0
def num_cols(self):
width = self.width
if self.scrolling:
width -= self.scroll_button_size
cw = self.cell_size[0]
if cw:
return width // cw
else:
return 0
def item_is_selected(self, n):
return False
def click_item(self, n, e):
pass
| Python |
#
# Albow - Table View
#
from itertools import izip
from pygame import Rect
from layout import Column
from palette_view import PaletteView
from utils import blit_in_rect
class TableView(Column):
columns = []
header_font = None
header_fg_color = None
header_bg_color = None
header_spacing = 5
column_margin = 2
def __init__(self, nrows = None, height = None,
header_height = None, row_height = None,
scrolling = True, **kwds):
columns = self.predict_attr(kwds, 'columns')
if row_height is None:
font = self.predict_font(kwds)
row_height = font.get_linesize()
if header_height is None:
header_height = row_height
row_width = 0
if columns:
for column in columns:
row_width += column.width
row_width += 2 * self.column_margin * len(columns)
contents = []
header = None
if header_height:
header = TableHeaderView(row_width, header_height)
contents.append(header)
row_size = (row_width, row_height)
if not nrows and height:
nrows = height // row_height
rows = TableRowView(row_size, nrows or 10, scrolling = scrolling)
contents.append(rows)
s = self.header_spacing
Column.__init__(self, contents, align = 'l', spacing = s, **kwds)
if header:
header.font = self.header_font or self.font
header.fg_color = fg_color = self.header_fg_color or self.fg_color
header.bg_color = bg_color = self.header_bg_color or self.bg_color
rows.font = self.font
rows.fg_color = self.fg_color
rows.bg_color = self.bg_color
rows.sel_color = self.sel_color
def column_info(self, row_data):
columns = self.columns
m = self.column_margin
d = 2 * m
x = 0
for i, column in enumerate(columns):
width = column.width
if row_data:
data = row_data[i]
else:
data = None
yield i, x + m, width - d, column, data
x += width
def draw_header_cell(self, surf, i, cell_rect, column):
self.draw_text_cell(surf, i, column.title, cell_rect,
column.alignment, self.font)
def draw_table_cell(self, surf, i, data, cell_rect, column):
text = column.format(data)
self.draw_text_cell(surf, i, text, cell_rect, column.alignment, self.font)
def draw_text_cell(self, surf, i, data, cell_rect, align, font):
buf = font.render(str(data), True, self.fg_color)
blit_in_rect(surf, buf, cell_rect, align)
def row_is_selected(self, n):
return False
def click_row(self, n, e):
pass
class TableColumn(object):
# title string
# width int
# alignment 'l' or 'c' or 'r'
# formatter func(data) -> string
# format_string string Used by default formatter
format_string = "%s"
def __init__(self, title, width, align = 'l', fmt = None):
self.title = title
self.width = width
self.alignment = align
if fmt:
if isinstance(fmt, (str, unicode)):
self.format_string = fmt
else:
self.formatter = fmt
def format(self, data):
if data is not None:
return self.formatter(data)
else:
return ""
def formatter(self, data):
return self.format_string % data
class TableRowBase(PaletteView):
def __init__(self, cell_size, nrows, scrolling):
PaletteView.__init__(self, cell_size, nrows, 1, scrolling = scrolling)
def num_items(self):
return self.parent.num_rows()
def draw_item(self, surf, row, row_rect):
table = self.parent
height = row_rect.height
row_data = self.row_data(row)
for i, x, width, column, cell_data in table.column_info(row_data):
cell_rect = Rect(x, row_rect.top, width, height)
self.draw_table_cell(surf, i, cell_data, cell_rect, column)
def row_data(self, row):
return self.parent.row_data(row)
def draw_table_cell(self, surf, i, data, cell_rect, column):
self.parent.draw_table_cell(surf, i, data, cell_rect, column)
class TableRowView(TableRowBase):
highlight_style = 'fill'
vstretch = True
def item_is_selected(self, n):
return self.parent.row_is_selected(n)
def click_item(self, n, e):
self.parent.click_row(n, e)
class TableHeaderView(TableRowBase):
def __init__(self, width, height):
TableRowBase.__init__(self, (width, height), 1, False)
# def row_data(self, row):
# return [c.title for c in self.parent.columns]
# def draw_table_cell(self, surf, i, text, cell_rect, column):
# self.parent.draw_header_cell(surf, i, text, cell_rect, column)
def row_data(self, row):
None
def draw_table_cell(self, surf, i, data, cell_rect, column):
self.parent.draw_header_cell(surf, i, cell_rect, column)
| Python |
import pygame
import math
import constants as c
import data
import bird
import sounds
class Turbine(pygame.sprite.Sprite):
def __init__(self, x, y):
''' Creates a turbine head, given its x and y coordinates'''
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = data.load_image("turbine.png", -1)
self.original = self.image
self.rect.center = (x, y)
self.center = self.rect.center
self.time_count = 0
self._spinning = True
@property
def output(self):
if self._spinning:
return c.TURBINE_kW
return 0
def update(self, time_diff):
self.time_count = self.time_count + time_diff
if self.time_count > 1000:
self.time_count = self.time_count - 1000
# now if the turbine not spinning don't rotate!
if self._spinning:
self.image = pygame.transform.rotate(self.original,
(self.time_count/1000.0*360.0))
else:
self._elapsed += time_diff
if self._elapsed > self._delay:
self._spinning = True
self._elapsed = 0
self.rect = self.image.get_rect(center = self.center)
def collide(self, other):
'someone has hit us! if it was a bird, calc the momentum and stop.'
if isinstance(other, bird.Bird):
# momentum in kgm/s
p = other.m * math.sqrt(other.velx**2 + other.vely**2)
# time out of action surely is larger for higher momentum.
self._delay = p * c.TURBINE_HITDELAY
self._elapsed = 0
self._spinning = False
# I love doing this dirty hack!! try and stop me...
other.kill()
# now for my next trick.. play sounds.
sounds.play_sfx('windmill_stop.wav')
| Python |
"""
a really poor popup box.
smart enough to display text and perhaps images
in a grid like or column like fashion.
image | text about image
| can span multiple
| lines.
clicking a mouse button will exit."""
import pygame
from pygame.locals import *
import data
import constants as c
def game_completed(display):
'show the user a nice ending screen. They deserve it.'
img, rect = data.load_image('gamecomplete.png', None)
display.blit(img, (0, 0))
pygame.display.flip()
wait_for_interaction()
def success_or_fail(display, cond, stats):
'show the success or failure screen'
img, rect = data.load_image('success.png' if cond else 'failure.png', None)
display.blit(img, (0, 0))
pygame.display.flip()
heading = pygame.font.Font(None, 36)
normaltext = pygame.font.Font(None, 30)
# show the user his stats.
txt = ('Target Energy: %s kWh\nProduced Energy: %s kWh'
% (stats.target_kWh, stats.total_kWh))
y = rendertxt(display, txt, normaltext, 500, 100)
for bonus in stats.bonus:
# bonus is a surface already to be shown.
display.blit(bonus, (500 - 60, y))
y += bonus.get_height()
pygame.display.update()
wait_for_interaction()
def popup(display, config):
'a full screen instructions before play popup'
original = display.copy()
# get a rectangle that is smaller than the original background.
rect = display.get_rect().inflate(-20, -20)
# make a new surface to draw this popup to.
pop_surf = pygame.Surface((rect.width, rect.height))
pop_surf.fill((100, 100, 100))
heading = pygame.font.Font(None, 36)
normaltext = pygame.font.Font(None, 24)
rendertxt(pop_surf, config.name, heading, 80, 50)
y = 100
y = rendertxt(pop_surf, 'Goal', heading, 100, y)
text = ('To pass the level you must produce %s kWh or more' %
config.target_kWh)
y = rendertxt(pop_surf, text, normaltext, 120, y)
text = ('* A turbine hit by a bird will not produce energy'
' for a period of time proportional to the momentum'
' of the bird')
y = rendertxt(pop_surf, 'Instructions', heading, 100, y)
y = rendertxt(pop_surf, text, normaltext, 120, y)
y = rendertxt(pop_surf, 'momentum = mass * speed', normaltext, 120, y)
text = ('* Each use of the fan will consume %s kWh of your produced'
' energy.' % c.AIRS_COST)
y = rendertxt(pop_surf, text, normaltext, 120, y)
# now render the game info.
rendertxt(pop_surf, 'Other Info', heading, 500, 100)
timelimit = 'time limit %s seconds' % config.timelimit
rendertxt(pop_surf, timelimit, normaltext, 550, 160)
# get all the birds so we can blit them.
all = pygame.sprite.Group()
birdclasses = [(v[0], k) for k, v in config.birds.items()]
y = 210
for Bird, name in birdclasses:
b = Bird(500, y, all)
b.velx, b.vely = (0, 0)
all.add(b)
rendertxt(pop_surf, '%s: %s kg' % (name, b.m), normaltext, 550, y)
y += 50
# now show the time attributes.
timesprite = pygame.sprite.Sprite()
timesprite.image, timesprite.rect = data.load_image('time.png', -1)
timesprite.rect.topleft = (500, 150)
all.add(timesprite)
display.blit(pop_surf, (10, 10))
pygame.display.flip()
time_last = pygame.time.get_ticks()
clk = pygame.time.Clock()
running = True
while running:
clk.tick(c.FPS)
time_current = pygame.time.get_ticks()
time_diff = time_current - time_last
time_last = time_current
all.update({'time': time_diff})
display.blit(pop_surf, (10, 10))
all.draw(display)
pygame.display.flip()
for e in pygame.event.get():
if e.type == MOUSEBUTTONDOWN:
running = False
if e.type == QUIT:
raise SystemExit("Poweroff")
def rendertxt(display, text, font, x, y):
BIG_BUFFER = 30
SMALL_BUFFER = 5
lines = data.wrap_multi_line(text, font, 300)
for line in lines:
surf = font.render(line, True, c.WHITE)
display.blit(surf, (x, y))
y += SMALL_BUFFER + surf.get_height()
return y + BIG_BUFFER
def wait_for_interaction():
clk = pygame.time.Clock()
running = True
pygame.time.delay(500)
pygame.event.clear()
while running:
clk.tick(c.FPS)
for e in pygame.event.get():
if e.type == MOUSEBUTTONDOWN:
running = False
if e.type == QUIT:
raise SystemExit("Poweroff")
| Python |
"""
File to house
bonuses both on a game-wide
and level-wide basis."""
import pygame
import data
import constants as c
def get_bonuses(gamestats, levelstats):
achieved = []
for bonus, kind in bonuses:
if kind == 'game':
stat = gamestats
else:
stat = levelstats
b = bonus(stat)
if b:
achieved.append(b)
return achieved
def transparent(f):
def make_result_transparent(*args):
surf = f(*args)
trans = surf.get_at((0, 0))
surf.set_colorkey(trans)
return surf
return make_result_transparent
def BadDriver(stats):
'a bad driver bonus. killing all birds'
if stats.saved > 0 or stats.dead == 0: return None
text = 'Bad driver award\n saved 0 birds.'
return makeaward('bonus_baddriver.png', text)
def FriendOfMany(stats):
'Never killed a single bird.'
if stats.saved == 0 or stats.dead > 0: return None
text = 'Friend of birds award\n killed 0 birds.'
return makeaward('bonus_friend.png', text)
def JnrPowerStation(stats):
'Lifetime accumulation of much energy.'
if stats.total_kWh < 10 or stats.total_kWh > 20:
return None
text = 'Jnr Power Station Lifetime award \n accumulated more than 10 kWh'
return makeaward('bonus_jnrpower.png', text)
def SnrPowerStation(stats):
'Lifetime accumulation of much more energy.'
if stats.total_kWh < 60:
return None
text = 'Snr Power Station Lifetime award\n accumulated more than 60 kWh'
return makeaward('bonus_snrpower.png', text)
def NetConsumer(stats):
'user consumed more than produced for level.'
if stats.total_kWh > 0:
return None
text = 'Net Consumer award\n consumed %s kWh' % (-stats.total_kWh)
return makeaward('bonus_netconsumer.png', text)
def MillionsofTransistors(stats):
'a certain number of birds died in a level.'
if stats.dead < 10:
return None
text = ('"Millions of tiny transistors" award\n'
' killed %s birds in a level') % stats.dead
return makeaward('bonus_millions.png', text)
def Featherinyourcapaward(stats):
'Lifetime saving of many birds.'
if stats.saved < 20:
return None
text = 'featherinyourcap Lifetime award\n Saved %s birds!' % stats.saved
return makeaward('bonus_featherincap.png', text)
def GoldStar(stats):
'Gold star for trying.'
if stats.attempts < 5:
return None
text = 'Gold Star award\n Tried and failed %s times' % stats.attempts
return makeaward('bonus_goldstar.png', text)
@transparent
def makeaward(filename, txt):
img, rect = data.load_image(filename, -1)
surf = pygame.Surface((rect.width + 300, rect.height))
surf.fill((150, 150, 150))
surf.blit(img, (0, 0))
normaltxt = pygame.font.Font(None, 24)
# now draw some lines.
points = ((0, surf.get_height()), surf.get_size(), (surf.get_width(), 0))
surf.set_alpha(200)
rendertxt(surf, txt, normaltxt, rect.width + 1, 10)
return surf
def rendertxt(display, text, font, x, y):
BIG_BUFFER = 30
SMALL_BUFFER = 5
lines = data.wrap_multi_line(text, font, 300)
for line in lines:
surf = font.render(line, True, c.WHITE)
display.blit(surf, (x, y))
y += SMALL_BUFFER + surf.get_height()
return y + BIG_BUFFER
bonuses = [(BadDriver, 'level'),
(FriendOfMany, 'level'),
(JnrPowerStation, 'game'),
(SnrPowerStation, 'game'),
(NetConsumer, 'level'),
(Featherinyourcapaward, 'game'),
(GoldStar, 'level'),
(MillionsofTransistors, 'level'),
]
| Python |
import pygame
XMAX = 800
YMAX = 600
RESOLUTION = (XMAX, YMAX)
FPS = 40
# number of milliseconds between bird updates.
BIRDRATE = 100
# bird event.
BIRDUPDATE = pygame.USEREVENT
# event definitions
# 250 ms between fan gusts
EVENT_FAN_TIMEOUT = 25
EVENT_FAN_TIMEOUT_TIME = 250
BLOW = 1
SUCK = 0
# the amount of kWh subtracted for creating an air.
AIRS_COST = 0.05
BIRD_BONUS = AIRS_COST * 0.5
BLOW_START_Y = 560
SUCK_START_Y = 0
# bird constants.
BIRD_FLAPUPDATE = 15 # number of frames before flapping.
MU = 0.1
# turbine output.
TURBINE_kW = 1000
TURBINE_HITDELAY = 3000
# colours
WHITE = (255, 255, 255)
| Python |
'''Simple data loader module.
Loads data files from the "data" directory shipped with a game.
Enhancing this to handle caching etc. is left as an exercise for the reader.
'''
import os
import sys
import pygame
from pygame.locals import *
if 'python' in sys.executable:
data_py = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
else:
data_py = os.path.abspath(os.path.dirname(sys.executable))
data_dir = os.path.normpath(os.path.join(data_py, 'data'))
def filepath(filename):
'''Determine the path to a file in the data directory.
'''
return os.path.join(data_dir, filename)
def load(filename, mode='rb'):
'''Open a file in the data directory.
"mode" is passed as the second arg to open().
'''
return open(os.path.join(data_dir, filename), mode)
def load_image(name, colorkey=None):
'''Loads an image from the data dir, with specified colorkey.
If colorkey is -1 then the colour in the corner of the image will
be used.
'''
fullname = filepath(name)
try:
image = pygame.image.load(fullname)
except pygame.error, message:
print 'Could not load image:', name
raise SystemExit, message
image = image.convert()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)
return image, image.get_rect()
"The following taken from pygame cookbook."
# This class handles sprite sheets
# This was taken from www.scriptefun.com/transcript-2-using
# sprite-sheets-and-drawing-the-background
# I've added some code to fail if the file wasn't found..
# Note: When calling images_at the rect is the format:
# (x, y, x + offset, y + offset)
class Spritesheet(object):
def __init__(self, filename):
try:
self.sheet = pygame.image.load(filepath(filename)).convert()
except pygame.error, message:
print 'Unable to load spritesheet image:', filepath(filename)
raise SystemExit, message
# Load a specific image from a specific rectangle
def image_at(self, rectangle, colorkey=None):
"Loads image from x,y,x+offset,y+offset"
rect = pygame.Rect(rectangle)
image = pygame.Surface(rect.size).convert()
image.blit(self.sheet, (0, 0), rect)
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, pygame.RLEACCEL)
return image
# Load a whole bunch of images and return them as a list
def images_at(self, rects, colorkey = None):
"Loads multiple images, supply a list of coordinates"
imgs = []
for rect in rects:
imgs.append(self.image_at(rect, colorkey))
return imgs
# Load a whole strip of images
def load_strip(self, rect, image_count, colorkey = None):
"Loads a strip of images and returns them as a list"
tups = []
for x in range(image_count):
tups.append((rect[0]+rect[2]*x, rect[1], rect[2], rect[3]))
return self.images_at(tups, colorkey)
from itertools import chain
def truncline(text, font, maxwidth):
real=len(text)
stext=text
l=font.size(text)[0]
cut=0
a=0
done=1
old = None
while l > maxwidth:
a=a+1
n=text.rsplit(None, a)[0]
if stext == n:
cut += 1
stext= n[:-cut]
else:
stext = n
l=font.size(stext)[0]
real=len(stext)
done=0
return real, done, stext
def wrapline(text, font, maxwidth):
done=0
wrapped=[]
while not done:
nl, done, stext=truncline(text, font, maxwidth)
wrapped.append(stext.strip())
text=text[nl:]
return wrapped
def wrap_multi_line(text, font, maxwidth):
""" returns text taking new lines into account.
"""
lines = chain(*(wrapline(line, font, maxwidth) for line in text.splitlines()))
return list(lines)
| Python |
"""
animation.py
implementation of animations, uses sprite sheets."""
import pygame
import data
class Animation(pygame.sprite.Sprite):
def __init__(self, image, pos, delay_ms):
"give the filename, x,y coords and delay between transitions."
pygame.sprite.Sprite.__init__(self)
s = data.Spritesheet(image)
self.images = s.load_strip((0, 0, 30, 30), 3, colorkey=-1)
self.image = self.images.pop(0)
self.rect = self.image.get_rect(topleft=pos)
self._delay = delay_ms
# the elapsed time since last change.
self._elapsed = 0
def update(self, kwargs):
'update images according to the time elapsed.'
time = kwargs.get('time')
if time:
self._elapsed += time
if self._elapsed > self._delay:
self._elapsed = 0 # reset elapsed time.
try:
self.image = self.images.pop(0)
except IndexError:
self.kill()
| Python |
#
# fan.py
#
# The Fan class
#
import pygame
import data
import constants as c
import sounds
FAN_READY = 0
FAN_BLOW = 1
FAN_SUCK = 2
class Fan(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image_normal, self.rect = data.load_image("fan.png", None)
self.image_blow, _ = data.load_image("fan_blow.png", None)
self.image_suck, _ = data.load_image("fan_suck.png", None)
self.image = self.image_normal
self.rect.topleft = (350, 560)
self.state = FAN_READY
def click(self, button):
# if we are ready to blow/suck
if self.state == FAN_READY:
# add the timer event, controls blow/suck rate
pygame.time.set_timer(c.EVENT_FAN_TIMEOUT, c.EVENT_FAN_TIMEOUT_TIME)
# now check to see which button is pressed and change image
# accordingly
if button == 1:
self.state = FAN_BLOW
self.image = self.image_blow
sounds.play_sfx('fan_blow.wav')
elif button == 3:
self.state = FAN_SUCK
self.image = self.image_suck
sounds.play_sfx('fan_suck.wav')
return True
else:
return False
def timeout(self):
# once timeout is called we can return to the ready state
self.state = FAN_READY
self.image = self.image_normal
def update(self, time_diff):
self.rect.centerx = pygame.mouse.get_pos()[0]
| Python |
import pygame
import constants as c
import data
import bird
class Air(pygame.sprite.Sprite):
def __init__(self, kind, a, b, m):
pygame.sprite.Sprite.__init__(self)
# pass in kind, velocity coeffs (pixels/s) and mass (kg)
self.kind = kind
self.a = a/1000.0
self.b = b/1000.0
self.m = m
# load appropriate image
if self.kind == c.BLOW:
self.image, self.rect = data.load_image("blow.png", -1)
else:
self.image, self.rect = data.load_image("suck.png", -1)
# set up the starting position of the air
if self.kind == c.BLOW:
self.starty = c.BLOW_START_Y
else:
self.starty = c.SUCK_START_Y
self.rect.midtop = (pygame.mouse.get_pos()[0], self.starty)
def update(self, time_diff):
# find the distance between the air and its start point
delta_y = abs(self.rect.top - self.starty)
# calculate its velocity as a function of delta_y
if self.kind == c.BLOW:
self.v = -1.0 * (self.a*delta_y + self.b)
else:
self.v = (self.a * delta_y + self.b)
# update rect position
self.rect.top = self.rect.y + self.v * time_diff
def collide(self, other):
'air has collided with another object'
if isinstance(other, bird.Bird):
self.kill()
| Python |
#
# scorebar.py
#
# implementation of the score bar.
#
import pygame
import data
import constants as c
font = None
def rendertxt(txt):
global font
try:
return font.render(txt, 1, (255, 255, 255))
except AttributeError:
font = pygame.font.Font(None, 26)
return rendertxt(txt)
class Scorebar(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
# store an original copy of the background.
self.orig, self.rect = data.load_image('topbar.png', None)
self.image = self.orig.copy()
self.rect.topleft = (0, 0)
self._stats = { 'dead birds': '0',
'saved birds': '0',
'time elapsed': '0',
'kWh generated': '0'}
# the order in which to show the updates.
self._nowshow = ['dead birds', 'saved birds',
'time elapsed', 'kWh generated']
self._frames = 0
self._dirty = 0
def _clear(self):
'clear the display. and set the dirty flag.'
self.image = self.orig.copy()
self._dirty = 1
def _fps(self, txt):
'write some fps to the display. a debug function. also broken'
self._clear()
# write the text.
txt = rendertxt(txt)
self.image.blit(txt, txt.get_rect(topleft=(10, 10)))
self.update({}) # this breaks the fps function. i have no desire to fix
def update(self, kwargs):
'''update the round robin of text with game stats.
clears the dirty flag.'''
self._clear()
x = 30
for kw, txt in kwargs.items():
if kw in self._stats:
ts = rendertxt('%s = %s' % (kw, txt))
self.image.blit(ts, ts.get_rect(topleft=(x , 10)))
# dirty method to ensure that x does not vary too much frame
# to frame.
x += (ts.get_width() + 50) / 20 * 20
| Python |
#! /usr/bin/env python
from gamelib import main
main.main()
| Python |
#! /usr/bin/env python
from gamelib import main
try:
main.main()
except SystemExit:
pass
| Python |
#! /usr/bin/env python
from gamelib import main
main.main()
| Python |
#! /usr/bin/env python
from gamelib import main
try:
main.main()
except SystemExit:
pass
| Python |
#!/usr/bin/env python2.7
import json
import logging
import os
import pprint as pp
import sys
import unittest
import urllib2
try:
from webtest import TestApp
except:
print """Please install webtest from http://webtest.pythonpaste.org/"""
sys.exit(1)
# Attempt to locate the App Engine SDK based on the system PATH
for d in sorted(os.environ['PATH'].split(os.path.pathsep)):
path = os.path.join(d, 'dev_appserver.py')
if not os.path.isfile(path):
continue
print 'Found the App Engine SDK directory: %s' % d
sys.path.insert(0, d)
# The App Engine SDK root is now expected to be in sys.path (possibly provided via PYTHONPATH)
try:
import dev_appserver
except ImportError:
error_msg = ('The path to the App Engine Python SDK must be in the '
'PYTHONPATH environment variable to run unittests.')
# The app engine SDK isn't in sys.path. If we're on Windows, we can try to
# guess where it is.
import platform
if platform.system() == 'Windows':
sys.path = sys.path + ['C:\\Program Files\\Google\\google_appengine']
try:
import dev_appserver # pylint: disable-msg=C6204
except ImportError:
print error_msg
raise
else:
print error_msg
raise
# add App Engine libraries
sys.path += dev_appserver.EXTRA_PATHS
from google.appengine.ext import testbed
from google.appengine.api import backends
class HttpMatcherTest(unittest.TestCase):
def verifyNodeJsServerRunning(self):
url = 'http://127.0.0.1:12345/ping'
try:
result = urllib2.urlopen(url)
r = json.loads(result.read())
logging.debug('%s -> %s' % (url, r))
self._serverid = r['serverid']
except urllib2.URLError, e:
self.fail('Node.js games-server must be running. Could not connect to %s\n%s' % (url, e))
def get(self, *args, **kwargs):
result = self.app.get(*args, **kwargs)
logging.debug('self.app.get %s %s -> %s' % (args, kwargs, result.body))
return result
def post(self, *args, **kwargs):
result = self.app.post(*args, **kwargs)
logging.debug('self.app.post %s %s -> %s' % (args, kwargs, result.body ))
return result
def setUp(self):
# see testbed docs https://developers.google.com/appengine/docs/python/tools/localunittesting
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_memcache_stub()
self.testbed.init_datastore_v3_stub()
self.testbed.init_urlfetch_stub()
# Pretend we're a matcher backend
self.assertEquals(None, backends.get_backend())
self.save_get_backend = backends.get_backend
backends.get_backend = lambda: 'matcher'
self.assertEquals('matcher', backends.get_backend())
# create TestApp wrapper around client.main.app
from client import main
main._JSON_ENCODER.indent = None
self.app = TestApp(main.app)
#
self.verifyNodeJsServerRunning()
# no maximum length for diffs
self.maxDiff = None
def tearDown(self):
# restore patched methods
backends.get_backend = self.save_get_backend
self.testbed.deactivate()
def test_list_games_starts_emtpy(self):
res = self.get('/list-games')
self.assertEquals('{}', res.body)
def test_start_game(self):
res = self.get('/start-game')
r = json.loads(res.body)
self.assertIn('no-available-servers' , r.get('result'))
def test_start_game2(self):
self.assertTrue(self._serverid)
expected_req = { 'controller_port': 12345, 'serverid': self._serverid, 'pairing_key': 'XXXXXXXXXXXXXXXXXXXXXX' }
expected_res = { 'backend': 'matcher', 'controller_host': '127.0.0.1:12345', 'success': True }
# TODO ensure that in this post, self.request.remote_addr = 127.0.0.1
res = self.post('/register-controller', json.dumps(expected_req), extra_environ={'REMOTE_ADDR': '127.0.0.1'})
r = res.json
self.assertEquals(True, r.get('success'))
self.assertEquals(expected_res, r)
self.verifyNodeJsServerRunning()
res = self.get('/start-game')
r = res.json
self.assertEquals(True, r.get('success'))
name = r.get('name')
self.assertTrue(len(name))
time = r.get('time')
self.assertTrue(time > 0)
game_state = r.get(u'game_state')
self.assertEquals(8, game_state.get(u'max_players'))
self.assertEquals(1, game_state.get(u'min_players'))
self.assertEquals({}, game_state.get(u'players'))
self.assertEquals(name, r.get(u'name'))
self.assertTrue(r.get(u'success'))
self.assertEquals(time, r.get(u'time'))
self.assertEquals(self._serverid, r.get(u'serverid'))
self.assertEquals(u'127.0.0.1:12345', r.get(u'controller_host'))
self.assertEquals(u'http://127.0.0.1:9090/%s' % name, r.get(u'gameURL'))
self.assertEquals(9090, r.get(u'port'))
if __name__ == '__main__':
unittest.main()
| Python |
'''Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
#limitations under the License.'''
from client import db_api
from client import matcher
from google.appengine.api import app_identity
from google.appengine.api import backends
from google.appengine.api import oauth
from google.appengine.api import urlfetch
from google.appengine.api import users
from google.appengine.api.urlfetch import fetch
import cgi
import datetime
import json
import logging
import os
import pprint as pp
import random
import sys
import traceback
import urllib
import webapp2
# constants
_DEBUG = True
_JSON_ENCODER = json.JSONEncoder()
if _DEBUG:
_JSON_ENCODER.indent = 4
_JSON_ENCODER.sort_keys = True
if backends.get_backend() == 'matcher':
_match_maker = matcher.MatchMaker()
_EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email"
_IS_DEVELOPMENT = os.environ['SERVER_SOFTWARE'].startswith('Development/')
#######################################################################
# common functions
#######################################################################
def tojson(python_object):
"""Helper function to output and optionally pretty print JSON."""
return _JSON_ENCODER.encode(python_object)
def fromjson(msg):
"""Helper function to ingest JSON."""
try:
return json.loads(msg)
except Exception, e:
raise Exception('Unable to parse as JSON: %s' % msg)
_PAIRING_KEY = fromjson(open('shared/pairing-key.json').read())['key']
def fetchjson(url, deadline, payload=None):
"""Fetch a remote JSON payload."""
method = "GET"
headers = {}
if payload:
method = "POST"
headers['Content-Type'] = 'application/json'
result = fetch(url, method=method, payload=payload, headers=headers, deadline=deadline).content
return fromjson(result)
def json_by_default_dispatcher(router, request, response):
"""WSGI router which defaults to 'application/json'."""
response.content_type = 'application/json'
return router.default_dispatcher(request, response)
def e(msg):
"""Convient method to raise an exception."""
raise Exception(repr(msg))
def w(msg):
"""Log a warning message."""
logging.warning('##### %s' % repr(msg))
#######################################################################
# frontend related stuff
#######################################################################
# frontend handler
class FrontendHandler(webapp2.RequestHandler):
def determine_user(self):
userID = self.request.get('userID')
if userID:
if _IS_DEVELOPMENT:
return userID, self.request.get('displayName', userID)
if userID.startswith('bot*'):
# we'll use the userID as the displayName
return userID, userID
try:
# TODO avoid http://en.wikipedia.org/wiki/Confused_deputy_problem
user = oauth.get_current_user(_EMAIL_SCOPE)
# TODO instead get a suitable displayName from https://www.googleapis.com/auth/userinfo.profile
return user.user_id(), user.nickname() # '0', 'example@example.com' in dev_appserver
except oauth.OAuthRequestError:
raise Exception("""OAuth2 credentials -or- a valid 'bot*...' userID must be provided""")
# frontend handler
class LoginHandler(FrontendHandler):
def post(self):
# for the admin only auth form
self.get()
def get(self):
config = db_api.getConfig(self.request.host_url)
if not config:
self.request_init()
return
redirectUri = '%s/logup.html' % self.request.host_url
authScope = 'https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/plus.me+https://www.googleapis.com/auth/plus.people.recommended';
returnto = self.request.get('redirect_uri')
authUri = 'http://accounts.google.com/o/oauth2/auth'
authUri += '?scope=' + authScope
authUri += '&redirect_uri=' + redirectUri
authUri += '&response_type=token'
authUri += '&client_id=' + str(config.client_id)
#authUri += '&state=' + returnto
self.response.headers['Access-Control-Allow-Origin'] = '*'
logging.debug('authUri=%s' % authUri)
self.redirect(authUri)
def request_init(self):
user = users.get_current_user()
if user:
if users.is_current_user_admin():
client_id = self.request.get('client_id')
client_secret = self.request.get('client_secret')
api_key = self.request.get('api_key')
if client_id and client_secret and api_key:
db_api.setConfig(self.request.host_url, client_id, client_secret, api_key)
body = 'Thank you! You may now <a href="javascript:window.location.reload();">reload</a> this page.'
else:
body = """Please enter the following information from the
<a href="https://developers.google.com/console" target="_blank">Developer Console<a> <b>%s</b> project:<br><br>
<form method="post">
<h3>Client ID for web applications<h3>
client_id:<input name="client_id"><br>
client_secret:<input name="client_secret"><br>
<h3>Simple API Access<h3>
api_key:<input name="api_key"><br>
<input type="submit">
</form>""" % self.request.host_url
else:
body = 'You (%s) are not an admin. Please <a href="%s">logout</a>.' % (user.email(), users.create_logout_url(self.request.path))
else:
body = 'Please <a href="%s">login</a> as an admin.' % users.create_login_url(self.request.path)
self.response.headers['Content-Type'] = 'text/html'
self.response.write('<html><body><h1>Datastore configuration</h1>%s</body></html>' % body)
# frontend handler
class Login(FrontendHandler):
def post(self):
self.response.headers['Access-Control-Allow-Origin'] = '*'
userID, displayName = self.determine_user()
usr = db_api.getUser(userID)
if not usr:
usr = db_api.newUser(userID, displayName)
r = {'userID': userID, 'displayName': displayName}
self.response.write(tojson(r) + '\n')
# frontend handler
class GritsService(FrontendHandler):
# TODO per client (userID) throttling to limit abuse
def post(self, fcn):
logging.info('%s ...' % self.request.url)
if not fcn:
fcn = self.request.get('fcn')
if fnc:
# TODO remove once there are no more uses of ?fcn=... in our code
logging.warning('Please use /grits/%s/?foo=... instead of /grits/?fcn=%s&foo=...' % (fnc, fnc))
self.response.headers['Access-Control-Allow-Origin'] = '*'
userID, displayName = self.determine_user()
usr = db_api.getUser(userID)
if not usr:
if userID.startswith('bot*'):
usr = db_api.newUser(userID, displayName)
else:
self.response.set_status(404)
self.response.write('Grits userID not found: ' + userID)
return
if fcn == 'getProfile':
r = {'userID': userID, 'credits': str(usr.credits), 'numWins': str(usr.numWins), 'virtualItems': usr.virtualItems}
self.response.write(tojson(r))
elif fcn == 'getFriends':
self.getFriends(userID)
elif fcn == 'buyItem':
itemID = self.request.get('itemID')
if not itemID:
self.response.set_status(400)
self.response.write('Grits itemID is required')
return
r = db_api.userAttemptToBuy(userID, itemID)
self.response.write(tojson(r))
elif fcn == 'findGame':
self.findGame(userID)
else:
self.response.set_status(400)
self.response.write('Bad grits request.')
def findGame(self, userID):
# forward the request to the matcher backend
url = '%s/find-game/%s' % (backends.get_url(backend='matcher', instance=None, protocol='HTTP'), userID)
payload = '{}'
resp = urlfetch.fetch(url=url,
payload=payload,
method=urlfetch.POST,
headers={'Content-Type': 'application/json'})
self.response.set_status(resp.status_code)
self.response.headers.update(resp.headers)
self.response.write(resp.content)
logging.info('%s -> %s -> %s' % (repr(payload), url, resp.content))
def getFriends(self, userID):
config = db_api.getConfig(self.request.host_url)
assert config.api_key
token = self.request.get('accessToken')
reqUri = 'https://www.googleapis.com/plus/v1games/people/me/people/recommended';
reqUri += '?key=' + config.api_key;
reqUri += '&access_token=' + token;
result = fetchjson(reqUri, None)
self.response.write(tojson(result))
#self.response.headers['Content-Type'] = 'application/json'
#self.response.headers['Access-Control-Allow-Origin'] = '*'
#self.redirect(reqUri)
# frontend handler
class PurchaseService(FrontendHandler):
def get(self):
iap.serverPurchasePostback(self)
# frontend handler
class SharedJsonAssets(FrontendHandler):
def get(self, filename):
f = open(filename, 'r')
self.response.write(f.read())
f.close()
#######################################################################
# 'matcher' backend related stuff
#######################################################################
# 'matcher' backend handler
class JsonHandler(webapp2.RequestHandler):
"""Convenience class for handling JSON requests."""
def handle(self, params, *args):
raise Exception('subclasses must implement this method')
def post(self, *args):
logging.info('%s <- %s' % (self.request.path, self.request.body))
try:
if not self.request.body:
raise Exception('Empty request')
params = fromjson(self.request.body)
r = self.handle(params, *args)
if not r:
raise Exception('Unexpected empty response from subclass')
self.response.write(tojson(r))
except:
# clients must already be prepared to deal with non-JSON responses,
# so a raw, human readable, stack trace is fine here
self.response.set_status(500)
tb = traceback.format_exc()
logging.warn(tb)
self.response.write(tb)
# 'matcher' backend handler
class FindGame(JsonHandler):
def handle(self, params, userID):
pingAll()
return self.get_game(userID)
def get_game(self, userID):
# previously matched / player re-entering?
player_game = _match_maker.lookup_player_game(userID)
if player_game:
return player_game
# look for a new available game
result = self._get_player_game(userID)
# found a game?
if result and 'game' in result:
player_game = result
usr = db_api.getUser(userID)
addPlayers(player_game, userID, usr.displayName)
return result
# more players needed to start game?
if result.get('players_needed_for_next_game', None) > 0:
return result
# start a new game
game = startGame()
if 'game_state' not in game:
logging.info('RETURNING RESULT FROM startGame(): %s' % game)
return game
logging.info('RETURNING RESULT: %s' % result)
return result
def _get_player_game(self, userID):
player_game = _match_maker.find_player_game(userID)
return player_game
# 'matcher' backend handler
class UpdateGameState(JsonHandler):
def handle(self, params, *args):
serverid = params['serverid']
new_game_state = params['game_state']
game_name = new_game_state['name']
_match_maker.update_player_names(serverid, game_name, new_game_state)
return {'success': True,
'backend': backends.get_backend()}
# 'matcher' backend handler
class RegisterController(JsonHandler):
def handle(self, params, *args):
if _PAIRING_KEY != params['pairing_key']:
return {'success': False,
'exception': 'bad pairing key'}
controller_port = params['controller_port']
ip = self.request.remote_addr
controller_host = '%s:%d' % (ip, controller_port)
params['controller_host'] = controller_host
_match_maker.update_server_info(params)
return {'success': True,
'backend': backends.get_backend(),
'controller_host': controller_host}
# 'matcher' backend handler
class ListGames(webapp2.RequestHandler):
def get(self):
self.response.write(tojson(pingAll()))
# 'matcher' backend handler
class Debug(webapp2.RequestHandler):
def get(self):
state = _match_maker.get_state()
self.response.write(tojson(state))
# 'matcher' backend handler
class StartGame(webapp2.RequestHandler):
def get(self):
self.response.write(tojson(startGame()))
# 'matcher' backend handler
class LogFiles(webapp2.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/html'
self.response.write('<html><body><h1>Log Files</h1>')
for serverid in _match_maker.get_game_servers():
server_info = _match_maker.get_game_server_info(serverid)
self.response.write('<p>%(id)s: '
'<a href="http://%(svr)s/forever.log">error</a> '
'<a href="http://%(svr)s/log">console</a> '
'<a href="http://%(svr)s/ping">ping</a> '
'<a href="http://%(svr)s/enable-dedup">enable-dedup</a> '
'<a href="http://%(svr)s/disable-dedup">disable-dedup</a> '
'</p>' %
{'id':serverid,
'svr':server_info['controller_host']})
self.response.write('</body></html>')
# 'matcher' backend handler
class GameOver(JsonHandler):
def handle(self, params, *args):
_match_maker.del_game(params['serverid'], params['name'])
return {'success': True, 'backend': backends.get_backend()}
# 'matcher' backend helper function
def pingAll():
removeserver = []
# TODO use async urlfetch to parallelize url fetch calls
for serverid in _match_maker.get_game_servers():
server_info = _match_maker.get_game_server_info(serverid)
url = 'http://%s/ping' % server_info['controller_host']
try:
r = fetchjson(url, 2)
logging.debug('pingAll(): %s -> %s' % (url, r))
except:
logging.warn('pingAll(): EXCEPTION %s' % traceback.format_exc())
removeserver.append(serverid)
if r['serverid'] != serverid:
removeserver.append(serverid)
continue
# check for games which have ended without our knowledge
remotegameinfo = r['gameinfo']
server_struct = _match_maker.get_game_server_struct(serverid)
games = server_struct['games']
removegame = []
for name, game in games.iteritems():
if name not in remotegameinfo:
# the game is unexpectedly gone
logging.warn('serverid %s unexpectedly lost game %s (did we miss a /game-over callback?)' % (serverid, name))
removegame.append(name)
for name in removegame:
_match_maker.del_game(serverid, name)
for serverid in removeserver:
_match_maker.del_game_server(serverid)
return _match_maker.get_game_servers()
# 'matcher' backend helper function
def rateUsage(r):
return max(int(r['cpu']), int(r['mem']))
# 'matcher' backend helper function
def startGame():
logging.debug('startGame()')
best = None
bestServer = None
for serverid, server_struct in pingAll().iteritems():
if not best or rateUsage(best) > rateUsage(r):
server_info = server_struct['server_info']
best = server_info
bestServer = best['controller_host']
if bestServer:
url = 'http://%s/start-game?p=%s' % (bestServer, _PAIRING_KEY)
game = fetchjson(url, 20)
logging.debug('startGame(): %s -> %s' % (url, tojson(game)))
if game.get('success', False):
ip = bestServer.split(':')[0]
game['gameURL'] = 'http://%s:%s/%s' % (ip, game['port'], game['name'])
game['controller_host'] = bestServer
game['serverid'] = best['serverid']
_match_maker.update_game(game)
return game
else:
return {'result': 'no-available-servers'}
def addPlayers(player_game, userID, displayName):
logging.info('addPlayers(player_game=%s, userID=%s, displayName=%s)' % (player_game, userID, displayName))
game = player_game['game']
url = 'http://%s/add-players?p=%s' % (game['controller_host'], _PAIRING_KEY)
player_game_key = player_game['player_game_key']
msg = {
'userID': userID,
'displayName': displayName,
'game_name' : game['name'],
'player_game_key': player_game_key,
}
try:
result = fetchjson(url, 20, payload=tojson(msg))
logging.info('addPlayers(): %s -> %s -> %s' % (tojson(msg), url, tojson(result)))
return {
'game': game,
'player_game_key': player_game_key,
'success': True,
}
except:
exc = traceback.format_exc()
logging.info('addPlayers(): %s -> %s -> %s' % (tojson(msg), url, exc))
return {
'success' : False,
'exception': exc,
}
#######################################################################
# handler common to frontends and backends
handlers = [
]
if not backends.get_backend():
# frontend specific handlers
handlers.extend([
('/login', Login),
('/loginoauth', LoginHandler),
('/grits/(.*)', GritsService),
('/(shared/.*\.json)', SharedJsonAssets),
])
elif backends.get_backend() == 'matcher':
# 'matcher' backend specific handlers
handlers.extend([
('/find-game/(.*)', FindGame),
('/update-game-state', UpdateGameState),
('/register-controller', RegisterController),
('/list-games', ListGames),
('/debug', Debug),
('/start-game', StartGame),
('/game-over', GameOver),
('/log-files', LogFiles),
])
app = webapp2.WSGIApplication(handlers, debug=True)
app.router.set_dispatcher(json_by_default_dispatcher)
| Python |
'''Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.'''
from google.appengine.api import apiproxy_stub_map
from google.appengine.api import backends
from google.appengine.api import runtime
import datetime
import logging
_NAME = '{}.{} {} ({})'.format(backends.get_backend(),
backends.get_instance(),
backends.get_url(),
datetime.datetime.now())
def my_shutdown_hook():
logging.warning('{} SHUTDOWN HOOK CALLED'.format(_NAME))
apiproxy_stub_map.apiproxy.CancelApiCalls()
# save_state()
# May want to raise an exception
# register our shutdown hook, which is not guaranteed to be called
logging.info('{} REGISTERING SHUTDOWN HOOK'.format(_NAME))
runtime.set_shutdown_hook(my_shutdown_hook)
| Python |
#!/usr/bin/env python
import optparse
import jwt
import sys
import json
import time
__prog__ = 'jwt'
__version__ = '0.1'
""" JSON Web Token implementation
Minimum implementation based on this spec:
http://self-issued.info/docs/draft-jones-json-web-token-01.html
"""
import base64
import hashlib
import hmac
try:
import json
except ImportError:
import simplejson as json
__all__ = ['encode', 'decode', 'DecodeError']
class DecodeError(Exception): pass
signing_methods = {
'HS256': lambda msg, key: hmac.new(key, msg, hashlib.sha256).digest(),
'HS384': lambda msg, key: hmac.new(key, msg, hashlib.sha384).digest(),
'HS512': lambda msg, key: hmac.new(key, msg, hashlib.sha512).digest(),
}
def base64url_decode(input):
input += '=' * (4 - (len(input) % 4))
return base64.urlsafe_b64decode(input)
def base64url_encode(input):
return base64.urlsafe_b64encode(input).replace('=', '')
def header(jwt):
header_segment = jwt.split('.', 1)[0]
try:
return json.loads(base64url_decode(header_segment))
except (ValueError, TypeError):
raise DecodeError("Invalid header encoding")
def encode(payload, key, algorithm='HS256'):
segments = []
header = {"typ": "JWT", "alg": algorithm}
segments.append(base64url_encode(json.dumps(header)))
segments.append(base64url_encode(json.dumps(payload)))
signing_input = '.'.join(segments)
try:
if isinstance(key, unicode):
key = key.encode('utf-8')
signature = signing_methods[algorithm](signing_input, key)
except KeyError:
raise NotImplementedError("Algorithm not supported")
segments.append(base64url_encode(signature))
return '.'.join(segments)
def decode(jwt, key='', verify=True):
try:
signing_input, crypto_segment = jwt.rsplit('.', 1)
header_segment, payload_segment = signing_input.split('.', 1)
except ValueError:
raise DecodeError("Not enough segments")
try:
header = json.loads(base64url_decode(header_segment))
payload = json.loads(base64url_decode(payload_segment))
signature = base64url_decode(crypto_segment)
except (ValueError, TypeError):
raise DecodeError("Invalid segment encoding")
if verify:
try:
if isinstance(key, unicode):
key = key.encode('utf-8')
if not signature == signing_methods[header['alg']](signing_input, key):
raise DecodeError("Signature verification failed")
except KeyError:
raise DecodeError("Algorithm not supported")
return payload
def fix_optionparser_whitespace(input):
"""Hacks around whitespace Nazi-ism in OptionParser"""
newline = ' ' * 80
doublespace = '\033[8m.\033[0m' * 2
return input.replace(' ', doublespace).replace('\n', newline)
def main():
"""Encodes or decodes JSON Web Tokens based on input
Decoding examples:
%prog --key=secret json.web.token
%prog --no-verify json.web.token
Encoding requires the key option and takes space separated key/value pairs
separated by equals (=) as input. Examples:
%prog --key=secret iss=me exp=1302049071
%prog --key=secret foo=bar exp=+10
The exp key is special and can take an offset to current Unix time.
"""
p = optparse.OptionParser(description=fix_optionparser_whitespace(main.__doc__),
prog=__prog__,
version='%s %s' % (__prog__, __version__),
usage='%prog [options] input')
p.add_option('-n', '--no-verify', action='store_false', dest='verify', default=True,
help='ignore signature verification on decode')
p.add_option('--key', dest='key', metavar='KEY', default=None,
help='set the secret key to sign with')
p.add_option('--alg', dest='algorithm', metavar='ALG', default='HS256',
help='set crypto algorithm to sign with. default=HS256')
options, arguments = p.parse_args()
if len(arguments) > 0 or not sys.stdin.isatty():
# Try to decode
try:
if not sys.stdin.isatty():
token = sys.stdin.read()
else:
token = arguments[0]
valid_jwt = jwt.header(token)
if valid_jwt:
try:
print json.dumps(jwt.decode(token, key=options.key, verify=options.verify))
sys.exit(0)
except jwt.DecodeError, e:
print e
sys.exit(1)
except jwt.DecodeError:
pass
# Try to encode
if options.key is None:
print "Key is required when encoding. See --help for usage."
sys.exit(1)
# Build payload object to encode
payload = {}
for arg in arguments:
try:
k,v = arg.split('=', 1)
# exp +offset special case?
if k == 'exp' and v[0] == '+' and len(v) > 1:
v = str(int(time.time()+int(v[1:])))
# Cast to integer?
if v.isdigit():
v = int(v)
else:
# Cast to float?
try:
v = float(v)
except ValueError:
pass
# Cast to true, false, or null?
constants = {'true': True, 'false': False, 'null': None}
if v in constants:
v = constants[v]
payload[k] = v
except ValueError:
print "Invalid encoding input at %s" % arg
sys.exit(1)
try:
print jwt.encode(payload, key=options.key, algorithm=options.algorithm)
sys.exit(0)
except Exception, e:
print e
sys.exit(1)
else:
p.print_help()
if __name__ == '__main__':
main()
| Python |
'''Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
#limitations under the License.'''
from google.appengine.api import backends
from google.appengine.api import users
import copy
import logging
import pprint as pp
import random
import sys
from client import db_api
def e(msg):
"""Convient method to raise an exception."""
raise Exception(repr(msg))
def w(msg):
"""Log a warning message."""
logging.warning('##### %s' % repr(msg))
class MatchMaker:
"""
Multiple player match making service, allowing players
to come together in an arena to show off their skills.
_game_servers =
{ serverid1: <server_struct>,
serverid2: <server_struct>,
}
<server_struct> =
{ 'server_info': <server_info>,
'games': { name1: <game>,
name2: <game>,
},
}
<server_info> =
{ 'serverid': ...,
'uptime': ...,
}
<game> =
{ serverid': ...,
'name': 'mPdn',
'gameURL': 'http://127.0.0.1:9090/mPdn',
'port': 9090,
'controller_host': '127.0.0.1:12345',
'game_state': {'players': {'324324382934982374823748923': '!1'}, 'min_players': 2, 'max_players': 8},
}
"""
_EMPTY_SERVER = { 'games' : {} }
def __init__(self):
self._game_servers = {}
self._players_waiting = []
self._players_playing = {}
def get_game_server_struct(self, serverid):
assert serverid
return self._game_servers.get(serverid, None)
def get_game_server_info(self, serverid):
assert serverid
server_struct = self.get_game_server_struct(serverid)
return server_struct['server_info']
def _set_game_server_struct(self, serverid, server_struct):
self._game_servers[serverid] = server_struct
def _set_game_server_info(self, serverid, server_info):
assert serverid
assert server_info
server_struct = self.get_game_server_struct(serverid)
if not server_struct:
server_struct = copy.deepcopy(MatchMaker._EMPTY_SERVER)
self._set_game_server_struct(serverid, server_struct)
server_struct['server_info'] = server_info
def get_state(self):
return {
'game_servers': self._game_servers,
'players_waiting': self._players_waiting,
'players_playing': self._players_playing,
}
def get_game_servers(self):
return self._game_servers
def del_game_server(self, serverid):
del self._game_servers[serverid]
remove = []
for player, player_game in self._players_playing.iteritems():
game = player_game['game']
if game['serverid'] == serverid:
remove.append(player)
for r in remove:
self._players_playing.pop(r)
def update_player_names(self, serverid, game_name, new_game_state):
server_struct = self.get_game_server_struct(serverid)
games = server_struct['games']
game = games[game_name]
game_state = game['game_state']
players = game_state['players']
new_players = new_game_state['players']
logging.info('Updating %s with %s' % (repr(players), repr(new_players)))
assert isinstance(players, dict)
assert isinstance(new_players, dict)
players.update(new_players)
def update_server_info(self, server_info):
serverid = server_info['serverid']
self._set_game_server_info(serverid, server_info)
def update_game(self, game):
serverid = game['serverid']
name = game['name']
assert serverid in self._game_servers
server_struct = self.get_game_server_struct(serverid)
games = server_struct['games']
games[name] = game
def del_game(self, serverid, game_name):
server_struct = self.get_game_server_struct(serverid)
games = server_struct['games']
game = games[game_name]
game_state = game['game_state']
players = game_state['players']
for p in players:
self._players_playing.pop(p)
del games[game_name]
def _add_player(self, userID, game):
assert isinstance(userID, str)
game_state = game['game_state']
min_players = int(game_state['min_players'])
max_players = int(game_state['max_players'])
players = game_state['players']
assert max_players >= min_players
assert len(players) < max_players
assert userID not in game_state['players']
players[userID] = 'TBD'
self._players_playing[userID] = {
'game': game,
'player_game_key': str(random.randint(-sys.maxint, sys.maxint)),
'userID': userID, # used by Android client
}
def make_matches(self):
if not self._players_waiting:
return
# TODO match based on skills instead of capacity
players_needed_for_next_game = self.make_matches_min_players()
if self._players_waiting:
self.make_matches_max_players()
return players_needed_for_next_game
def make_matches_min_players(self):
players_needed_for_next_game = -1
for server_struct in self._game_servers.itervalues():
for game in server_struct['games'].itervalues():
game_state = game['game_state']
players_in_game = game_state['players']
player_goal = int(game_state['min_players'])
players_needed = player_goal - len(players_in_game)
if not players_needed:
continue
if len(self._players_waiting) >= players_needed:
# let's get this party started
while len(players_in_game) < player_goal:
self._add_player(self._players_waiting.pop(0), game)
elif (players_needed_for_next_game == -1
or players_needed < players_needed_for_next_game):
players_needed_for_next_game = players_needed
return players_needed_for_next_game
def make_matches_max_players(self):
for server_struct in self._game_servers.itervalues():
for game in server_struct['games'].itervalues():
game_state = game['game_state']
players_in_game = game_state['players']
if len(players_in_game) < int(game_state['min_players']):
continue
player_goal = int(game_state['max_players'])
if len(players_in_game) == player_goal:
continue
while self._players_waiting and len(players_in_game) < player_goal:
self._add_player(self._players_waiting.pop(0), game)
def lookup_player_game(self, userID):
assert isinstance(userID, str)
return self._players_playing.get(userID, None)
def find_player_game(self, userID):
assert isinstance(userID, str)
if userID not in self._players_waiting:
self._players_waiting.append(userID)
players_needed_for_next_game = self.make_matches()
if userID in self._players_waiting:
#logging.info('find_player_game: %s must wait a little bit longer' % userID)
return {'result': 'wait', 'players_needed_for_next_game': players_needed_for_next_game}
player_game = self._players_playing.get(userID, None)
if not player_game:
raise Exception('userID %s is not in self._players_playing' % userID)
return player_game
| 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.