[Python-checkins] python/nondist/sandbox/twister Makefile,NONE,1.1 MersenneTwister.c,NONE,1.1 setup.py,NONE,1.1 test_twister.py,NONE,1.1

rhettinger@users.sourceforge.net rhettinger@users.sourceforge.net
Mon, 16 Dec 2002 16:22:48 -0800


Update of /cvsroot/python/python/nondist/sandbox/twister
In directory sc8-pr-cvs1:/tmp/cvs-serv18101/twister

Added Files:
	Makefile MersenneTwister.c setup.py test_twister.py 
Log Message:
Added draft version of MersenneTwister to the sandbox.
Needs code reviews, more tests, and integration with random.py.
Anyone is welcome to make changes directly.


--- NEW FILE: Makefile ---
PYTHON=python2.3

DTSO=   MersenneTwister.so

all:	$(DTSO)

$(DTSO): MersenneTwister.c
	$(PYTHON) setup.py build_ext -i

test:	$(DTSO)
        $(PYTHON) test_twister.py

clean:
	rm -rf $(DTSO) build *.pyc *.pyo *~

--- NEW FILE: MersenneTwister.c ---

/* Random objects */

/* ------------------------------------------------------------------
   The code in this module was based on a download from:
          http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html

   It was modified in 2002 by Raymond Hettinger as follows:

	* the principal computational lines were untouched.

	* combined genrand_int32() and genrand_res53() into a 
	  single function, random_random().

	* random_random() and the helper functions, init_genrand() 
	  and init_by_array(), were declared static, wrapped in
	  Python calling/return code, and had the global data 
	  references replaced with structure references.

	* to simplify code verification, the original code and its
	  adjacent wrappers were not converted to Python's preferred
	  style for C code.  Instead, the code was left with its
	  original indentation and coding conventions.

	* unused functions from the original were deleted.
	  new, original C python code was added to implement Random()
	  interface.
   
   The following are the verbatim comments from the original code:

   A C-program for MT19937, with initialization improved 2002/1/26.
   Coded by Takuji Nishimura and Makoto Matsumoto.

   Before using, initialize the state by using init_genrand(seed)  
   or init_by_array(init_key, key_length).

   Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
   All rights reserved.                          

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

     1. Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.

     2. Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.

     3. The names of its contributors may not be used to endorse or promote 
        products derived from this software without specific prior written 
        permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


   Any feedback is very welcome.
   http://www.math.keio.ac.jp/matumoto/emt.html
   email: matumoto@math.keio.ac.jp
*/

/* ---------------------------------------------------------------*/

#include "Python.h"
#include <time.h>		// for seeding to current time

/* Period parameters -- These are all magic.  Don't change. */  
#define N 624
#define M 397
#define MATRIX_A 0x9908b0dfUL   /* constant vector a */
#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
#define LOWER_MASK 0x7fffffffUL /* least significant r bits */

static PyObject *ErrorObject;

typedef struct {
	PyObject_HEAD
	unsigned long state[N]; 
	int index;
} RandomObject;

static PyTypeObject Random_Type;

#define RandomObject_Check(v)      ((v)->ob_type == &Random_Type)


/* Random methods */

static PyObject *
random_random(RandomObject *self)
{
    unsigned long y, z;
    static unsigned long mag01[2]={0x0UL, MATRIX_A};
    /* mag01[x] = x * MATRIX_A  for x=0,1 */
    unsigned long *mt;
    double result;

    mt = self->state;
    if (self->index >= N) { /* generate N words at one time */
        int kk;

        for (kk=0;kk<N-M;kk++) {
            y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
            mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
        }
        for (;kk<N-1;kk++) {
            y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
            mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
        }
        y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
        mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];

        self->index = 0;
    }
  
    y = mt[self->index++];
    y ^= (y >> 11);
    y ^= (y << 7) & 0x9d2c5680UL;
    y ^= (y << 15) & 0xefc60000UL;
    y ^= (y >> 18);

    assert(N%2 == 0 && self->index < N);
    z = mt[self->index++];   /* doesn't range check.  relies on N being even */
    z ^= (z >> 11);
    z ^= (z << 7) & 0x9d2c5680UL;
    z ^= (z << 15) & 0xefc60000UL;
    z ^= (z >> 18);
    result = ((y>>5)*67108864.0+(z>>6))*(1.0/9007199254740992.0);
    return PyFloat_FromDouble(result);
}

