Example #1
0
File: FFT.py Project: IanReid/ABFGP
def _raw_fft(a, n=None, axis=-1, init_function=fftpack.cffti, 
             work_function=fftpack.cfftf, fft_cache = _fft_cache ):
    a = Numeric.asarray(a)

    if n == None: n = a.shape[axis]

    try:
        wsave = fft_cache[n]
    except(KeyError):
        wsave = init_function(n)
        fft_cache[n] = wsave

    if a.shape[axis] != n:
        s = list(a.shape)
        if s[axis] > n:
            index = [slice(None)]*len(s)
            index[axis] = slice(0,n)
            a = a[index]
        else:
            index = [slice(None)]*len(s)
            index[axis] = slice(0,s[axis])
            s[axis] = n
            z = Numeric.zeros(s, a.typecode())
            z[index] = a
            a = z

    if axis != -1:
        a = Numeric.swapaxes(a, axis, -1)
    r = work_function(a, wsave)
    if axis != -1:
        r = Numeric.swapaxes(r, axis, -1)
    return r
Example #2
0
def solSpace(veclist, base=2):
    """Takes a list of vectors defining a basis, and returns a list of possible values for the mod space"""
    solutions = [(Numeric.nonzero(veclist[0]) + 1).tolist()]  # first solution is trivial, constant portion of space
    parameters = len(veclist) - 1  # find the total number of parameterized vectors
    combos = pow(base, parameters)  # find the total number of solutions (base number to the power of parameters)
    for i in range(1, combos):  # for each combo (starting at one, because we already have the zeroth
        val = i
        sum = veclist[0]  # grab the constant
        parm = 1  # index into the parameters
        while val > 0:
            mult = val % base  # the multiplier for the row
            val = val / base  # the remainder for the next row
            if mult == 0:  # if the multiplier is 0, skip to the next vector
                parm += 1
                continue
            add = veclist[parm] * mult  # multiply parameter vector by multiplier
            sum = modAdd(sum, add, base)  # perform addition
        sol = (Numeric.nonzero(sum) + 1).tolist()  # convert to a list of lights
        if not (sol in solutions):  # if this solution isn't unique, don't add it
            solutions.append(sol)
    answer = solutions[0]
    for sol in range(1, len(solutions)):  # for
        if len(solutions[sol]) < len(answer):
            answer = solutions[sol]
    return answer
Example #3
0
def spline_extension(x, y, y2, xmin=None, xmax=None):
	"""x, y, y2 = spline_extension(x_vals,y_vals, y2vals, xmin=None, xmax=None) 
	returns the x, y, y2 table for the spline as needed by splint() with adjustments to allow quadratic extrapolation 
	outside the range x[0]-x[-1], from xmin (or x[0] if xmin is None) to xmax (or x[-1] if xmax is None),
	working from x, y, y2 from an already-created spline"""

	xl=[x]
	yl=[y]
	y2l=[y2]
	
	if xmin is not None:
		h0=x[1]-x[0]
		h1=xmin-x[0]
		yextrap=y[0]+((y[1]-y[0])/h0 - h0*(y2[0]+2.0*y2[1])/6.0)*h1+y2[0]*h1*h1/2.0
		yl.insert(0, (yextrap,))
		xl.insert(0, (xmin,))
		y2l.insert(0, (y2[0],))

	if xmax is not None:
		h0=x[-1]-x[-2]
		h1=xmax-x[-1]
		yextrap=y[-1]+((y[-1]-y[-2])/h0 + h0*(2.0*y2[-2]+y2[-1])/6.0)*h1+y2[-1]*h1*h1/2.0
		yl.append((yextrap,))
		xl.append((xmax,))
		y2l.append((y2[-1],))

	return Numeric.concatenate(xl), Numeric.concatenate(yl), Numeric.concatenate(y2l)
Example #4
0
	def __init__( self, w, h, over ):
		self.w = w
		self.h = h
		self.last_update = pygame.time.get_ticks( )
		self.first_time = self.last_update
		self.surface = pygame.surface.Surface( (w, h), SRCALPHA, 32 )
		self.surface.convert_alpha( )
		self.over = over

		parray = pygame.surfarray.pixels3d( self.surface )
		parray[:,:] = (255, 255, 255)
		
		self.ttma = Numeric.zeros( (w, h), 'b' )
		self.dv = Numeric.zeros( (w, h), 'b' )
		self.rand_plus = Numeric.zeros( (w, h), 'b' )
		self.rand_minus = Numeric.zeros( (w, h), 'b' )
		self.active = False

		def center_dist( i, j ):
			x = w/2.0 - i
			y = h/2.0 - j
			d = math.sqrt( x*x + y*y )
			d = 1.0 - pow( d/max( w/2, h/2 ), 2.0 )
			if d < 0: return 0
			return int( d*255 )
		
		jr = range( 0, self.h )
		ir = range( 0, self.w )

		for j in jr:
			for i in ir:
				self.dv[i,j] = center_dist( i, j )
				self.rand_plus[i,j] = random.random( )*20
				self.rand_minus[i,j] = random.random( )*20
Example #5
0
    def __getitem__(self, item):
	if type(item) != type(0):
	    return SubTrajectory(self, Numeric.arange(len(self)))[item]
	if item >= len(self):
	    raise IndexError
        tindex = Numeric.add.reduce(Numeric.greater_equal(item, self.nsteps))-1
        return self.trajectories[tindex][item-self.nsteps[tindex]]
Example #6
0
 def getFreq(self, seconds):
     if self.fake:
         base = 300
         if random.random() < .2:
             freq = base + randint(-50,50)
         else:
             freq = base + randint(-200, 200)
         #freq = (random.random() * 400) + 100.0
         distance = freq * 0.0051 - 0.0472
         return (distance, freq, 1, 1, 1, 1)
     data = self.read(seconds)
     self.timestamp = time.time()
     transform = FFT.real_fft(data).real
     minFreq = 20 
     maxFreq = 700
     minFreqPos = int(minFreq * seconds)
     maxFreqPos = int(maxFreq * seconds)
     minFreqPos = max(0, minFreqPos)
     maxFreqPos = min(int(self.sample_rate * seconds), maxFreqPos)
     if minFreqPos == maxFreqPos:
         self.lastFreq = int(self.sample_rate * sampleTime/ 2.0)
         return
     elif minFreqPos > maxFreqPos:
         minFreqPos, maxFreqPos = maxFreqPos, minFreqPos
     freqPos = Numeric.argmax(transform[1+minFreqPos:maxFreqPos])
     value = transform[1+minFreqPos:maxFreqPos][freqPos]
     freq = int((freqPos + minFreqPos) / seconds)
     distance = freq * 0.0051 - 0.0472
     bestFreqPos = Numeric.argmax(transform[1:])
     bestValue = transform[1:][bestFreqPos]
     bestFreq = int(bestFreqPos / seconds)
     return (distance, freq, value, transform[0], bestFreq, bestValue)
Example #7
0
    def set_data (self, evt):
        dB = evt.data
        L = len (dB)

        if self.peak_hold:
            if self.peak_vals is None:
                self.peak_vals = dB
            else:
                self.peak_vals = Numeric.maximum(dB, self.peak_vals)
                dB = self.peak_vals

        x = max(abs(self.facsink.sample_rate), abs(self.facsink.baseband_freq))
        sf = 1000.0
        units = "ms"

        x_vals = ((Numeric.arrayrange (L/2)
                       * ( (sf / self.facsink.sample_rate  ) )) )
        points = Numeric.zeros((len(x_vals), 2), Numeric.Float64)
        points[:,0] = x_vals
        points[:,1] = dB[0:L/2]

        lines = plot.PolyLine (points, colour='green')	# DARKRED

        graphics = plot.PlotGraphics ([lines],
                                      title=self.facsink.title,
                                      xLabel = units, yLabel = "dB")

        self.Draw (graphics, xAxis=None, yAxis=self.y_range)
        self.update_y_range ()
    def __init__(self,filename):

        try:
            file = open(filename,'r')
            file.close()
        except IOError:
            raise UserInputException('%s does not exist' % filename)

        img = Image.open(filename)
        self.filename = filename

        self.size = max(img.size[0],img.size[1])

        img = img.convert('I') #convert to int
        temp = Numeric.fromstring(img.tostring(), Numeric.Int32)

        # I am not exactly sure why PI and Numeric's tostring and 
        # fromstring method are transposed relative to eachother,
        # but this code is what works
        temp.shape = img.size[1],img.size[0]

        # pad values if necessary
        self.data = Numeric.zeros((self.size,self.size),Numeric.Int32)
        self.data[0:temp.shape[0],0:temp.shape[1]] = temp
        self.data = Numeric.transpose(self.data)
