Exemplo n.º 1
0
Arquivo: imv.py Projeto: sldion/DNACC
def main():
    
    """ A simple example.  Note that the Tkinter lines are there only
    because this code will be run standalone.  On the interpreter,
    simply invoking surf and view would do the job."""
    
    import Tkinter
    r = Tkinter.Tk()
    r.withdraw()

    def f(x, y):
        return Numeric.sin(x*y)/(x*y)

    x = Numeric.arange(-7., 7.05, 0.1)
    y = Numeric.arange(-5., 5.05, 0.05)
    v = surf(x, y, f)

    import RandomArray
    z = RandomArray.random((50, 25))
    v1 = view(z)
    v2 = view(z, warp=1)
    z_large = RandomArray.random((1024, 512))
    v3 = viewi(z_large)

    # A hack for stopping Python when all windows are closed.
    v.master = r 
    v1.master = r
    v2.master = r
    #v3.master = r
    
    r.mainloop()
Exemplo n.º 2
0
 def setUp(self):
     self.number = 50
     X = RandomArray.random(self.number)
     Y = RandomArray.random(self.number)
     Z = RandomArray.random(self.number)
     co = Numeric.array([X, Y, Z])
     self.points = []
     for i in range(len(co[0])):
         self.points.append(tuple(co[:, i].tolist()))
Exemplo n.º 3
0
 def setUp(self):
     self.number = 50
     X = RandomArray.random(self.number)
     Y = RandomArray.random(self.number)
     Z = RandomArray.random(self.number)
     co = Numeric.array([X, Y, Z])
     self.points = []
     for i in range(len(co[0])):
         self.points.append(tuple(co[:,i].tolist()))
Exemplo n.º 4
0
    def _synth(self, freq, msdur, vol, risefall):
        t = arange(0, msdur / 1000.0, 1.0 / _Beeper._dafreq)
        s = zeros((t.shape[0], 2))
        # use trapezoidal envelope with risefall (below) time
        if msdur < 40:
            risefall = msdur / 2.0
        env = -abs((t - (t[-1] / 2)) / (risefall / 1000.0))
        env = env - min(env)
        env = where(less(env, 1.0), env, 1.0)

        bits = _Beeper._bits
        if bits < 0:
            bits = -bits
            signed = 1
        else:
            signed = 0

        fullrange = power(2, bits - 1)

        if freq is None:
            y = (env * vol * fullrange * \
              RandomArray.random(t.shape)).astype(Int16)
        else:
            y = (env * vol * fullrange * \
              sin(2.0 * pi * t * freq)).astype(Int16)

        if _Beeper._chans == 2:
            y = transpose(array([y, y]))
        s = pygame.sndarray.make_sound(y)
        return s
Exemplo n.º 5
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)
Exemplo n.º 6
0
Arquivo: beep.py Projeto: mazerj/pype2
	def _synth(self, freq, msdur, vol, risefall):
		t = arange(0, msdur / 1000.0, 1.0 / _Beeper._dafreq)
		s = zeros((t.shape[0], 2))
		# use trapezoidal envelope with risefall (below) time
		if msdur < 40:
			risefall = msdur / 2.0
		env = -abs((t - (t[-1] / 2)) / (risefall/1000.0))
		env = env - min(env)
		env = where(less(env, 1.0), env, 1.0)

		bits = _Beeper._bits
		if bits < 0:
			bits = -bits
			signed = 1
		else:
			signed = 0

		fullrange = power(2, bits-1)

		if freq is None:
			y = (env * vol * fullrange * \
				 RandomArray.random(t.shape)).astype(Int16)
		else:
			y = (env * vol * fullrange * \
				 sin(2.0 * pi * t * freq)).astype(Int16)

		if _Beeper._chans == 2:
			y = transpose(array([y,y]))
		s = pygame.sndarray.make_sound(y)
		return s
Exemplo n.º 7
0
 def __init__(self, rows, cols, size):
     self.rows = rows
     self.cols = cols
     self.vectorLen = size
     self.weight = RandomArray.random((rows, cols, size))
     self.input = []
     self.loadOrder = []
     self.step = 0
     self.maxStep = 1000.0