/* initializes mt[N] with a seed */
static PyObject * 
init_genrand(RandomObject *self, unsigned long s)
{
    int mti;
    unsigned long *mt;

    assert(RandomObject_Check(self));
    mt = self->state;
    mt[0]= s & 0xffffffffUL;
    for (mti=1; mti<N; mti++) {
        mt[mti] = 
	    (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); 
        /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
        /* In the previous versions, MSBs of the seed affect   */
        /* only MSBs of the array mt[].                        */
        /* 2002/01/09 modified by Makoto Matsumoto             */
        mt[mti] &= 0xffffffffUL;
        /* for >32 bit machines */
    }
    self->index = mti;
    Py_INCREF(Py_None);
    return Py_None;
}

/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
static PyObject * 
init_by_array(RandomObject *self, unsigned long init_key[], unsigned long key_length)
{
    unsigned int i, j, k;	/* was signed in the original code. RDH 12/16/2002 */
    unsigned long *mt;

    mt = self->state;
    init_genrand(self, 19650218UL);
    i=1; j=0;
    k = (N>key_length ? N : key_length);
    for (; k; k--) {
        mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
          + init_key[j] + j; /* non linear */
        mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
        i++; j++;
        if (i>=N) { mt[0] = mt[N-1]; i=1; }
        if (j>=key_length) j=0;
    }
    for (k=N-1; k; k--) {
        mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
          - i; /* non linear */
        mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
        i++;
        if (i>=N) { mt[0] = mt[N-1]; i=1; }
    }

    mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ 
    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
random_seed(RandomObject *self, PyObject *args)
{
	time_t now;
	unsigned long *key;
	unsigned long keylength;
	long seed;
	unsigned int i;
	PyObject *result;

	keylength = PyTuple_Size(args);
	if (keylength == 0) {
		time(&now);
		return init_genrand(self, (unsigned long)now);
	}

	key = (unsigned long *) PyMem_MALLOC(keylength * sizeof(unsigned long));
	if (key == NULL)
		return NULL;
	
	for (i=0; i<keylength ; i++) {
		seed = PyInt_AsLong(PyTuple_GET_ITEM(args, i));
		if (seed == -1 && PyErr_Occurred()) {
			PyMem_FREE(key);
			return NULL;
		}
		key[i] = (unsigned long)seed;
	}

	result = init_by_array(self, key, keylength);
	PyMem_FREE(key);
	return result;
}

static PyObject *
random_getstate(RandomObject *self)
{
	PyObject *state;
	PyObject *element;
	int i;

	state = PyTuple_New(N+1);
	if (state == NULL)
		return NULL;
	for (i=0; i<N ; i++) {
		element = PyInt_FromLong((long)(self->state[i]));
		if (element == NULL)
			goto Fail;
		PyTuple_SET_ITEM(state, i, element);
	}
	element = PyInt_FromLong((long)(self->index));
	if (element == NULL)
		goto Fail;
	PyTuple_SET_ITEM(state, i, element);
	return state;

Fail:
	for (i=i-1; i>=0 ; i--)
		Py_DECREF(PyTuple_GET_ITEM(state, i));
	Py_DECREF(state);
	return NULL;
}

static PyObject *
random_setstate(RandomObject *self, PyObject *state)
{
	int i;
	long element;

	if (!PyTuple_Check(state)) {
		PyErr_SetString(PyExc_TypeError, 
			"state vector must be a tuple");
		return NULL;
	}
	if (PyTuple_Size(state) != N+1) {
		PyErr_SetString(PyExc_ValueError, 
			"state vector is the wrong size");
		return NULL;
	}

	for (i=0; i<N ; i++) {
		element = PyInt_AsLong(PyTuple_GET_ITEM(state, i));
		if (element == -1 && PyErr_Occurred())
			return NULL;
		self->state[i] = (unsigned long)element;
	}

	element = PyInt_AsLong(PyTuple_GET_ITEM(state, i));
	if (element == -1 && PyErr_Occurred())
		return NULL;
	self->index = (int)element;

	Py_INCREF(Py_None);
	return Py_None;
}

#define SLICESIZE 6

static PyObject *
random_jumpahead(RandomObject *self, PyObject *spinvalue)
{
	unsigned long init_key[SLICESIZE];
	unsigned long spin;
	int i;

	spin = PyInt_AsLong(spinvalue);
	if (spin == -1 && PyErr_Occurred())
		return NULL;

	for (i=0 ; i<SLICESIZE ; i++)
		init_key[i] = self->state[i];
	init_key[0] ^= spin;
	init_key[1] ^= spin + 0x123;

	return init_by_array(self, init_key, SLICESIZE);
}

static PyObject *   // XXX ? make an iterator  ? remove from interface when testing is done
random_randomlist(RandomObject *self, PyObject *cnt)
{
	long count, i;
	PyObject *list;

	count = PyInt_AsLong(cnt);
	if (count == -1  && PyErr_Occurred())
		return NULL;
	list = PyList_New((int) count);
	if (list == NULL)
		return NULL;
	for (i=0 ; i<count ; i++)
		PyList_SET_ITEM(list, i, random_random(self));
	return list;
}

static PyMethodDef random_methods[] = {
        {"random",      (PyCFunction)random_random,  METH_NOARGS,
		PyDoc_STR("random() -> x in the interval [0,1).")},
        {"seed",	(PyCFunction)random_seed,  METH_VARARGS,
		PyDoc_STR("seed(*seeds) -> None.  Defaults to current time")},
        {"getstate",    (PyCFunction)random_getstate,  METH_NOARGS,
		PyDoc_STR("getstate() -> tuple containing the current state.")},
        {"setstate",      (PyCFunction)random_setstate,  METH_O,
		PyDoc_STR("setstate(state) -> None.  Restores generator state.")},
	{"jumpahead",	(PyCFunction)random_jumpahead,  METH_O,
		PyDoc_STR("jumpahead(int) -> None.  Create a new state from\n\
the existing state and the supplied integer.")},
	{"randomlist",	(PyCFunction)random_randomlist,  METH_O,
		PyDoc_STR("randomlist(len) -> list.  Return a list of random floats.")},
	{NULL,		NULL}		/* sentinel */
};

/* Create New Instance */

static PyObject *
random_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
        RandomObject *self;
        self = (RandomObject *)PyObject_New(RandomObject, &Random_Type);
	if (self == NULL)
		return NULL;
	if (random_seed(self, args) == NULL) {
		Py_DECREF(self);
		return NULL;
	}
	return (PyObject *)self;
}

PyDoc_STRVAR(random_doc,
"Random() -> create a random number generator with its own internal state.");

static PyTypeObject Random_Type = {
	/* The ob_type field must be initialized in the module init function
	 * to be portable to Windows without using C++. */
	PyObject_HEAD_INIT(NULL)
	0,				/*ob_size*/
        "MersenneTwister.Random",	/*tp_name*/
        sizeof(RandomObject),		/*tp_basicsize*/
	0,				/*tp_itemsize*/
	/* methods */
        (destructor)PyObject_Del,	/*tp_dealloc*/
	0,				/*tp_print*/
        0,				/*tp_getattr*/
        0,				/*tp_setattr*/
	0,				/*tp_compare*/
	0,				/*tp_repr*/
	0,				/*tp_as_number*/
	0,				/*tp_as_sequence*/
	0,				/*tp_as_mapping*/
	0,				/*tp_hash*/
        0,				/*tp_call*/
        0,				/*tp_str*/
        PyObject_GenericGetAttr,	/*tp_getattro*/
        0,				/*tp_setattro*/
        0,				/*tp_as_buffer*/
        Py_TPFLAGS_DEFAULT,		/*tp_flags*/
        random_doc,			/*tp_doc*/
        0,				/*tp_traverse*/
        0,				/*tp_clear*/
        0,				/*tp_richcompare*/
        0,				/*tp_weaklistoffset*/
        0,				/*tp_iter*/
        0,				/*tp_iternext*/
        random_methods,			/*tp_methods*/
        0,				/*tp_members*/
        0,				/*tp_getset*/
        0,				/*tp_base*/
        0,				/*tp_dict*/
        0,				/*tp_descr_get*/
        0,				/*tp_descr_set*/
        0,				/*tp_dictoffset*/
        0,				/*tp_init*/
        PyType_GenericAlloc,		/*tp_alloc*/
        random_new,			/*tp_new*/
        0,				/*tp_free*/
        0,				/*tp_is_gc*/
};

PyDoc_STRVAR(module_doc,
"Module implements the Mersenne Twister random number generator .");

static PyMethodDef module_functions[] = {
        {"Random",      (PyCFunction)random_new,  METH_VARARGS,
		PyDoc_STR("Random(*seeds) -> RandomObject")},
	{NULL,		NULL}		/* sentinel */
};

PyMODINIT_FUNC
initMersenneTwister(void)
{
	PyObject *m;

	/* Initialize the type of the new type object here; doing it here
	 * is required for portability to Windows without requiring C++. */
	Random_Type.ob_type = &PyType_Type;

	/* Create the module and add the functions */
	m = Py_InitModule3("MersenneTwister", module_functions, module_doc);

	/* Add some symbolic constants to the module */
	if (ErrorObject == NULL) {
		ErrorObject = PyErr_NewException("MersenneTwister.error", NULL, NULL);
		if (ErrorObject == NULL)
			return;
	}
	Py_INCREF(ErrorObject);
	PyModule_AddObject(m, "error", ErrorObject);
}


--- NEW FILE: setup.py ---
from distutils.core import setup, Extension

setup(name="MersenneTwister", version = "0.1",
      ext_modules=[Extension("MersenneTwister", ["MersenneTwister.c"])])

--- NEW FILE: test_twister.py ---
#!/usr/bin/env python

import unittest
import operator
import MersenneTwister
import time
from test import test_support

class TestBasicOps(unittest.TestCase):
    def setUp(self):
        self.gen = MersenneTwister.Random()
        
    def test_autoseed(self):
        self.gen.seed()
        state1 = self.gen.getstate()
        time.sleep(1)
        self.gen.seed()      # diffent seeds at different times
        state2 = self.gen.getstate()   
        self.assertNotEqual(state1, state2)

    def test_saverestore(self):
        N = 5000
        self.gen.seed()
        state = self.gen.getstate()
        randseq = self.gen.randomlist(N)
        self.gen.setstate(state)    # should regenerate the same sequence
        self.assertEqual(randseq, self.gen.randomlist(N))

    def test_referenceImplementation(self):
        """The code from the original source came with a demo.
           Altering it to create 2000 53-bit precision floats
           yields a base case that the Python implemenation
           should match.  Only the last five of entries are
           checked (if its still on track after 2000 steps,
           that is a good sign).
        """
        testseeds = [int(hex,16) for hex in '0x123 0x234 0x345 0x456'.split()]
        expected = [0.09857852, 0.93585516, 0.53237051, 0.74474624, 0.07408276]
        self.gen.seed(*testseeds)
        actual = self.gen.randomlist(2000)[-5:]
        for a, e in zip(actual, expected):
            self.assertEqual(round(a-e, 7), 0)

    def test_jumpahead(self):
        """For the MersenneTwister, there is no exact analog to jumpahead(n)
        where n represents a discrete number of forward steps.  The use case
        for jumpahead is to create a non-overlapping sequence.  Here, we test
        that jumpahead(n) at least generates a different sequence from
        the original and on successive calls.
        """
        N = 500000
        a = self.gen.random()
        self.gen.jumpahead(N)
        b = self.gen.random()
        self.assertNotEqual(a, b)
        self.gen.jumpahead(N)
        c = self.gen.random()
        self.assertNotEqual(b, c)
        
def test_main():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(TestBasicOps))
    test_support.run_suite(suite)

if __name__ == "__main__":
    test_main()