Example #9
0
 def subcounts(self,prefix=[]):
     if not prefix:
         return Numeric.array([m._count for m in self.t_table.itervalues()])
     elif prefix[0] not in self.t_table:
         return Numeric.array([0])
     else:
         return self.t_table[prefix[0]].subcounts(prefix[1:])
Example #10
0
def LinearLeastSquaresFit(xdata,ydata):
    """
    Special case of polynomialLeastSquaresFit,
    which returns the R^2 value

    intercept,slope,R_squared = LinearLeastSquaresFit(xdata,ydata)
    
    """
    xdata=Numeric.array(xdata)
    ydata=Numeric.array(ydata)
    # form that LeastSquaresFit wants the data in
    data=map(lambda x,y:(x,y),xdata,ydata)
    # I am not sure if the particular guess for parameters will result in a error in some cases
    lsq=polynomialLeastSquaresFit(parameters=(0,0), data=data)
    
    intercept=lsq[0][0]
    slope=lsq[0][1]

    avg_y=mean(ydata)
    
    predicted_data = intercept + slope*xdata
    numerator=Numeric.sum((predicted_data-ydata)**2)
    denominator=Numeric.sum((ydata-avg_y)**2)

    R_squared = 1 - numerator/denominator

    return intercept,slope, R_squared
def process(fname):
    """Process verif output file.

    fname: name of file

    return: tuple of (exp_name, solver, dx, dt, dome_e, max_e, min_e, mean_e, sd_e)"""

    # extract errors
    ncf = Scientific.IO.NetCDF.NetCDFFile(fname)
    diff = ncf.variables["thke"][-1, :, :] - ncf.variables["thk"][-1, :, :]
    centre = (Numeric.shape(diff)[0] - 1) / 2
    dome_e = diff[centre, centre]
    diff = Numeric.ravel(diff)
    max_e = max(diff)
    min_e = min(diff)
    hist = histogram.histogram(100)
    hist.set_ranges_uniform(round_down(min_e), round_up(max_e))
    for e in diff.tolist():
        hist.increment(e)
    mean_e = hist.mean()
    sd_e = hist.sigma()

    config = ncf.title.split(",")
    exp_name = config[0][-1]
    solver = config[1].strip()
    dx = float(config[2].strip()[:-2])
    dt = float(config[3].strip()[:-1])

    ncf.close()

    return (exp_name, solver, dx, dt, dome_e, max_e, min_e, mean_e, sd_e)
Example #12
0
def main():

    # Retrieve user input
    try:
        f = open(sys.argv[1], "r")
        lines = f.readlines()
    except:
        print "\n usage: " + sys.argv[0] + " CO2_angles.dat\n"
        sys.exit(0)

    # Read in the data
    angles, probs = [], []
    for line in lines:
        row = line.split()
        angles.append(float(row[0]))
        probs.append(float(row[1]))

    # Do the rescaling
    for i in range(len(angles)):
        factor = ((math.sin(angles[i] * (math.pi / 180.0))) ** 2) ** 0.5
        if factor < 1.0e-03:
            factor = 1.0e-03
        probs[i] /= factor

    norm = Numeric.sum(Numeric.array(probs))

    # Write to output file
    out = open("CO2_angles.dat.norm", "w")
    for i in range(len(angles) - 1):
        out.write(str(angles[i]) + "  " + str(probs[i] / norm) + "\n")
    out.close()
Example #13
0
def solve_linear_equations(a, b):
    one_eq = len(b.shape) == 1
    if one_eq:
        b = b[:, Numeric.NewAxis]
    _assertRank2(a, b)
    _assertSquareness(a)
    n_eq = a.shape[0]
    n_rhs = b.shape[1]
    if n_eq != b.shape[0]:
        raise LinAlgError, 'Incompatible dimensions'
    t =_commonType(a, b)
#    lapack_routine = _findLapackRoutine('gesv', t)
    if _array_kind[t] == 1: # Complex routines take different arguments
        lapack_routine = lapack_lite.zgesv
    else:
        lapack_routine = lapack_lite.dgesv
    a, b = _fastCopyAndTranspose(t, a, b)
    pivots = Numeric.zeros(n_eq, 'l')
    results = lapack_routine(n_eq, n_rhs, a, n_eq, pivots, b, n_eq, 0)
    if results['info'] > 0:
        raise LinAlgError, 'Singular matrix'
    if one_eq:
        return Numeric.ravel(b) # I see no need to copy here
    else:
        return multiarray.transpose(b) # no need to copy
Example #14
0
 def _ticks(self, lower, upper):
     ideal = (upper-lower)/7.
     log = Numeric.log10(ideal)
     power = Numeric.floor(log)
     fraction = log-power
     factor = 1.
     error = fraction
     for f, lf in self._multiples:
         e = Numeric.fabs(fraction-lf)
         if e < error:
             error = e
             factor = f
     grid = factor * 10.**power
     if power > 3 or power < -3:
         format = '%+7.0e'
     elif power >= 0:
         digits = max(1, int(power))
         format = '%' + `digits`+'.0f'
     else:
         digits = -int(power)
         format = '%'+`digits+2`+'.'+`digits`+'f'
     ticks = []
     t = -grid*Numeric.floor(-lower/grid)
     while t <= upper:
         ticks.append( (t, format % (t,)) )
         t = t + grid
     return ticks
    def removePolygons(self):
        """ Remove all the polygons from the object. """

        self.polygonsX = Numeric.array([], Numeric.Float)
        self.polygonsY = Numeric.array([], Numeric.Float)
        self.polygonBeginningsIndex = Numeric.array([], Numeric.Int)
        self.polygonNumberOfItems = Numeric.array([], Numeric.Int)
Example #16
0
 def boundingBox(self):
     p1, p2 = self.objects[0].boundingBox()
     for o in self.objects[1:]:
         p1o, p2o = o.boundingBox()
         p1 = Numeric.minimum(p1, p1o)
         p2 = Numeric.maximum(p2, p2o)
     return p1, p2
Example #17
0
 def _axisInterval(self, spec, lower, upper):
     if spec is None:
         return None
     if spec == 'minimal':
         if lower == upper:
             return lower-0.5, upper+0.5
         else:
             return lower, upper
     if spec == 'automatic':
         range = upper-lower
         if range == 0.:
             return lower-0.5, upper+0.5
         log = Numeric.log10(range)
         power = Numeric.floor(log)
         fraction = log-power
         if fraction <= 0.05:
             power = power-1
         grid = 10.**power
         lower = lower - lower % grid
         mod = upper % grid
         if mod != 0:
             upper = upper - mod + grid
         return lower, upper
     if type(spec) == type(()):
         lower, upper = spec
         if lower <= upper:
             return lower, upper
         else:
             return upper, lower
     raise ValueError, str(spec) + ': illegal axis specification'
    def GetArray(self):
        input = self.__export.GetInput()
        input.UpdateInformation()
        type = input.GetScalarType()
        extent = input.GetWholeExtent()
        numComponents = input.GetNumberOfScalarComponents()
        dim = (extent[5]-extent[4]+1,
               extent[3]-extent[2]+1,
               extent[1]-extent[0]+1)
        if (numComponents > 1):
            dim = dim + (numComponents,)
        size = dim[0]*dim[1]*dim[2]*numComponents*self.__sizeDict[type]

        if _NEW_NUMERIC:
            imArray = Numeric.zeros((size,),Numeric.UnsignedInt8)
            self.__export.Export(imArray)
        else:
            imString = Numeric.zeros((size,),
                                     Numeric.UnsignedInt8).tostring()
            self.__export.Export(imString)
            imArray = Numeric.fromstring(imString,self.__typeDict[type])
            # just to remind myself of the dangers of memory management
            del imString

        # reshape array appropriately.
        imArray = Numeric.reshape(imArray, dim)
        # convert unsigned short to int to avoid sign issues
        if (type == VTK_UNSIGNED_SHORT and self.__ConvertUnsignedShortToInt):
            imArray = umath.bitwise_and(imArray.astype(Numeric.Int32),0xffff)

        return imArray
    def length(self):
        """Returns a scalar field corresponding to the length (norm) of
        the vector field."""
	l = Numeric.sqrt(Numeric.add.reduce(self.values**2, -1))
	try: default = Numeric.sqrt(Numeric.add.reduce(self.default))
	except ValueError: default = None
	return ScalarField(self.axes, l, default, 0)
    def _setsize(self):
	self.width = string.atoi(self.canvas.cget('width'))
	self.height = string.atoi(self.canvas.cget('height'))
	self.plotbox_size = 0.97*Numeric.array([self.width, -self.height])
	xo = 0.5*(self.width-self.plotbox_size[0])
	yo = self.height-0.5*(self.height+self.plotbox_size[1])
	self.plotbox_origin = Numeric.array([xo, yo])
    def draw(self, graphics):
        """Draws the graphics object |graphics|, which can be
        a PolyLine3D or a VisualizationGraphics object."""
	self.last_draw = (graphics, )
	self.configure(cursor='watch')
	self.update_idletasks()
        graphics.project(self.axis, self.plane)
	p1, p2 = graphics.boundingBoxPlane()
        center = 0.5*(p1+p2)
	scale = self.plotbox_size / (p2-p1)
        sign = scale/Numeric.fabs(scale)
        if self.scale is None:
            minscale = Numeric.minimum.reduce(Numeric.fabs(scale))
            self.scale = 0.9*minscale
        scale = sign*self.scale
        box_center = self.plotbox_origin + 0.5*self.plotbox_size
	shift = -center*scale + box_center + self.translate
	graphics.scaleAndShift(scale, shift)
	items, depths = graphics.lines()
        sort = Numeric.argsort(depths)
        for index in sort:
            x1, y1, x2, y2, color, width = items[index]
            Line(self.canvas, x1, y1, x2, y2, fill=color, width=width)
	self.configure(cursor='top_left_arrow')
	self.update_idletasks()
Example #22
0
        def computeTriangle(tri):
            """This is a nested function which computes the angles in a triangle
            or on the face of a tetrahedron.
            
            Could employ dot product or cosine & sine rules.
            
            Input: three references to points in array 'cells'
            Output: three angles in degrees (list)
            """

            # define three rotations of the same triangle so that the same
            # algorithm can be used to find each angle
            a = points[tri[0]]; b = points[tri[1]]; c = points[tri[2]]
            tris = [[a, b, c], [b, c, a], [c, b, a]]
            angles = []
            
            for i in tris:
                # define 2 vectors representing 2 sides of the triangle
                # either side of the angle to be calculated
                r_ab = Numeric.transpose(i[1]) - i[0]
                r_ac = Numeric.transpose(i[2]) - i[0]
                
                # calculate the angle between the two sides
                rdotr = Numeric.dot(r_ab, r_ac)
                modrr = math.sqrt(sum(r_ab**2))*math.sqrt(sum(r_ac**2))
                
                angle = math.degrees(math.acos(rdotr / modrr))
                angles.append(angle)
                
#                tangles = Numeric.zeros([3],Numeric.Float32)
#            print len(angles)
#            print angles[0], angles[1], angles[2]
            tangles = [angles[0], angles[1], angles[2]]
            return tangles
Example #23
0
def GetLatLongString(ddvalue,lltype='latitude'):
    """ Convert a decimal degree value to a
        string appropriate for Lat/Long
        display.

        ddvalue- position in decimal degrees
        lltype- latitude or longitude

        returns: lat/long string
    """
    import Numeric
    
    deg=int(abs(ddvalue))
    min=int((abs(ddvalue)-deg)*60)
    sec=int((abs(ddvalue)-deg-(float(min)/60.0))*3600.0)
    if lltype == 'latitude':
        if Numeric.sign(ddvalue) == -1:
            ch='S'
        else:
            ch='N'
    else:
        if Numeric.sign(ddvalue) == -1:
            ch='W'
        else:
            ch='E'

    nstr="%dd%d'%.1f''%s" % (deg,min,sec,ch)
    return nstr
Example #24
0
def _conv_numpy_to_numeric(array):
    kind = array.dtype.kind
    if kind == 'V':
        raise FlavorError( "the ``numeric`` flavor does not support "
                           "heterogeneous arrays" )

    # It seems that the array protocol in Numeric does leak.  See
    # http://comments.gmane.org/gmane.comp.python.numeric.general/12563
    # for more info on this issue.
    ##if kind != 'S':
    ##    return Numeric.asarray(array)  # use the array protocol

    shape = array.shape
    if kind == 'S':
        if array.itemsize > 1:
            # Numeric does not support character arrays with elements
            # with a size > 1.  Simulate with an additional dimension.
            shape = shape + (array.itemsize,)
        typecode = 'c'
    else:
        # See the above note about the Numeric leak.
        typecode = _numtype_from_nptype[array.dtype.type]
    # Convert to a contiguous buffer (``tostring()`` is very efficient).
    arrstr = array.tostring()
    array = Numeric.fromstring(arrstr, typecode)
    array = Numeric.reshape(array, shape)
    return array
Example #25
0
def raster_add( s_fh, s_xoff, s_yoff, s_xsize, s_ysize, s_band_n,
                             t_fh, t_xoff, t_yoff, t_xsize, t_ysize, t_band_n,
                             nodata ):

    import Numeric
    
    if verbose != 0:
        print 'Copy %d,%d,%d,%d to %d,%d,%d,%d.' \
              % (s_xoff, s_yoff, s_xsize, s_ysize,
             t_xoff, t_yoff, t_xsize, t_ysize )

    s_band = s_fh.GetRasterBand( s_band_n )
    t_band = t_fh.GetRasterBand( t_band_n )

    data_src = s_band.ReadAsArray( s_xoff, s_yoff, s_xsize, s_ysize,
                                   t_xsize, t_ysize )
    data_dst = t_band.ReadAsArray( t_xoff, t_yoff, t_xsize, t_ysize )

    nodata_test = Numeric.equal(data_src,s_band.GetNoDataValue())
    data_src_fill = Numeric.choose( nodata_test, (data_src, 0) )
   
    to_write = Numeric.add(data_src_fill,data_dst)
                               
    t_band.WriteArray( to_write, t_xoff, t_yoff )
    
    return 0
Example #26
0
def main():

    # Retrieve user input
    try:
        f = open(sys.argv[1],'r')
        lines = f.readlines()
        f.close()
    except:
        print '\n usage: '+sys.argv[0]+' XY.dat\n'
        sys.exit(0)

    # Parse the data
    t, y = [], []
    for line in lines:
        t.append(float(line.split()[0]))
        y.append(float(line.split()[1]))

    # Calculate the FFT and get the frequencies
    N  = float(len(t))
    dt = t[1] - t[0]
    T  = N * dt
    df = 1.0 / T
    f  = Numeric.arange(N,typecode=Numeric.Float)*df
    H  = ( FFT.fft(y)*Numeric.conjugate(FFT.fft(y)) ).real / N

    # Write to file
    out = open('PSD.dat','w')
    for i in range(len(f)/2):
        out.write(str(f[i])+' '+str(H[i])+'\n')
    out.close()
Example #27
0
def overshootPath(pts):
    result = []
    for i in range(1, len(pts)-1):
        p2 = pts[i]
        back = 0
        i2 = i
        while back < 40 and i2 > 0:
            back += Vector(pts[i2 + 1] - pts[i2]).length()
            i2 -= 1
        p0 = pts[i2]

        back = 0
        i2 = i
        while back < 25 and i2 > 0:
            back += Vector(pts[i2 + 1] - pts[i2]).length()
            i2 -= 1
        p1 = pts[i2]

        f = 1
        d = 5
        p = -f/d * p0 + -(f*2)/d * p1 + (d + f * 3)/d * p2

        result.append(num.array([p[0], p[1]]))

    nearPts = num.concatenate((pts[:15], pts[-15:]))
    inner = sum(nearPts) / len(nearPts)

    result = [inner] + result[-2:] + result + result[:7]

        
    return result
Example #28
0
def GetAlphabeticGridString(index):
    """ Get string for reference grid horizontal
        index (1='A',2='B',...,27='AA',...)
    """
    # This function doesn't work yet.
    alphabet=['A','B','C','D','E','F','G','H','I','J','K',
              'L','M','N','O','P','Q','R','S','T','U','V',
              'W','X','Y','Z']
    alen=len(alphabet)
    sc=Numeric.log(alen)
    nletters=int(Numeric.log(index)/sc)
    str=''
    rem=index
    for idx in range(nletters,-1,-1):
        rint=int(rem/pow(alen,idx-1))
        rem=rem-rint*pow(alen,idx-1)
        print 'rint ',rint,' rem: ',rem
        if (rint == 0) and (len(str) == 0):
            continue
        if rem == 0:
            str=str+alphabet[0]
        else:    
            str=str+alphabet[rint-1]
        
    return str
Example #29
0
def _getMatrix(data, dof):
    """Create the matrices A and b for a spline with 4 data points."""    
    # We need to be sure that we've got exactly 4 data points. 
    assert(Numeric.shape(data)[0] == 4)

    A = Numeric.zeros((12, 12))
    b = [Numeric.zeros((12,)) for i in range(dof)]
    row = 0

    for t in range(1,4):
        # Constrain the spline to fit the 4 points in this chunk of the
        # trajectory.
        col = (t - 1) * 4
        A[row, col:col + 4] = [1, t, t**2, t**3]
        for i in range(dof): b[i][row] = data[t - 1, i]
        row += 1

        A[row, col:col + 4] = [1, t + 1, (t + 1)**2, (t + 1)**3]
        for i in range(dof): b[i][row] = data[t, i]
        row += 1

        # Constrain the first and second derivatives at each of the
        # internal points to be equal.
        if t < 3:
            A[row + 4, col:col + 8] = [0, 1, 2 * t, 3 * t**2, 0, -1, -2 * t, -3 * t**2]
            A[row + 5, col:col + 8] = [0, 0, 2, 6 * t, 0, 0, -2, -6 * t]

    # Constrain the second derivative of the end points of the trajectory to
    # be 0.
    A[-2, :4] = [0, 0, 2, 6]
    A[-1, -4:] = [0, 0, 2, 24]

    return (A, b)
Example #30
0
    def __find_opt_w_p_node(self):
        """Help function for load_balancing()
        Finds and returns the optimal number of walkers
        per node for a possibly non-uniform set of nodes
        """
        timings = self.pypar.gather(Numeric.array([abs(self.t1-self.t0)]),
                                    self.master_rank)
        tmp_timings = copy.deepcopy(timings)
        timings = self.pypar.broadcast(tmp_timings,
                                       self.master_rank)

        C = self.no_of_walkers/sum(1./timings)

        tmp_loc_walkers = C/timings

        self.loc_walkers = self.NumericFloat2IntList(tmp_loc_walkers)
        remainders = tmp_loc_walkers-self.loc_walkers

        while sum(self.loc_walkers) < self.no_of_walkers:
            maxarg = Numeric.argmax(remainders)
            self.loc_walkers[maxarg] += 1
            remainders[maxarg] = 0

        if self.master and self.first_balance and\
               not hasattr(self,'silent'):
            print timings
            print self.loc_walkers

        return self.loc_walkers
Example #31
0
 def op_less_than(self, value, filter_keys):
     return Numeric.arrayrange(value)
Example #32
0
 def check_numpy_array_argument_return(self):
     import numpy as N
     f = PyCFunction('foo')
     f += Variable('a', N.ndarray, 'in, out')
     foo = f.build()
     assert_equal(foo(N.array([1, 2])), N.array([1, 2]))
Example #33
0
    def __init__(self, *args):
        Qt.QWidget.__init__(self, *args)

        layout = Qt.QGridLayout(self)

        # try to create a plot for SciPy arrays
        try:
            # import does_not_exist
            import numpy
            # make a curve and copy the data
            numpy_curve = Qwt.QwtPlotCurve('y = lorentzian(x)')
            x = numpy.arange(0.0, 10.0, 0.01)
            y = lorentzian(x)
            numpy_curve.setData(x, y)
            # here, we know we can plot NumPy arrays
            numpy_plot = Qwt.QwtPlot(self)
            numpy_plot.setTitle('numpy array')
            numpy_plot.setCanvasBackground(Qt.Qt.white)
            numpy_plot.plotLayout().setCanvasMargin(0)
            numpy_plot.plotLayout().setAlignCanvasToScales(True)
            # insert a curve and make it red
            numpy_curve.attach(numpy_plot)
            numpy_curve.setPen(Qt.QPen(Qt.Qt.red))
            layout.addWidget(numpy_plot, 0, 0)
            numpy_plot.replot()
        except ImportError as message:
            print("%s: %s" % (ImportError, message))
            print("Install NumPy to plot plot NumPy arrays")
        except TypeError as message:
            print("%s: %s" % (TypeError, message))
            print("Rebuild PyQwt to plot NumPy arrays")

        # try to create a plot for Numeric arrays
        try:
            # import does_not_exist
            import Numeric
            # make a curve and copy the data
            numeric_curve = Qwt.QwtPlotCurve('y = lorentzian(x)')
            x = Numeric.arange(0.0, 10.0, 0.01)
            y = lorentzian(x)
            numeric_curve.setData(x, y)
            # here, we know we can plot Numeric arrays
            numeric_plot = Qwt.QwtPlot(self)
            numeric_plot.setTitle('Numeric array')
            numeric_plot.setCanvasBackground(Qt.Qt.white)
            numeric_plot.plotLayout().setCanvasMargin(0)
            numeric_plot.plotLayout().setAlignCanvasToScales(True)
            # insert a curve and make it red
            numeric_curve.attach(numeric_plot)
            numeric_curve.setPen(Qt.QPen(Qt.Qt.red))
            layout.addWidget(numeric_plot, 0, 1)
            numeric_plot.replot()
        except ImportError as message:
            print("%s: %s" % (ImportError, message))
            print("Install Numeric to plot Numeric arrays")
        except TypeError as message:
            print("%s: %s" % (TypeError, message))
            print("Rebuild PyQwt to plot Numeric arrays")

        # try to create a plot for numarray arrays
        try:
            # import does_not_exist
            import numarray
            # make a curve and copy the data
            numarray_curve = Qwt.QwtPlotCurve('y = lorentzian(x)')
            x = numarray.arange(0.0, 10.0, 0.01)
            y = lorentzian(x)
            numarray_curve.setData(x, y)
            # here, we know we can plot numarray arrays
            numarray_plot = Qwt.QwtPlot(self)
            numarray_plot.setTitle('numarray array')
            numarray_plot.setCanvasBackground(Qt.Qt.white)
            numarray_plot.plotLayout().setCanvasMargin(0)
            numarray_plot.plotLayout().setAlignCanvasToScales(True)
            # insert a curve and make it red
            numarray_curve.attach(numarray_plot)
            numarray_curve.setPen(Qt.QPen(Qt.Qt.red))
            layout.addWidget(numarray_plot, 1, 0)
            numarray_plot.replot()
        except ImportError as message:
            print("%s: %s" % (ImportError, message))
            print("Install numarray to plot numarray arrays")
        except TypeError as message:
            print("%s: %s" % (TypeError, message))
            print("Rebuild PyQwt to plot numarray arrays")

        # create a plot widget for lists of Python floats
        list_plot = Qwt.QwtPlot(self)
        list_plot.setTitle('Python list')
        list_plot.setCanvasBackground(Qt.Qt.white)
        list_plot.plotLayout().setCanvasMargin(0)
        list_plot.plotLayout().setAlignCanvasToScales(True)
        x = drange(0.0, 10.0, 0.01)
        y = [lorentzian(item) for item in x]
        # insert a curve, make it red and copy the lists
        list_curve = Qwt.QwtPlotCurve('y = lorentzian(x)')
        list_curve.attach(list_plot)
        list_curve.setPen(Qt.QPen(Qt.Qt.red))
        list_curve.setData(x, y)
        layout.addWidget(list_plot, 1, 1)
        list_plot.replot()
Example #34
0
 def op_between(self, value, filter_keys):
     return Numeric.arrayrange(*value)
Example #35
0
 def op_greater_equal(self, value, filter_keys):
     return Numeric.arrayrange(value, len(self))
Example #36
0
 def op_greater_than(self, value, filter_keys):
     return Numeric.arrayrange(value + 1, len(self))
Example #37
0
 def op_less_equal(self, value, filter_keys):
     return Numeric.arrayrange(value + 1)
Example #38
0
    def __init__(self, startfile, communicator=None, deforming_mesh=False):
        """Initialize the object.

        Keyword arguments:

        startfile      -- the name of the SUmb input parameter file
        communicator   -- an MPI communicator for specifying which processors
                          to run on (optional)
        deforming_mesh -- set to True or False whether or not this is a 
                          deforming mesh case (optional, default is False)
                          

        """
        # Make sure the parameter file exists
        if not os.path.isfile(startfile):
            print 'Error: Could not find file %s' % startfile
            return None

        # Setup a mesh object
        self.Mesh = SUmbMesh()

        # Create a Python communicator to mirror the Fortran
        # SUmb_COMM_WORLD and set the Fortran SUmb communicator to the
        # Python one.
        if (communicator is not None):
            self.sumb_comm_world = communicator
        else:
            self.sumb_comm_world = mpi.COMM_WORLD.comm_create(
                mpi.COMM_WORLD[:])
        sumb.communication.sumb_comm_world = int(self.sumb_comm_world)
        self.Mesh.sumb_comm_world = self.sumb_comm_world

        # Store the name of the input file
        self.startfile = startfile
        sumb.inputio.paramfile[0:len(startfile)] = startfile

        # Determine the rank and number of processors inside the group
        # defined by sumb_comm_world.
        self.myid = sumb.communication.myid = self.sumb_comm_world.rank
        self.nproc = sumb.communication.nproc = self.sumb_comm_world.size

        # Allocate the memory for SENDREQUESTS and RECVREQUESTS.
        try:
            sumb.communication.sendrequests = Numeric.zeros(
                (self.sumb_comm_world.size))
            sumb.communication.recvrequests = Numeric.zeros(
                (self.sumb_comm_world.size))
        except:
            print "Memory allocation failure for SENDREQUESTS " \
           "and RECVREQUESTS."
            return

        # Set the SUmb module value of standalonemode to false and
        # the value of deforming_grid to the input value.
        sumb.iteration.standalonemode = False
        sumb.iteration.deforming_grid = deforming_mesh

        # Write the intro message
        sumb.writeintromessage()

        # Read the parameter file
        sumb.readparamfile()

        # Partition the blocks and read the grid
        sumb.partitionandreadgrid()

        # Perform the preprocessing task
        sumb.preprocessing()

        # Initialize the flow variables
        sumb.initflow()

        # Create dictionary of variables we are monitoring
        nmon = sumb.monitor.nmon[0]
        self.monnames = {}
        for i in range(nmon):
            self.monnames[string.strip(
                sumb.monitor.monnames[i].tostring())] = i

        # Create dictionary of the family names
        sumb.mdgetfamilynames()
        nfamilies = sumb.mddata.mdnfamilies[0]
        self.Mesh.families = {}
        for i in range(nfamilies):
            self.Mesh.families[string.strip(
                sumb.mddata.mdfamilynames[i].tostring())] = i + 1
        sumb.mdcreatensurfnodes()

        # Determine the total number of blocks in the mesh and store it
        self.Mesh.nmeshblocks = self.sumb_comm_world.allreduce(
            sumb.block.ndom[0], mpi.SUM)

        return
Example #39
0
import Numeric, hist, math, random

a = Numeric.array(
    map(
        lambda x: map(lambda y: float(y), x.split()),
        open("/cdat/dafe/mccann/luminosity/tunes.dat",
             "r").read().splitlines()))

execfile("/cdat/dafe/mccann/luminosity/tmp.py")


def cotT(aline):
    myx = random.gauss(bx, bdx)
    myy = random.gauss(by, bdy)
    myz = 0.
    if random.random() > bzgap:
        myz = random.gauss(bz, bdz1)
    else:
        myz = random.gauss(bz, bdz2)
    (westx, westy, westz, eastx, easty, eastz) = aline
    westcotT = (westz + myz) / math.sqrt((westx + myx)**2 + (westy + myy)**2)
    eastcotT = (eastz + myz) / math.sqrt((eastx + myx)**2 + (easty + myy)**2)
    return (westcotT - eastcotT) / 2.


(bx, by, bz) = (0., 0., 0.)
(bdx, bdy, bdz1, bdz2, bzgap) = (0., 0., 0., 0., 0.)


def test(x, y, z, dx, dy, dz1, dz2, zgap):
    global bx, by, bz, bdx, bdy, bdz1, bdz2, bzgap
Example #40
0
 def take(self, rows):
     return Numeric.take(self.data, rows)
Example #41
0
 def all_reduce(self, x):
     xs = self.pypar.gather(Numeric.array([x]), self.master_rank)
     return self.pypar.broadcast(float(Numeric.sum(xs)), self.master_rank)
Example #42
0
def sma(input, length):
    # return the sma for the current bar (input[0])
    return Numeric.sum(input[0:length]) / length
Example #43
0
        ttl1='Ideal Wall'
      elif data['tw']==0:
        ttl1='No Wall'
      else:
        ttl1 = '%s=10^{%g}'%(ttl,(cmath.log10(data[var_key]).real))
    try:
      g._add_to_queue([Gnuplot.Data(evalsr,evalsi,with='points ps 2',title=ttl1)])
      if i == int(ref):
        g.itemlist[-1].set_option(with='points ps 3')
    except (ValueError):
      continue
    var_list.append(data[var_key])
for i in range(len(matching_files)):
  print matching_files[i],':',var_list[i],';  ',
print ''
inds = Numeric.argsort(var_list)
g.itemlist = list(Numeric.take(g.itemlist,inds))
if min(var_list)==-1:
  g.itemlist.append(g.itemlist[0])
  g.itemlist = g.itemlist[1:]
tt = ''
for i in range(len(print_keys)):
  if print_keys[i] != var_key:
    tt = tt+'%s=%g, '%(print_keys[i],d1.data[print_keys[i]])
g.title(tt[:-2])
set_ytics = 'set ytics ('
set_xtics = 'set xtics ('
for i in range(2):
  for j in range(-int(cmath.log10(scale_fac).real)+0,13,1):
    scale = (-1)**i*10**j
    if j%2 != 0:
Example #44
0
 def NumericFloat2IntList(self, x):
     return Numeric.array(x.tolist(), 'i').tolist()
		self.uiinboundinterval = uidata.Integer('Interval', 10, 'rw', persist=True)
		inboundcontainer = uidata.Container('Inbound')
		inboundcontainer.addObjects((self.uiinboundhostname,
																	self.uiinboundusername,
																	self.uiinboundpassword,
																	self.uiinboundinterval))
		testsettingsmethod = uidata.Method('Confirm', self.testSettings)
		settingscontainer = uidata.Container('Settings')
		settingscontainer.addObjects((addresscontainer, outboundcontainer,
																	inboundcontainer, testsettingsmethod))

		container = uidata.LargeContainer('Email')
		container.addObjects((statuscontainer, settingscontainer))
		self.uicontainer.addObject(container)
	'''

if __name__ == '__main__':
	import getpass
	import Numeric

	numericimage = Numeric.ones((256, 256))
	imagestring = NumericImage2String(numericimage)
	message = makeMessage('*****@*****.**', '*****@*****.**',
															'testing email', 'this is a test...', imagestring)
	send(message, 'cronus1')
	#username = getpass.getuser()
	username = '******'
	password = getpass.getpass()
	print waitForReply(message, 'mail.scripps.edu', username, password)

Example #46
0
def main():

    # Grab config file from command line ========================================

    if sys.argv[1]:
        configFile = sys.argv[1]
    else:
        print "Please supply a config file."
        return

    # Parse config file =========================================================

    file = open(configFile, 'r')
    fileContents = file.read()
    pattern = re.compile(r"^(\w+)\s*=(.*)$", re.M)
    config = pattern.findall(fileContents)
    config = dict(config)
    for key in config:
        config[key] = config[key].strip()
        #print key+": "+config[key]

    # Construct the problem =====================================================

    #=== Comm ===#
    comm = Epetra.PyComm()

    #=== Map ===#

    # These two lines work correctly...
    n = 19881
    map = Epetra.Map(n, 0, comm)

    # ...this doesn't...but we'd like to create the map directly from the file...
    #(ierr, map) = EpetraExt.MatrixMarketFileToMap(config['A_FILE'], comm)

    #=== Matrix ===#
    (ierr,
     matrix) = EpetraExt.MatrixMarketFileToCrsMatrix(config['A_FILE'], map)

    #=== LHS ===#
    if config.has_key('X_FILE') and config['X_FILE']:
        file = open(config['X_FILE'], 'r')
        fileContents = file.read()
        pattern = re.compile(r"\s*\d+\s+\d+\s+((?:-|\d|.)+)\s*$", re.M)
        values = pattern.findall(fileContents)
        values = [float(v) for v in values]
        lhs = Epetra.Vector(map, Numeric.array(values))
    else:
        lhs = Epetra.Vector(map)
        lhs.Random()

    #=== RHS ===#
    if config.has_key('B_FILE') and config['B_FILE']:
        file = open(config['B_FILE'], 'r')
        fileContents = file.read()
        pattern = re.compile(r"\s*\d+\s+\d+\s+((?:-|\d|.)+)\s*$", re.M)
        values = pattern.findall(fileContents)
        values = [float(v) for v in values]
        rhs = Epetra.Vector(map, Numeric.array(values))
    else:
        rhs = Epetra.Vector(map)
        rhs.PutScalar(0.0)

    # Solve the problem =========================================================

    # sets up the parameters for ML using a python dictionary
    mlList = {}

    mlList['output'] = 10

    if config.has_key('SMOOTHER_TYPE') and config['SMOOTHER_TYPE']:
        mlList['smoother: type'] = config['SMOOTHER_TYPE']

    if config.has_key('SMOOTHER_SWEEPS') and config['SMOOTHER_SWEEPS']:
        mlList['smoother: sweeps'] = int(config['SMOOTHER_SWEEPS'])

    if config.has_key('SMOOTHER_MLS_POLYNOMIAL_ORDER'
                      ) and config['SMOOTHER_MLS_POLYNOMIAL_ORDER']:
        mlList['smoother: MLS plynomial order'] = int(
            config['SMOOTHER_MLS_POLYNOMIAL_ORDER'])

    if config.has_key('COARSE_TYPE') and config['COARSE_TYPE']:
        mlList['coarse: type'] = config['COARSE_TYPE']

    if config.has_key('COARSE_SWEEPS') and config['COARSE_SWEEPS']:
        mlList['coarse: sweeps'] = int(config['COARSE_SWEEPS'])

    if config.has_key('COARSE_MLS_POLYNOMIAL_ORDER'
                      ) and config['COARSE_MLS_POLYNOMIAL_ORDER']:
        mlList['coarse: MLS plynomial order'] = int(
            config['COARSE_MLS_POLYNOMIAL_ORDER'])

    if config.has_key('MAX_LEVELS') and config['MAX_LEVELS']:
        mlList['max levels'] = int(config['MAX_LEVELS'])

    if config.has_key('AGGREGATION_TYPE') and config['AGGREGATION_TYPE']:
        mlList['aggregation: type'] = config['AGGREGATION_TYPE']

    if config.has_key('AGGREGATION_DAMPING_FACTOR'
                      ) and config['AGGREGATION_DAMPING_FACTOR']:
        mlList['aggregation: damping factor'] = float(
            config['AGGREGATION_DAMPING_FACTOR'])

    # creates the preconditioner and computes it
    prec = ML.MultiLevelPreconditioner(matrix, False)
    prec.SetParameterList(mlList)
    prec.ComputePreconditioner()

    # sets up the solver, specifies Prec as preconditioner, and solves using CG.
    solver = AztecOO.AztecOO(matrix, lhs, rhs)
    solver.SetPrecOperator(prec)
    solver.SetAztecOption(AztecOO.AZ_solver, AztecOO.AZ_cg)
    solver.SetAztecOption(AztecOO.AZ_output, 16)
    solver.Iterate(1550, 1e-5)
Example #47
0
def ReadRaster(raster, x, y, w, h):
    """读取栅格数据(用来保证越界不会出错)
    @type raster: gdal.RasterDataset
    @param raster: 数据集
    @type x:int
    @type y:int
    @type w:int
    @type h: int
    @param x,y,w,h: 读取栅格的矩形大小
    """
    rasw, rash = raster.RasterXSize, raster.RasterYSize
    bandcount = raster.RasterCount
    begx, begy, width, height = x, y, w, h
    exwr, exwl, exhb, exht = 0, 0, 0, 0  #超过图像范围的行列
    if x < 0:
        begx = 0
        exwl = -x
        width -= exwl
    if y < 0:
        begy = 0
        exht = -y
        height -= exht
    if x + w > rasw:
        exwr = x + w - rasw
        width = rasw - begx
    if y + h > rash:
        exhb = y + h - rash
        height = rash - begy
    print begx, begy, width, height
    data = raster.ReadAsArray(begx, begy, width, height)
    datatype = data.typecode()
    data = RRGGBB2RGBRGB(data)

    #进行数组的扩展和补充
    if exwl > 0 and exwr > 0:
        data1 = Num.zeros((height, exwl, bandcount), datatype)
        data2 = Num.zeros((height, exwr, bandcount), datatype)
        data = Num.concatenate((data1, data, data2), 1)
    elif exwl > 0:
        data1 = Num.zeros((height, exwl, bandcount), datatype)
        data = Num.concatenate((data1, data), 1)
    elif exwr > 0:
        data2 = Num.zeros((height, exwr, bandcount), datatype)
        data = Num.concatenate((data, data2), 1)

    if exht > 0 and exhb > 0:
        data1 = Num.zeros((exht, w, bandcount), datatype)
        data2 = Num.zeros((exhb, w, bandcount), datatype)
        data = Num.concatenate((data1, data, data2))
    elif exht > 0:
        data1 = Num.zeros((exht, w, bandcount), datatype)
        data = Num.concatenate((data1, data))
    elif exhb > 0:
        data2 = Num.zeros((exhb, w, bandcount), datatype)
        data = Num.concatenate((data, data2))

    return data
Example #48
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((640, 480))

    im1 = pygame.Surface(screen.get_size())
    #im1= im1.convert()
    im1.fill((100, 0, 0))

    im2 = pygame.Surface(screen.get_size())
    im2.fill((0, 50, 0))
    # we make a srcalpha copy of it.
    #im3= im2.convert(SRCALPHA)
    im3 = im2
    im3.set_alpha(127)

    images = {}
    images[K_1] = im2
    images[K_2] = pygame.image.load(os.path.join(data_dir, "chimp.bmp"))
    images[K_3] = pygame.image.load(os.path.join(data_dir, "alien3.gif"))
    images[K_4] = pygame.image.load(os.path.join(data_dir, "liquid.bmp"))
    img_to_blit = im2.convert()
    iaa = img_to_blit.convert_alpha()

    blits = {}
    blits[K_a] = BLEND_ADD
    blits[K_s] = BLEND_SUB
    blits[K_m] = BLEND_MULT
    blits[K_EQUALS] = BLEND_MAX
    blits[K_MINUS] = BLEND_MIN

    blitsn = {}
    blitsn[K_a] = "BLEND_ADD"
    blitsn[K_s] = "BLEND_SUB"
    blitsn[K_m] = "BLEND_MULT"
    blitsn[K_EQUALS] = "BLEND_MAX"
    blitsn[K_MINUS] = "BLEND_MIN"

    screen.blit(im1, (0, 0))
    pygame.display.flip()
    clock = pygame.time.Clock()
    print("one pixel is:%s:" % [im1.get_at((0, 0))])

    going = True
    while going:
        clock.tick(60)

        for event in pygame.event.get():
            if event.type == QUIT:
                going = False
            if event.type == KEYDOWN:
                usage()

            if event.type == KEYDOWN and event.key == K_ESCAPE:
                going = False

            elif event.type == KEYDOWN and event.key in images.keys():
                img_to_blit = images[event.key]
                iaa = img_to_blit.convert_alpha()

            elif event.type == KEYDOWN and event.key in blits.keys():
                t1 = time.time()
                # blits is a dict keyed with key -> blit flag.  eg BLEND_ADD.
                im1.blit(img_to_blit, (0, 0), None, blits[event.key])
                t2 = time.time()
                print("one pixel is:%s:" % [im1.get_at((0, 0))])
                print("time to do:%s:" % (t2 - t1))

            elif event.type == KEYDOWN and event.key in [K_t]:

                for bkey in blits.keys():
                    t1 = time.time()

                    for x in range(300):
                        im1.blit(img_to_blit, (0, 0), None, blits[bkey])

                    t2 = time.time()

                    # show which key we're doing...
                    onedoing = blitsn[bkey]
                    print("time to do :%s: is :%s:" % (onedoing, t2 - t1))

            elif event.type == KEYDOWN and event.key in [K_o]:
                t1 = time.time()
                # blits is a dict keyed with key -> blit flag.  eg BLEND_ADD.
                im1.blit(iaa, (0, 0))
                t2 = time.time()
                print("one pixel is:%s:" % [im1.get_at((0, 0))])
                print("time to do:%s:" % (t2 - t1))

            elif event.type == KEYDOWN and event.key == K_SPACE:
                # this additive blend without clamp two surfaces.
                #im1.set_alpha(127)
                #im1.blit(im1, (0,0))
                #im1.set_alpha(255)
                t1 = time.time()

                im1p = pygame.surfarray.pixels2d(im1)
                im2p = pygame.surfarray.pixels2d(im2)
                im1p += im2p
                del im1p
                del im2p
                t2 = time.time()
                print("one pixel is:%s:" % [im1.get_at((0, 0))])
                print("time to do:%s:" % (t2 - t1))

            elif event.type == KEYDOWN and event.key in [K_z]:
                t1 = time.time()
                im1p = pygame.surfarray.pixels3d(im1)
                im2p = pygame.surfarray.pixels3d(im2)
                im1p16 = im1p.astype(Numeric.UInt16)
                im2p16 = im1p.astype(Numeric.UInt16)
                im1p16 += im2p16
                im1p16 = Numeric.minimum(im1p16, 255)
                pygame.surfarray.blit_array(im1, im1p16)

                del im1p
                del im2p
                t2 = time.time()
                print("one pixel is:%s:" % [im1.get_at((0, 0))])
                print("time to do:%s:" % (t2 - t1))

            elif event.type == KEYDOWN and event.key in [K_r, K_g, K_b]:
                # this adds one to each pixel.
                colmap = {}
                colmap[K_r] = 0x10000
                colmap[K_g] = 0x00100
                colmap[K_b] = 0x00001
                im1p = pygame.surfarray.pixels2d(im1)
                im1p += colmap[event.key]
                del im1p
                print("one pixel is:%s:" % [im1.get_at((0, 0))])

            elif event.type == KEYDOWN and event.key == K_p:
                print("one pixel is:%s:" % [im1.get_at((0, 0))])

            elif event.type == KEYDOWN and event.key == K_f:
                # this additive blend without clamp two surfaces.

                t1 = time.time()
                im1.set_alpha(127)
                im1.blit(im2, (0, 0))
                im1.set_alpha(255)

                t2 = time.time()
                print("one pixel is:%s:" % [im1.get_at((0, 0))])
                print("time to do:%s:" % (t2 - t1))

        screen.blit(im1, (0, 0))
        pygame.display.flip()

    pygame.quit()
import biggles, Numeric

x = [9.460 - 0.020, 9.460, 10.023 - 0.020, 10.023, 10.355 - 0.020, 10.355]
y = [0.9990, 0.9921, 1.0002, 0.9969, 0.9983, 0.9928]
dy = [0.0025, 0.0020, 0.0017, 0.0037, 0.0029, 0.0023]

p = biggles.Table(2, 1)
p[0, 0] = biggles.FramedPlot()
p[0, 0].add(biggles.Points(x, y, symboltype="filled circle"))
p[0, 0].add(biggles.SymmetricErrorBarsY(x, y, dy))
p[0, 0].add(biggles.LineY(1.))
p[0, 0].x1.range = 9.3, 10.5
p[0, 0].y1.range = 0.985, 1.0035
p[0, 0].x1.label = "Center of mass energy (GeV)"
p[0, 0].y1.label = "BB lumi / GG lumi"

p[1, 0] = biggles.FramedPlot()
p[1,0].add(biggles.Curve([9.3, 9.4, 9.4, 9.5, 9.5, 10, 10, 10.1, 10.1, 10.3, 10.3, 10.4, 10.4, 10.5],\
                          Numeric.array([0, 0, 350.3*0.025/8.993, 350.3*0.025/8.993, 0, 0, 142.32*0.020/7.945, 142.32*0.020/7.945, 0, 0, 96.14*0.024/7.361, 96.14*0.024/7.361, 0, 0])*18/350.3))
p[1, 0].x1.range = 9.3, 10.5
p[1, 0].x1.label = "Center of mass energy (GeV)"
p[1, 0].y1.label = r"Size of $\Upsilon \to e^+e^-$ correction"
p[1, 0].y1.range = 0., 0.06

p.show()
p.write_eps("lumiratio.eps")
Example #50
0
    def guess_cb(self, *args):
	"""Guess image geometry parameters."""

	def correlation(array1, array2):
	    """Calculate correlation coefficient of two arrays."""
	    n_elems = float(array1.shape[0])
	    M1 = Numeric.add.reduce(array1)
	    M2 = Numeric.add.reduce(array2)
	    D1 = Numeric.add.reduce(array1 * array1) - M1 * M1 / n_elems
	    D2 = Numeric.add.reduce(array2 * array2) - M2 * M2 / n_elems
            K = (Numeric.add.reduce(array1 * array2) - M1 * M2 / n_elems) / math.sqrt(D1 * D2)

	    return K

	header = long(self.header_entry.get_text())
	width = long(self.width_entry.get_text())
	height = long(self.height_entry.get_text())
	bands = long(self.bands_entry.get_text())
	gdaltype = \
	    gdal.GetDataTypeByName(self.type_list[self.type_menu.get_history()])
	numtype = gdalnumeric.GDALTypeCodeToNumericTypeCode(gdaltype)
	depth = gdal.GetDataTypeSize(gdaltype) / 8
	
	filename = self.open_entry.get_text()
        if os.path.isfile(filename) == 0:
            gvutils.error('Input file '+filename+' does not exist!')
            return
        
	filesize = os.stat(filename)[ST_SIZE]
	if filesize < header:
	    gvutils.error('Specified header size larger then file size!')
            return
	imagesize = (filesize - header) / bands / depth

	if width != 0 and height == 0:
	    height = imagesize / width
	elif width == 0 and height != 0:
	    width = imagesize / height
	else:
	    rawfile = open(filename, 'rb')
	    longt = 40.0	# maximum possible height/width ratio
	    cor_coef = 0.0
	    w = long(math.sqrt(imagesize / longt))
	    w_max = long(math.sqrt(imagesize * longt))
	    if (self.swap_menu.get_history() == 0 \
		and sys.byteorder == 'little') or \
	       (self.swap_menu.get_history() == 1 and sys.byteorder == 'big'):
		swap = 0
	    else:
		swap = 1
	    while w < w_max:
		if imagesize % w == 0:
		    scanlinesize = w * depth
		    h = imagesize / w
		    rawfile.seek(header + h / 2 * scanlinesize)
		    buf1 = rawfile.read(scanlinesize)
		    buf2 = rawfile.read(scanlinesize)
		    a1 = Numeric.fromstring(buf1, numtype)
		    a2 = Numeric.fromstring(buf2, numtype)
		    if swap:
			a1.byteswapped()
			a2.byteswapped()

		    try:
  		        tmp = correlation(a1.astype(Numeric.Float32), a2.astype(Numeric.Float32))
                    except:
                        # catch 0 division errors
                        gvutils.error('Unable to guess image geometry!')
                        return
                    
		    if tmp > cor_coef:
			cor_coef = tmp
			width = w
			height = h
		w += 1

	self.width_entry.set_text(str(width))
	self.height_entry.set_text(str(height))
Example #51
0
# Prep the individual data files (makes topocentric data)

print "\n\n**** Making topocentric data files...\n\n"

ns = []
epochs = []
for filenum in xrange(len(files)):
    file = files[filenum]
    if (datatype == 'pkmb'):
        (nout, dt, epoch) = pkmb_prepdata(optlist, file, filenum)
    ns.append(nout)
    epochs.append(epoch)
if (numout):
    epochs.append(epochs[0] + numout * dt / 86400.0)
    ns.append(0)
ns = Numeric.asarray(ns)
epochs = Numeric.asarray(epochs)

# Calculate the amount of padding to add after each file

binsneeded = ((epochs[1:] - epochs[:-1]) * 86400.0 / dt + 0.5).astype('i')
padbins = binsneeded - ns[:-1]

# Add padding to the data topocentric files we just wrote

print "\n\n**** Adding padding...\n\n"

for filenum in xrange(len(padbins)):
    outfile = optlist['o'] + ` filenum ` + '.dat'
    if (padbins[filenum] > 0):
        command = 'patchdata ' + ` padbins[
Example #52
0
import gnosis.xml.pickle as xml_pickle
import Numeric, array
import funcs

funcs.set_parser()


class foo:
    pass


f = foo()

f.a = Numeric.array([[1, 2, 3, 4], [5, 6, 7, 8]])
f.b = Numeric.array([1.2, 2.3, 3.4, 4.5])
f.y = array.array('b', [1, 2, 3, 4])
f.z = array.array('f', [1, 2, 3, 4])

a = Numeric.array([6, 7, 8, 9])


def testfoo(o1, o2):
    for attr in ['a', 'b', 'y', 'z', 'l', 'd', 'e']:
        if getattr(o1, attr) != getattr(o2, attr):
            raise "ERROR(1)"


# make sure refs work
f.l = [a, a, a]

f.d = {'One': a, 'Two': Numeric.array([10, 11, 12])}
Example #53
0
 def __init__(self, addressLength, dataLength):
     self.addressDecoder = Neuron(randomBits(addressLength))
     self.counters = Numeric.zeros(dataLength)
 def _test_soomfunc(self, fn, want, *args):
     args = [Numeric.array(a, typecode='l') for a in args]
     result = fn(*args)
     self.assertEqual(result.typecode(), 'l')
     self.assertEqual(list(result), want)
Example #55
0
def main():
    """
    Return desired atomic coordinates
    """
    try:
        num_x_trans = int(sys.argv[1])
        num_y_trans = int(sys.argv[2])
        num_z_trans = int(sys.argv[3])
        basis_type = sys.argv[4]
    except IndexError:
        print '\nusage: ' + sys.argv[
            0] + ' x_trans, y_trans, z_trans, basis_type\n'
        sys.exit(0)

    a = 1.0
    if basis_type == 'hcp':
        a1 = Numeric.array([1.0, 0.0, 0.0]) * a
        a2 = Numeric.array([-0.5, 3**0.5 / 2.0, 0.0]) * a
        a3 = Numeric.array([0.0, 0.0, (8.0 / 3.0)**0.5]) * a
    else:
        a1 = Numeric.array([a, 0.0, 0.0])
        a2 = Numeric.array([0.0, a, 0.0])
        a3 = Numeric.array([0.0, 0.0, a])

    sc = Numeric.array([[0.0, 0.0, 0.0]])
    hcp = Numeric.array([[0.0, 0.0, 0.0]])
    bcc = Numeric.array([[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]])
    fcc = Numeric.array([[0.0, 0.0, 0.0], [0.5, 0.5, 0.0], [0.5, 0.0, 0.5],
                         [0.0, 0.5, 0.5]])
    cI16_JY = Numeric.array([[4.0E-02, 4.0E-02, 4.0E-02],
                             [4.6E-01, 9.6E-01, 5.4E-01],
                             [9.6E-01, 5.4E-01, 4.6E-01],
                             [2.9E-01, 2.9E-01, 2.9E-01],
                             [5.4E-01, 4.6E-01, 9.6E-01],
                             [2.1E-01, 7.1E-01, 7.9E-01],
                             [7.1E-01, 7.9E-01, 2.1E-01],
                             [7.9E-01, 2.1E-01, 7.1E-01],
                             [5.4E-01, 5.4E-01, 5.4E-01],
                             [9.6E-01, 4.6E-01, 4.0E-02],
                             [4.6E-01, 4.0E-02, 9.6E-01],
                             [4.0E-02, 9.6E-01, 4.6E-01],
                             [7.9E-01, 7.9E-01, 7.9E-01],
                             [7.1E-01, 2.1E-01, 2.9E-01],
                             [2.1E-01, 2.9E-01, 7.1E-01],
                             [2.9E-01, 7.1E-01, 2.1E-01]])
    tetragonal_nitrogen = Numeric.array([[0.098, 0.098, 0.0],
                                         [0.902, 0.902, 0.0],
                                         [0.402, 0.598, 0.5],
                                         [0.598, 0.402, 0.5]])
    Nepsilon = Numeric.array([[0.0477444, 0.0394043, 0.949856],
                              [0.952256, 0.960596, 0.0501445],
                              [0.531101, 0.438327, 0.442201],
                              [0.435612, 0.359518, 0.54249],
                              [0.172472, 0.502245, 0.925462],
                              [0.22403, 0.399988, 0.031043],
                              [0.648548, 0.489154, 0.910909],
                              [0.700106, 0.386897, 0.0164902],
                              [0.0960269, 0.157856, 0.472166],
                              [0.970638, 0.227801, 0.589518],
                              [0.0374346, 0.633818, 0.458946],
                              [0.912046, 0.703763, 0.576298],
                              [0.540886, 0.00789884, 0.7523],
                              [0.446018, 0.90098, 0.706547],
                              [0.606758, 0.94395, 0.272419],
                              [0.51189, 0.837031, 0.226665]])
    cgN = Numeric.array([[0.067000, 0.067000, 0.067000],
                         [0.567000, 0.933000, 0.567000],
                         [0.933000, 0.433000, 0.433000],
                         [0.567000, 0.433000, 0.933000],
                         [0.500000, 0.500000, 0.500000],
                         [0.933000, 0.433000, 0.000000],
                         [0.500000, 0.067000, 0.933000],
                         [0.067000, 0.933000, 0.433000]])

    Nchain = Numeric.array([[0.000000, 0.000000, 0.000000],
                            [0.000000, 0.500000, 0.1300000],
                            [0.500000, 0.000000, 0.500000],
                            [0.500000, 0.500000, 0.6300000]])

    #    Nchain = Numeric.array([ [0.000000, 0.000000, 0.000000], [0.000000, 1.275000, 0.680000],
    #                             [1.055000, 0.000000, 2.616500], [1.055000, 1.275000, 3.297000] ])

    basis_atoms = locals()[basis_type]

    bravis_lattice = []

    for i in range(num_x_trans):
        for j in range(num_y_trans):
            for k in range(num_z_trans):
                for l in range(len(basis_atoms)):
                    bravis_lattice.append(i * a1 + j * a2 + k * a3 +
                                          basis_atoms[l])

    filename = 'xred.dat'
    outputFile = open(filename, 'w')

    for triple in bravis_lattice:

        xcart = a / float(num_x_trans) * (triple[0])
        ycart = a / float(num_y_trans) * (triple[1])
        zcart = a / float(num_z_trans) * (triple[2])

        outputFile.write(' % .8f' % xcart + '  % .8f' % ycart +
                         '  % .8f' % zcart + '\n')

    outputFile.close()
Example #56
0
#!/usr/bin/python2.3

import caca
import math
from random import Random
from math import *
import Numeric as N

ret = caca.init()

r = N.zeros(256)
g = N.zeros(256)
b = N.zeros(256)
a = N.zeros(256)

rand = Random()

# Our pixel array
pixels = N.zeros(32*32*4)
#pixels = pixelst.tolist()

for i in range(0,256):
    r[i] = i
    g[i] = i
    b[i] = i
    a[i] = 128

        
bitmap = caca.create_bitmap(32,32,32,32*4,0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000)
#caca.set_bitmap_palette(bitmap, r, g, b, a)
Example #57
0
    cffile.history = '%s: %s' % (datetime.datetime.today(),
                                 string.join(sys.argv))

    num = int(1.1 * options.margin_radius / options.delta + 0.5)
    num = 2 * (num - 1) + 1
    # creating dimensions
    cffile.createDimension('x0', num - 1)
    cffile.createDimension('x1', num)
    cffile.createDimension('y0', num - 1)
    cffile.createDimension('y1', num)
    cffile.createDimension('level', 1)
    cffile.createDimension('time', None)
    #creating variables
    delta = options.delta * 1000.
    varx = cffile.createVariable('x0')
    varx[:] = (delta / 2. + delta * Numeric.arange(num - 1)).astype(
        Numeric.Float32)
    varx = cffile.createVariable('x1')
    varx[:] = (delta * Numeric.arange(num)).astype(Numeric.Float32)

    vary = cffile.createVariable('y0')
    vary[:] = (delta / 2. + delta * Numeric.arange(num - 1)).astype(
        Numeric.Float32)
    vary = cffile.createVariable('y1')
    vary[:] = (delta * Numeric.arange(num)).astype(Numeric.Float32)

    varlevel = cffile.createVariable('level')
    varlevel[0] = 1

    vartime = cffile.createVariable('time')
    vartime[0] = 0
Example #58
0
 def distance(self, otherAddress):
     xor = Numeric.logical_xor(self.address, otherAddress)
     sum = reduce(operator.add, xor)
     return sum
def _maxwellboltzmanndistribution(masses, temp):
    xi = RandomArray.standard_normal(shape=(len(masses), 3))
    momenta = xi * Numeric.sqrt(masses * temp)[:, Numeric.NewAxis]
    return momenta
Example #60
0
import Numeric, os
os.chdir('c:/temp')
data2 = Numeric.array([ [0,54,100], [87,230,5], [161,120,24] ])
data3 = Numeric.array([ [0,100,23], [78,29,1], [134,245,0] ])
print data2
print data3
ndvi = (data3 - data2) / (data3 + data2)
mask = Numeric.greater(data3 + data2, 0)
print mask
ndvi = Numeric.choose(mask, (-99, (data3 - data2) / (data3 + data2)))
data3 = data3.astype(Numeric.Float16)
data2 = data2.astype(Numeric.Float16)
ndvi = Numeric.choose(mask, (-99, (data3 - data2) / (data3 + data2)))
print ndvi
import gdal
from gdalconst import *
driver = gdal.GetDriverByName('HFA')
ds = driver.Create('sample1.img', 3, 3, 1, GDT_Float32)
band = ds.GetRasterBand(1)
band.WriteArray(ndvi, 0, 0)
ds = None
ds = driver.Create('sample2.img', 3, 3, 1, GDT_Float32)
band = ds.GetRasterBand(1)
band.WriteArray(ndvi, 0, 0)
ds = None
ds = driver.Create('sample3.img', 3, 3, 1, GDT_Float32)
band = ds.GetRasterBand(1)
band.WriteArray(ndvi, 0, 0)
band.FlushCache()
band.SetNoDataValue(-99)
band.GetStatistics(0,1)