Beispiel #1
0
def random_tree(labels):
    """
    Given a list of labels, create a list of leaf nodes, and then one
    by one pop them off, randomly grafting them on to the growing tree.

    Return the root node.
    """
    assert len(labels) > 2
    import RandomArray; RandomArray.seed()
    leaves = []
    for label in labels:
        leaves.append(Fnode(istip=1, label=label))

    leaf_indices = list(RandomArray.permutation(len(leaves)))

    joined = [leaves[leaf_indices.pop()]]
    remaining = leaf_indices
    while remaining:
        i = RandomArray.randint(0, len(joined)-1)
        c1 = joined[i]
        if c1.back:
            n = c1.bisect()
        else:
            n = InternalNode()
            n.add_child(c1)
        c = leaves[remaining.pop()]
        n.add_child(c)
        joined.append(c)
        joined.append(n)

    for node in joined:
        if not node.back:
            node.isroot = 1
            return node
Beispiel #2
0
def randomArray(shape, seed=None, range=(0, 1), type=Float):
    """Utility to generate a Numeric array full of pseudorandom numbers in the given range.
       This will attempt to use the RandomArray module, but fall back on using the standard
       random module in a loop.
       """
    global globalSeed
    if not seed:
        if not globalSeed:
            globalSeed = int(time.time())
        seed = globalSeed
        # Keep our global seed mixed up enough that many requests for
        # random arrays consecutively still gives random-looking output.
        globalSeed = (globalSeed + random.randint(1, 0xFFFFF)) & 0x7FFFFFF

    try:
        import RandomArray

        RandomArray.seed(seed + 1, seed + 1)
        return (RandomArray.random(shape) * (range[1] - range[0]) + range[0]).astype(type)
    except ImportError:
        random.seed(seed)
        a = zeros(multiply.reduce(shape), Float)
        for i in xrange(a.shape[0]):
            a[i] = random.random() * (range[1] - range[0]) + range[0]
        return reshape(a, shape).astype(type)
    def test_sparse_vs_dense(self):
        RandomArray.seed(0)             # For reproducability
        for s, l in (100, 100000), (10000, 100000), (100000, 100000):
            small = Numeric.sort(RandomArray.randint(0, 100000, (s,)))
            large = Numeric.sort(RandomArray.randint(0, 100000, (l,)))

            sparse1 = soomfunc.sparse_intersect(small, large)
            sparse2 = soomfunc.sparse_intersect(large, small)
            dense1 = soomfunc.dense_intersect(small, large)
            dense2 = soomfunc.dense_intersect(large, small)

            self.assertEqual(sparse1, sparse2)
            self.assertEqual(dense1, dense2)
            self.assertEqual(sparse1, dense1)
Beispiel #4
0
import sys, cPickle, time, commands, os, re
import RandomArray
from Numeric import *
from Asap.testtools import ReportTest

# cpu time:  time.clock().   Wall clock time: time.time()

host = commands.getoutput("hostname")
timesteps = 20
dbfilename = "bigtiming.dat"
selfcheckfilename = "bigtiming-selfcheck.dat"
logfilename = "bigtiming.log"
asapversion = GetVersion()
when = time.strftime("%a %d %b %Y %H:%M", time.localtime(time.time()))

RandomArray.seed(42, 12345)

PrintVersion(1)
print "Running ASAP timing on "+host+"."
if re.match("^n\d\d\d.dcsc.fysik.dtu.dk$", host):
    print "    This is a d512 node on Niflheim."
    fullhost = "niflheim-d512/%s" % (host.split(".")[0])
    host = "niflheim-d512"
elif re.match("^[stu]\d\d\d.dcsc.fysik.dtu.dk$", host):
    print "    This is an s50 node on Niflheim."
    fullhost = "niflheim-s50/%s" % (host.split(".")[0])
    host = "niflheim-s50"
else:
    fullhost = host