Exemplo n.º 8
0
def init_velocities(T, ma, ndf=None):

    # Simple equipartition, no Maxwell-Boltzmann
    # For Maxwell-Boltzmann, use RandomArray.standard_normal()
    import RandomArray
    v = RandomArray.random((len(ma), 3)) - 0.5

    # Make the C.M. static
    vcm = v_cm(v, ma)
    for xyz in range(3):
        v[:, xyz] = v[:, xyz] - vcm[xyz]

    # Re-scale for correct kinetic energy
    kin = ekin(v, ma)
    # This will take into account the reduced no of degrees of freedom
    if ndf is None:
        ndf = 3 * len(ma) - 3
    temp = temp_from_ekin(kin, ndf)
    v = v * math.sqrt(T / temp)

    return v
Exemplo n.º 9
0
def PlotFit(traj=SandPConstantDollar,
            times=SandPTime,
            nRandomTrajs=0,
            a=0.04,
            output=False):

    plotEm = []
    eta, trajFlattened = RemoveMeanGrowth(traj, times)
    plotEm.append(times)
    plotEm.append(trajFlattened)

    randomTimes = scipy.arange(times[0], times[-1] + 1.e-10,
                               (times[-1] - times[0]) / (len(times) - 1))
    randomTrajs = []
    for i in range(nRandomTrajs):
        randomTrajs.append(
            scipy.exp(scipy.cumsum(a *
                                   (RandomArray.random(len(times)) - 0.5))))
    randomTrajsFlattened = randomTrajs[:]
    for rF in randomTrajsFlattened:
        eta, rF = RemoveMeanGrowth(rF, randomTimes)
        plotEm.append(randomTimes)
        plotEm.append(rF)

    pylab.plot(*plotEm)
    pylab.show()

    if output:
        outputSandP = file("SandPFlattened.dat", "w")
        for t, data in zip(times, trajFlattened):
            outputSandP.write("%s %s\n" % (t, data))
        outputSandP.close()
        outputRandom = file("OneDRandomFlattened.dat", "w")
        for rF in randomTrajs:
            eta, rF = RemoveMeanGrowth(rF, randomTimes)
            for t, data in zip(randomTimes, rF):
                outputRandom.write("%s %s\n" % (t, data))
            outputRandom.write("\n")
        outputRandom.close()
Exemplo n.º 10
0
def randn(*args):
    """u = randn(d0,d1,...,dn) returns zero-mean, unit-variance Gaussian
    random numbers in an array of size (d0,d1,...,dn)."""
    x1 = RandomArray.random(args)
    x2 = RandomArray.random(args)
    return sqrt(-2*log(x1))*cos(2*pi*x2)
Exemplo n.º 11
0
def rand(*args):
    """rand(d1,...,dn) returns a matrix of the given dimensions
    which is initialized to random numbers from a uniform distribution
    in the range [0,1).
    """
    return RandomArray.random(args)
Exemplo n.º 12
0
 def OnTimerFraction( self, event ):
     """Perform the particle-system simulation calculations"""
     points = self.points.coord.point
     colors = self.points.color.color
     '''Our calculations are going to need to know how much time 
     has passed since our last event.  This is complicated by the 
     fact that a "fraction" event is cyclic, returning to 0.0 after 
     1.0.'''
     f = event.fraction()
     if f < self.lastFraction:
         f += 1.0
     deltaFraction = (f-self.lastFraction)
     self.lastFraction = event.fraction()
     '''If we have received an event which is so soon after a 
     previous event as to have a 0.0s delta (this does happen 
     on some platforms), then we need to ignore this simulation 
     tick.'''
     if not deltaFraction:
         return
     '''Each droplet has been moving at their current velocity 
     for deltaFraction seconds, update their position with the 
     results of this speed * time.  You'll note that this is not 
     precisely accurate for a body under acceleration, but it 
     makes for easy calculations.  Two machines running 
     the same simulation will get *different* results here, as 
     a faster machine will apply acceleration more frequently,
     resulting in a faster total velocity.'''
     points = points + (self.velocities*deltaFraction)
     '''We also cycle the droplet's colour value, though with 
     the applied texture it's somewhat hard to see.'''
     colors = colors + (self.colorVelocities*deltaFraction)
     '''Now, apply acceleration to the current velocities such 
     that the droplets have a new velocity for the next simulation 
     tick.'''
     self.velocities[:,1] = self.velocities[:,1] + (gravity * deltaFraction)
     '''Find all droplets which have "retired" by falling below the 
     y==0.0 plane.'''
     below = less_equal( points[:,1], 0.0)
     dead = nonzero(below)
     if isinstance( dead, tuple ):
         # weird numpy change here...
         dead = dead[0]
     if len(dead):
         '''Move all dead droplets back to the emitter.'''
         def put( a, ind, b ):
             for i in ind:
                 a[i] = b
         put( points, dead, emitter)
         '''Re-spawn up to half of the droplets...'''
         dead = dead[:(len(dead)//2)+1]
         if len(dead):
             '''Reset color to initialColor, as we are sending out 
             these droplets right now.'''
             put( colors, dead, initialColor)
             '''Assign slightly randomized versions of our initial 
             velocity for each of the re-spawned droplets.  Replace 
             the current velocities with the new velocities.'''
             if RandomArray:
                 velocities = (RandomArray.random( (len(dead),3) ) + [-.5, 0.0, -.5 ]) * initialVelocityVector
             else:
                 velocities = [
                     array( (random.random()-.5, random.random(), random.random()-.5), 'f')* initialVelocityVector
                     for x in xrange(len(dead))
                 ]
             def copy( a, ind, b ):
                 for x in xrange(len(ind)):
                     i = ind[x]
                     a[i] = b[x]
             copy( self.velocities, dead, velocities)
     '''Now re-set the point/color fields so that the nodes notice 
     the array has changed and they update the GL with the changed 
     values.'''
     self.points.coord.point = points
     self.points.color.color = colors
Exemplo n.º 13
0
    LAST = p
    return p


def psprint(dest="-"):
    if TABLE:
        TABLE.write_eps(dest)


if __name__ == '__main__':
    import sys, Numeric, RandomArray
    x = Numeric.arrayrange(-10, 10)
    y = x**2
    e = y / 4

    a = RandomArray.random([20, 20, 3])
    imagesc(a, x=range(-10, 10), y=range(-10, 10))
    drawnow()
    sys.stdin.readline()

    a = Numeric.array([[[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0]],
                       [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
                       [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
                       [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]])
    imagesc(a)
    drawnow()
    sys.stdin.readline()

    #plot(list(x), list(y), 'ko-')
    errorbar2(list(x), list(y), e, e, 'ko-')
Exemplo n.º 14
0
assert allclose(computeResiduals(As, None, lmbd, Q), zeros(kconv), 0.0, tol)
assert allclose(lmbd, lmbd_exact, tol*tol, 0.0)

print 'OK'

#-------------------------------------------------------------------------------
# Test 2: K = None

print 'Test 2',

lmbd_exact = zeros(ncv, 'd')
for k in xrange(ncv):
    lmbd_exact[k] =  A[k,k]/M[k,k]


X0 = RandomArray.random((n,ncv))

kconv, lmbd, Q, it, it_inner = jdsym.jdsym(As, Ms, None, ncv, 0.0, tol, 150, itsolvers.qmrs,
                                           jmin=5, jmax=10, eps_tr=1e-4, clvl=1)
    
assert ncv == kconv
assert allclose(computeResiduals(As, Ms, lmbd, Q), zeros(kconv), 0.0, normM*tol)
assert allclose(lmbd, lmbd_exact, normM*tol*tol, 0.0)

print 'OK'

#-------------------------------------------------------------------------------
# Test 3: general case

print 'Test 3',
Exemplo n.º 15
0
    if show:
        p.show()
    LAST = p
    return p

def psprint(dest="-"):
    if TABLE:
        TABLE.write_eps(dest)

if __name__=='__main__' :
    import sys, Numeric, RandomArray
    x = Numeric.arrayrange(-10,10);
    y = x**2;
    e = y/4

    a = RandomArray.random([20,20,3])
    imagesc(a, x=range(-10,10), y=range(-10,10))
    drawnow()
    sys.stdin.readline()
    

    a = Numeric.array([[[1, 0, 0],
                [0, 1, 0],
                [0, 0, 1],
                [0, 0, 0]],
               [[0, 0, 0],
                [0, 0, 0],
                [0, 0, 0],
                [0, 0, 0]],
               [[0, 0, 0],
                [0, 0, 0],
Exemplo n.º 16
0
def rand(*args):
    """rand(d1,...,dn) returns a matrix of the given dimensions
    which is initialized to random numbers from a uniform distribution
    in the range [0,1).
    """
    return RandomArray.random(args)
Exemplo n.º 17
0
            print "Error =", error

    def trainPattern(self, pattern):
        # will depend on self.step
        x, y, d = self.winner(pattern)
        error += self.updateMap(pattern, x, y)
        print "Winner is weight at (", x, y, ") (diff was", d,  ") error = ", \
              error

    def test(self):
        import numpy.oldnumeric as Numeric
        self.loadOrder = range(len(self.input))
        histogram = Numeric.zeros((self.cols, self.rows), 'i')
        for p in self.loadOrder:
            x, y, d = self.winner(self.input[p])
        #    print "Input[%d] =" % p, self.input[p],"(%d, %d)" % (x, y)
            histogram[x][y] += 1
        for r in range(self.rows):
            for c in range(self.cols):
                print "%5d" % histogram[c][r],
            print ""
        print ""

if __name__ == '__main__':
    import numpy.oldnumeric as Numeric
    s = SOM(5, 7, 5) # rows, cols; length of high-dimensional input
    s.setInputs( RandomArray.random((100, 5))) 
    s.maxStep = 100
    s.train()
    s.test()
Exemplo n.º 18
0
import RandomArray, time, sys
from tables import Filters
import tables.netcdf3 as NetCDF
import Scientific.IO.NetCDF
# create an n1dim by n2dim random array.
n1dim = 1000
n2dim = 10000
print 'reading and writing a %s by %s random array ..'%(n1dim,n2dim)
array = RandomArray.random((n1dim,n2dim))
filters = Filters(complevel=0,complib='zlib',shuffle=0)
# create a file, put a random array in it.
# no compression is used.
# first, use Scientific.IO.NetCDF
t1 = time.time()
file = Scientific.IO.NetCDF.NetCDFFile('test.nc','w')
file.createDimension('n1', None)
file.createDimension('n2', n2dim)
foo = file.createVariable('data', 'd', ('n1','n2',))
for n in range(n1dim):
    foo[n] = array[n]
file.close()
print 'Scientific.IO.NetCDF took',time.time()-t1,'seconds'
# now use pytables NetCDF emulation layer.
t1 = time.time()
file = NetCDF.NetCDFFile('test.h5','w')
file.createDimension('n1', None)
file.createDimension('n2', n2dim)
# no compression (override default filters instance).
foo = file.createVariable('data', 'd', ('n1','n2',),filters=filters)
# this is faster
foo.append(array)
def _random_norm(shape):
    matrix = asarray(RandomArray.random(shape), MATCODE)
    return _normalize(matrix)
Exemplo n.º 20
0
def testRandom(nx, ny):
    return RandomArray.random((nx, ny))
Exemplo n.º 21
0
    def OnTimerFraction(self, event):
        """Perform the particle-system simulation calculations"""
        points = self.points.coord.point
        colors = self.points.color.color
        '''Our calculations are going to need to know how much time 
        has passed since our last event.  This is complicated by the 
        fact that a "fraction" event is cyclic, returning to 0.0 after 
        1.0.'''
        f = event.fraction()
        if f < self.lastFraction:
            f += 1.0
        deltaFraction = (f - self.lastFraction)
        self.lastFraction = event.fraction()
        '''If we have received an event which is so soon after a 
        previous event as to have a 0.0s delta (this does happen 
        on some platforms), then we need to ignore this simulation 
        tick.'''
        if not deltaFraction:
            return
        '''Each droplet has been moving at their current velocity 
        for deltaFraction seconds, update their position with the 
        results of this speed * time.  You'll note that this is not 
        precisely accurate for a body under acceleration, but it 
        makes for easy calculations.  Two machines running 
        the same simulation will get *different* results here, as 
        a faster machine will apply acceleration more frequently,
        resulting in a faster total velocity.'''
        points = points + (self.velocities * deltaFraction)
        '''We also cycle the droplet's colour value, though with 
        the applied texture it's somewhat hard to see.'''
        colors = colors + (self.colorVelocities * deltaFraction)
        '''Now, apply acceleration to the current velocities such 
        that the droplets have a new velocity for the next simulation 
        tick.'''
        self.velocities[:,
                        1] = self.velocities[:, 1] + (gravity * deltaFraction)
        '''Find all droplets which have "retired" by falling below the 
        y==0.0 plane.'''
        below = less_equal(points[:, 1], 0.0)
        dead = nonzero(below)
        if isinstance(dead, tuple):
            # weird numpy change here...
            dead = dead[0]
        if len(dead):
            '''Move all dead droplets back to the emitter.'''
            def put(a, ind, b):
                for i in ind:
                    a[i] = b

            put(points, dead, emitter)
            '''Re-spawn up to half of the droplets...'''
            dead = dead[:(len(dead) // 2) + 1]
            if len(dead):
                '''Reset color to initialColor, as we are sending out 
                these droplets right now.'''
                put(colors, dead, initialColor)
                '''Assign slightly randomized versions of our initial 
                velocity for each of the re-spawned droplets.  Replace 
                the current velocities with the new velocities.'''
                if RandomArray:
                    velocities = (RandomArray.random((len(dead), 3)) +
                                  [-.5, 0.0, -.5]) * initialVelocityVector
                else:
                    velocities = [
                        array((random.random() - .5, random.random(),
                               random.random() - .5), 'f') *
                        initialVelocityVector for x in xrange(len(dead))
                    ]

                def copy(a, ind, b):
                    for x in xrange(len(ind)):
                        i = ind[x]
                        a[i] = b[x]

                copy(self.velocities, dead, velocities)
        '''Now re-set the point/color fields so that the nodes notice 
        the array has changed and they update the GL with the changed 
        values.'''
        self.points.coord.point = points
        self.points.color.color = colors
Exemplo n.º 22
0
import RandomArray, time, sys
from tables import Filters
import tables.netcdf3 as NetCDF
import Scientific.IO.NetCDF
# create an n1dim by n2dim random array.
n1dim = 1000
n2dim = 10000
print 'reading and writing a %s by %s random array ..' % (n1dim, n2dim)
array = RandomArray.random((n1dim, n2dim))
filters = Filters(complevel=0, complib='zlib', shuffle=0)
# create a file, put a random array in it.
# no compression is used.
# first, use Scientific.IO.NetCDF
t1 = time.time()
file = Scientific.IO.NetCDF.NetCDFFile('test.nc', 'w')
file.createDimension('n1', None)
file.createDimension('n2', n2dim)
foo = file.createVariable('data', 'd', (
    'n1',
    'n2',
))
for n in range(n1dim):
    foo[n] = array[n]
file.close()
print 'Scientific.IO.NetCDF took', time.time() - t1, 'seconds'
# now use pytables NetCDF emulation layer.
t1 = time.time()
file = NetCDF.NetCDFFile('test.h5', 'w')
file.createDimension('n1', None)
file.createDimension('n2', n2dim)
# no compression (override default filters instance).
Exemplo n.º 23
0
def randn(*args):
    """u = randn(d0,d1,...,dn) returns zero-mean, unit-variance Gaussian
    random numbers in an array of size (d0,d1,...,dn)."""
    x1 = RandomArray.random(args)
    x2 = RandomArray.random(args)
    return sqrt(-2*log(x1))*cos(2*pi*x2)
Exemplo n.º 24
0
"""Matlab(tm) compatibility functions.