print "Current time is "+when
print ""
Beispiel #5
0
        data = N.floor((data - self.min)/self.bin_width).astype(N.Int)
        nbins = self.array.shape[0]
        histo = N.add.reduce(weights*N.equal(N.arange(nbins)[:,N.NewAxis],
                                             data), -1)
        histo[-1] = histo[-1] + N.add.reduce(N.repeat(weights,
                                                      N.equal(nbins, data)))
        self.array[:, 1] =  self.array[:, 1] + histo


if __name__ == '__main__':
    if N.package == 'Numeric':
        import RandomArray as random
    elif N.package == 'NumPy':
        from numpy import random
    nsamples = 1000
    random.seed(12,13)
    data = random.normal(1.0, 0.5, nsamples)
    h = Histogram(data, 50)  # use 50 bins between min & max samples
    h.normalizeArea()        # make probabilities in histogram
    x = h.getBinIndices()
    y = h.getBinCounts()

    # add many more samples:
    nsamples2 = nsamples*100
    data = random.normal(1.0, 0.5, nsamples2)
    h.addData(data)
    h.normalizeArea()
    x2 = h.getBinIndices()
    y2 = h.getBinCounts()

    # and more:
Beispiel #6
0
from Numeric import dot,sum 
import sys,numeric_version 
import RandomArray 
import LinearAlgebra 

print sys.version 
print "Numeric version:",numeric_version.version 

RandomArray.seed(123,456) 
a = RandomArray.normal(0,1,(100,10)) 
f = RandomArray.normal(0,1,(10,30)) 
e = RandomArray.normal(0,0.1,(100,30)) 
print "Got to seed:",RandomArray.get_seed() 

b = dot(a,f)+e 

(x,res,rank,s)=LinearAlgebra.linear_least_squares(a,b) 

f_res = sum((b-dot(a,f))**2) 
x_res = sum((b-dot(a,x))**2) 

print "'Planted' residues, upper bound for optimal residues:" 
print f_res 
print "Claimed residues:" 
print res 
print "Actual residues:" 
print x_res 
print "Ratio between actual and claimed (shoudl be 1):" 
print x_res/res 
print "Ratio between actual and planted (should be <1):" 
print x_res/f_res 
Classes:
MarkovModel     Holds the description of a markov model
"""
import math

from Numeric import *
import RandomArray

import StringIO     # StringIO is in Numeric's namespace, so import this after.

from Bio import listfns


#RandomArray.seed(0, 0)   # use 0 for debugging
RandomArray.seed()

VERY_SMALL_NUMBER = 1E-300
LOG0 = log(VERY_SMALL_NUMBER)

MATCODE = Float64

class MarkovModel:
    def __init__(self, states, alphabet,
                 p_initial=None, p_transition=None, p_emission=None):
        self.states = states
        self.alphabet = alphabet
        self.p_initial = p_initial
        self.p_transition = p_transition
        self.p_emission = p_emission
    def __str__(self):
        data = N.floor((data - self.min)/self.bin_width).astype(N.Int)
        nbins = self.array.shape[0]
        histo = N.add.reduce(weights*N.equal(N.arange(nbins)[:,N.NewAxis],
                                             data), -1)
        histo[-1] = histo[-1] + N.add.reduce(N.repeat(weights,
                                                      N.equal(nbins, data)))
        self.array[:, 1] =  self.array[:, 1] + histo


if __name__ == '__main__':
    if N.package == 'Numeric':
        import RandomArray as random
    elif N.package == 'NumPy':
        from numpy import random
    nsamples = 1000
    random.seed(12,13)
    data = random.normal(1.0, 0.5, nsamples)
    h = Histogram(data, 50)  # use 50 bins between min & max samples
    h.normalizeArea()        # make probabilities in histogram
    x = h.getBinIndices()
    y = h.getBinCounts()

    # add many more samples:
    nsamples2 = nsamples*100
    data = random.normal(1.0, 0.5, nsamples2)
    h.addData(data)
    h.normalizeArea()
    x2 = h.getBinIndices()
    y2 = h.getBinCounts()

    # and more: