def __setitem__(self, index, value): """Override built in. This is called when instance is called to assign a value, e.g.: matrix[3, 'A'] = (entry1, entry2)""" if type(index) == types.TupleType: row, colName = index else: raise IndexError("index is not a tuple") if type(value) == types.TupleType: value1, value2 = value elif type(value) == types.StringType: value = value else: raise ValueError("value being assigned is not a tuple") if colName in self.colList: # find the location in order in the array col = self.colList.index(colName) # calculate the offsets to the actual array location col1 = col * 2 col2 = col1 + 1 # store each element in turn self.array[(row,col1+self.extraCount)] = asarray(value1,self._typecode) self.array[(row,col2+self.extraCount)] = asarray(value2,self._typecode) elif colName in self.extraList: col = self.extraList.index(colName) self.array[(row,col)] = asarray(value,self._typecode) else: raise KeyError("can't find %s column" % col)
def __setitem__(self, index, value): """Override built in. This is called when instance is called to assign a value, e.g.: matrix[3, 'A'] = (entry1, entry2)""" if type(index) == types.TupleType: row, colName = index else: raise IndexError("index is not a tuple") if type(value) == types.TupleType: value1, value2 = value elif type(value) == types.StringType: value = value else: raise ValueError("value being assigned is not a tuple") if colName in self.colList: # find the location in order in the array col = self.colList.index(colName) # calculate the offsets to the actual array location col1 = col * 2 col2 = col1 + 1 # store each element in turn self.array[(row, col1 + self.extraCount)] = asarray( value1, self._typecode) self.array[(row, col2 + self.extraCount)] = asarray( value2, self._typecode) elif colName in self.extraList: col = self.extraList.index(colName) self.array[(row, col)] = asarray(value, self._typecode) else: raise KeyError("can't find %s column" % col)
def exercise_generalized_inverse_numpy(): #print 'Numeric' from Numeric import asarray from LinearAlgebra import generalized_inverse m = asarray([[1,1],[0,0]]) n = generalized_inverse(m) #print 'matrix \n',m #print 'inverse\n', n m = asarray([[1,1,1],[0,0,0],[0,0,0]]) n = generalized_inverse(m)
def exercise_generalized_inverse_numpy(): #print 'Numeric' from Numeric import asarray from LinearAlgebra import generalized_inverse m = asarray([[1, 1], [0, 0]]) n = generalized_inverse(m) #print 'matrix \n',m #print 'inverse\n', n m = asarray([[1, 1, 1], [0, 0, 0], [0, 0, 0]]) n = generalized_inverse(m)
def __rmul__(self, other): import copy from Numeric import asarray, matrixmultiply a = copy.copy(self) if asarray(other).shape == (): a.SetBasis(other * self.GetBasis()) elif asarray(other).shape == self.GetBasis().shape: a.SetBasis(matrixmultiply(other, self.GetBasis())) else: raise ValueError, 'matrices are not aligned' return a
def __rmul__(self,other): import copy from Numeric import asarray,matrixmultiply a=copy.copy(self) if asarray(other).shape == (): a.SetBasis(other*self.GetBasis()) elif asarray(other).shape == self.GetBasis().shape: a.SetBasis(matrixmultiply(other,self.GetBasis())) else: raise ValueError, 'matrices are not aligned' return a
def _asarray1d(arr): """Ensure 1d array for one array. """ m = asarray(arr) if len(m.shape)==0: m = reshape(m,(1,)) return m
def iahistogram(f): """ o Purpose Image histogram. o Synopsis h = iahistogram(f) o Input f: o Output h: o Description o Examples f = iaread('woodlog.pgm') iashow(f) h = iahistogram(f) g,d = iaplot(h) g('set data style boxes') g.plot(d) showfig(h) """ from Numeric import asarray,searchsorted,sort,ravel,concatenate,product f = asarray(f) n = searchsorted(sort(ravel(f)), range(max(ravel(f))+1)) n = concatenate([n, [product(f.shape)]]) h = n[1:]-n[:-1] return h
def _asarray1d(arr): """Ensure 1d array for one array. """ m = asarray(arr) if len(m.shape) == 0: m = reshape(m, (1, )) return m
def iaind2sub(dim,i): """ o Purpose Convert linear index to double subscripts. o Synopsis x,y = iaind2sub(dim,i) o Input dim: Dimension. i: Index. o Output x: y: o Description o Examples f = Numeric.array([[0,6,0,2],[4,0,1,8],[0,0,3,0]]) print f i = Numeric.nonzero(Numeric.ravel(f)) (x,y) = iaind2sub(f.shape, i) print x print y print f[x[0],y[0]] print f[x[4],y[4]] """ from Numeric import asarray i = asarray(i) x = i / dim[1] y = i % dim[1] return x,y
def setWidget(self, widget, newValue): """Called by AttributeControl to set our widgets' values to the observed values, to implement refresh(). This is also used during initialization. """ drawingArea = widget.drawingArea color = map(int, tuple(asarray(newValue[:3]) * 65535)) gdkColor = drawingArea.get_colormap().alloc_color(*color) self.setColor(drawingArea, gdkColor, newValue[3])
def TranslateCoordinates(self,translation,type): """Returns a translated grid This method can be used to translate the coordinates of a grid. Two different types of translation exist * 'active' : Translates every grid point according to 'translation' * 'passive' : Translates the origin of the grid according to 'translation' This method only supports a translation vector that matches the grid coordinates and for this reason 'translation' should be specified in terms of these coordinates. """ import ArrayTools from Numeric import asarray from Vector import Vector import copy # finding the output grid translategrid=copy.copy(self) # preparing for translation and calculating origin #trunctranslation=self._GetTruncatedTranslation(translation) if type=='active': translationnumbers=self._GetTranslationNumbers(-asarray(translation)) # origin translategrid.SetOrigin(self.GetOrigin()) elif type=='passive': translationnumbers=self._GetTranslationNumbers(asarray(translation)) # origin transorigin=Vector(space=self.GetOrigin().GetSpace()) transorigin.SetCartesianCoordinates(translategrid.GetSpace().CartesianCoordinatesFromCoordinates(self.CoordinatesFromGridCoordinates(translation))) translategrid.SetOrigin(self.GetOrigin()+transorigin) else: raise ValueError, 'translation type not defined' # finding the output array translatearray=ArrayTools.Translate(self.GetArray(),translationnumbers) translategrid.SetArray(translatearray) return translategrid
def spline(x, y, yp1=None, ypn=None): """y2 = spline(x_vals,y_vals, yp1=None, ypn=None) returns the y2 table for the spline as needed by splint()""" n=len(x) u=zeros(n,Float) y2=zeros(n,Float) x=asarray(x, Float) y=asarray(y, Float) dx=x[1:]-x[:-1] dxi=1.0/dx dx2i=1.0/(x[2:]-x[:-2]) dy=(y[1:]-y[:-1]) siga=dx[:-1]*dx2i dydx=dy*dxi # u[i]=(y[i+1]-y[i])/float(x[i+1]-x[i]) - (y[i]-y[i-1])/float(x[i]-x[i-1]) u[1:-1]=dydx[1:]-dydx[:-1] #this is an incomplete rendering of u... the rest requires recursion in the loop if yp1 is None: y2[0]=u[0]=0.0 else: y2[0]= -0.5 u[0]=(3.0*dxi[0])*(dy[0]*dxi[0] -yp1) for i in range(1,n-1): sig=siga[i-1] p=sig*y2[i-1]+2.0 y2[i]=(sig-1.0)/p u[i]=(6.0*u[i]*dx2i[i-1] - sig*u[i-1])/p if ypn is None: qn=un=0.0 else: qn= 0.5 un=(3.0*dxi[-1])*(ypn- dy[-1]*dxi[-1] ) y2[-1]=(un-qn*u[-2])/(qn*y2[-2]+1.0) for k in range(n-2,-1,-1): y2[k]=y2[k]*y2[k+1]+u[k] return y2
def SetBasis(self, basis): from Numeric import asarray dim = len(basis) v = dim * [0] for i in range(dim): try: v[i] = basis[i].GetCartesianCoordinates() except: v[i] = basis[i] self.Basis = asarray(v)
def MultiplyVector(self,vector,other): """ Multiplies a Vector with a scalar""" import copy from Numeric import asarray v=copy.copy(vector) if asarray(other).shape == (): v.SetCartesianCoordinates(other*vector.GetCartesianCoordinates()) return v else: raise ValueError, 'wrong multiplication of Vector'
def MultiplyVector(self, vector, other): """ Multiplies a Vector with a scalar""" import copy from Numeric import asarray v = copy.copy(vector) if asarray(other).shape == (): v.SetCartesianCoordinates(other * vector.GetCartesianCoordinates()) return v else: raise ValueError, 'wrong multiplication of Vector'
def SetBasis(self,basis): from Numeric import asarray dim=len(basis) v=dim*[0] for i in range(dim): try: v[i]=basis[i].GetCartesianCoordinates() except: v[i]=basis[i] self.Basis=asarray(v)
def SetArray(self,array): """Sets the array This method sets the array. The array should have the shape ( *a1* , *a2*,..., *ai* , *N1* , *N2* ,..., *NN* ) in case of a grid having *i* components in a *N* dimensional space. *Ni* corresponds to the number of values along each axis. Note that even though the array is given in terms of a tuple or a list it will be converted to a NumPy array. """ self.Array=asarray(array)
def validate ( self, object, name, value ): """ Validates that a value is legal for the trait. """ try: # Make sure the value is an array: type_value = type( value ) if type_value is not ArrayType: if type_value not in SequenceTypes: self.error( object, name, self.repr( value ) ) value = asarray( value, self.typecode ) # Make sure the array is of the right type: if ((self.typecode is not None) and (value.typecode() != self.typecode)): if self.coerce: value = value.astype( self.typecode ) else: value = asarray( value, self.typecode ) # If no shape requirements, then return the value: trait_shape = self.shape if trait_shape is None: return value # Else make sure that the value's shape is compatible: value_shape = value.shape if len( trait_shape ) == len( value_shape ): for i, dim in enumerate( value_shape ): item = trait_shape[i] if item is not None: if type( item ) is int: if dim != item: break elif ((dim < item[0]) or ((item[1] is not None) and (dim > item[1]))): break else: return value except: pass self.error( object, name, self.repr( value ) )
def validate(self, object, name, value): """ Validates that a value is legal for the trait. """ try: # Make sure the value is an array: type_value = type(value) if type_value is not ArrayType: if type_value not in SequenceTypes: self.error(object, name, self.repr(value)) value = asarray(value, self.typecode) # Make sure the array is of the right type: if ((self.typecode is not None) and (value.typecode() != self.typecode)): if self.coerce: value = value.astype(self.typecode) else: value = asarray(value, self.typecode) # If no shape requirements, then return the value: trait_shape = self.shape if trait_shape is None: return value # Else make sure that the value's shape is compatible: value_shape = value.shape if len(trait_shape) == len(value_shape): for i, dim in enumerate(value_shape): item = trait_shape[i] if item is not None: if type(item) is int: if dim != item: break elif ((dim < item[0]) or ((item[1] is not None) and (dim > item[1]))): break else: return value except: pass self.error(object, name, self.repr(value))
def ReadFromPositionsScalars(self, positions, scalars): """Reads vtkPolyData from positions and scalars""" # Inserting positions self.pointdata = vtkPointsFromArray(positions) # Inserting scalars #self.scalardata=vtkScalarsFromArray(scalars) self.scalardata = vtkFloatArrayFromNumPyArray( copy.copy(asarray(scalars)[..., NewAxis])) # Inserting positions and scalars in vtkPolyData self.GetvtkPolyData().SetPoints(self.pointdata.GetvtkPoints()) #self.GetvtkPolyData().GetPointData().SetScalars(self.scalardata.GetvtkScalars()) pointdata = self.GetvtkPolyData().GetPointData() pointdata.SetScalars(self.scalardata.GetvtkFloatArray())
def setColor(self, drawingArea, color, alpha): """Accepts a gdkcolor and a floating point alpha, showing their values in the control widgets and setting the attached object attribute to the new color value. """ drawingArea.gdkColor = color drawingArea.modify_bg(gtk.STATE_NORMAL, color) drawingArea.colorTuple = (color.red / 65535, color.green / 65535, color.blue / 65535, alpha) # Show the color in hex, since floating point takes too much space drawingArea.label.set_text("#%02X%02X%02X%02X" % tuple(asarray(drawingArea.colorTuple)*255)) drawingArea.setFunction(drawingArea.colorTuple)
def CoordinateArrayFromUnitVectors(shape, gridunitvectors, origin=[0, 0, 0], indexfunction=lambda i, length: i): """ This method can be used to obtain an array representing the coordinates of a space defined by 'gridunitvecors'. 'gridunitvectors' is in turn a list containing the vectors defining the cells of the grid, i.e. the vectors between neighboring grid points. These vectors are spanned according to the specified shape. 'origin' -- specifies the origin of the returned coordinate array. 'indexfunction' -- is a lambda expression that defines the indices with which each of the specified gridunitvectors are to be multiplied. 'indexfunction' must take two arguments, 'i' and 'length' - default is 'lambda i,length:i'. During exection the input index 'i' will run over the interval 0,1,..., 'length' -1. **An Example** To obtain a coordinate array of shape (10,10) with 'gridunitvectors' =[[2,0],[0,1]] and the origin at [10,0] use: 'CoordinateArrayFromUnitVectors((10,10),[[2,0],[0,1],[10,0])' Note that the output array will be of shape (< *dimension* > , < *spatialcoordinates* >). """ from Numeric import add, fromfunction, array, asarray coordinatelist = [] gridunitvectors = asarray(gridunitvectors) # Looping over the dimensionality of the vectors for dim in range(gridunitvectors.shape[1]): coordinates = origin[dim] # Contribution from each unitvector for nunitvector in range(gridunitvectors.shape[0]): # Finding the indices from which the coordinate grid # is spanned indices = map( lambda i, f=indexfunction, l=shape[nunitvector]: f(i, l), range(shape[nunitvector])) coordinatefunc = lambda i, v=gridunitvectors[nunitvector, dim ]: i * v coordinates = add.outer(coordinates, map(coordinatefunc, indices)) coordinatelist.append(coordinates) return array(coordinatelist)
def get_colours(n): """ Return n pastel colours. """ base = asarray([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) if n <= 3: return base[0:n] # how many new colours to we need to insert between # red and green and between green and blue? needed = (((n - 3) + 1) / 2, (n - 3) / 2) colours = [] for start in (0, 1): for x in linspace(0, 1, needed[start] + 2): colours.append((base[start] * (1.0 - x)) + (base[start + 1] * x)) return [pastel(c) for c in colours[0:n]]
def get_colours(n): """ Return n pastel colours. """ base = asarray([[1,0,0], [0,1,0], [0,0,1]]) if n <= 3: return base[0:n] # how many new colours to we need to insert between # red and green and between green and blue? needed = (((n - 3) + 1) / 2, (n - 3) / 2) colours = [] for start in (0, 1): for x in linspace(0, 1, needed[start]+2): colours.append((base[start] * (1.0 - x)) + (base[start+1] * x)) return [pastel(c) for c in colours[0:n]]
def SetRGBColors(self,colorlist): """Sets the vtkLookupTable This method can be used to change the colortable. 'colorlist' is expected to be a list of colors whose elements is either specified in terms of the RGB colorscale or in terms of the name of a color. A complete list of the recognized colors can be obtained via the method 'GetColorNames' . **An example** To generate a colortable going from red to (0.5000,0.1647,0.1647) to black use: 'SetRGBColors(["red",(0.5000,0.1647,0.1647),"black"])' . """ from Numeric import asarray,Float,array interval=256/(len(colorlist)-1) Ncolors=interval*(len(colorlist)-1) self.SetNumberOfColors(Ncolors) # Translating colors (if any) to r,g,b numbers for i in range(len(colorlist)): if type(colorlist[i]) in [type([]),type(())]: colorlist[i]=asarray(colorlist[i],Float) else: colorlist[i]=array(self.ColorNameToRGB(colorlist[i])) # Finding the difference between adjacent colors # dcolorlist is the steplenght for each color entry dcolorlist=[] for i in range(len(colorlist)-1): dcolorlist.append((colorlist[i+1]-colorlist[i])/interval) # Inserting the colors in the table color=colorlist[0] for loopnumber in range(len(colorlist)-1): for entry in range(loopnumber*interval,(loopnumber+1)*interval): r,g,b=color self.SetTableValue(entry,r,g,b,1.0) color=color+dcolorlist[loopnumber]
def Repeat(self,periods): """Returns a repeated grid This method can be used used to repeat the grid an integer number of times according to the unit cell. Note that the unit cell in the returned grid will also be expanded according to 'periods' . """ from ArrayTools import RepeatArray from Numeric import transpose,asarray a=copy.copy(self) # Finding the new grid valueorder=len(self.GetShape())-len(self.GetSpatialShape()) # Only the spatial coordinates are repeated a.SetArray(RepeatArray(a.GetArray(),valueorder*[1]+periods)) # Finding the new space newspace=copy.copy(self.GetSpace()) newspace.SetBasis(transpose(transpose(self.GetSpace().GetBasis())*asarray(periods))) a.SetSpace(newspace) return a
def pastel(colour, weight=2.4): """ Convert colour into a nice pastel shade""" rgb = asarray(colorConverter.to_rgb(colour)) # scale colour maxc = max(rgb) if maxc < 1.0 and maxc > 0: # scale colour scale = 1.0 / maxc rgb = rgb * scale # now decrease saturation total = sum(rgb) slack = 0 for x in rgb: slack += 1.0 - x # want to increase weight from total to weight # pick x s.t. slack * x == weight - total # x = (weight - total) / slack x = (weight - total) / slack rgb = [c + (x * (1.0 - c)) for c in rgb] return rgb
def pastel(colour, weight=2.4): """ Convert colour into a nice pastel shade""" rgb = asarray(colorConverter.to_rgb(colour)) # scale colour maxc = max(rgb) if maxc < 1.0 and maxc > 0: # scale colour scale = 1.0 / maxc rgb = rgb * scale # now decrease saturation total = sum(rgb) slack = 0 for x in rgb: slack += 1.0 - x # want to increase weight from total to weight # pick x s.t. slack * x == weight - total # x = (weight - total) / slack x = (weight - total) / slack rgb = [c + (x * (1.0-c)) for c in rgb] return rgb
def Map(function, array, coordinates): """Return a mapped array This method can be used to map an array along with the coordinates corresponding to each grid point. The arrangement of the arguments in the input function is expected to be of the form 'function(' *arrayvalue* , *coordinate* ')' where *coordinate* is a NumPy array having a length correspoding to the dimension. """ from Numeric import reshape, swapaxes, asarray # Finding the dimension of the array dim = coordinates.shape[0] spatialshape = array.shape[-dim:] # Reshaping array shape=(indices,) flatarray = reshape(array, (array.shape[:-dim] + (-1, ))) # Reshaping coordinates (indices,dim) flatcoordinates = swapaxes(reshape(coordinates, (dim, -1)), 0, 1) maparray = asarray(map(function, flatarray, flatcoordinates)) # Reshaping back again return reshape(maparray, spatialshape)
def CoordinatesFromCartesianCoordinates(self,coordinates): from LinearAlgebra import solve_linear_equations return solve_linear_equations(transpose(self.GetBasis()),asarray(coordinates))
def iaconv(f,h): """ o Purpose 2D convolution. modified by drewp to build a result array of the same typecode as 'f', which makes this work on complex arrays. o Synopsis g = iaconv(f,h) o Input f: input image. h: PSF (point spread function), or kernel. The origin is at the array center. o Output g: o Description Perform a 2D discrete convolution. The kernel origin is at the center of image h. o Examples import Numeric f = Numeric.zeros((5,5)) f[2,2] = 1 print f h = Numeric.array([[1,2,3],[4,5,6]]) print h a = iaconv(f,h) print a f = Numeric.array([[1,0,0,0],[0,0,0,0]]) print f h = Numeric.array([1,2,3]) print h a = iaconv(f,h) print a f = Numeric.array([[1,0,0,0,0,0],[0,0,0,0,0,0]]) print f h = Numeric.array([1,2,3,4]) print h a = iaconv(f,h) print a f = iaread('cameraman.pgm') h = [[1,2,1],[0,0,0],[-1,-2,-1]] g = iaconv(f,h) gn = ianormalize(g, [0,255]) iashow(gn) """ from Numeric import asarray,NewAxis,zeros,array,product f, h = asarray(f), asarray(h) if len(f.shape) == 1: f = f[NewAxis,:] if len(h.shape) == 1: h = h[NewAxis,:] if product(f.shape) < product(h.shape): f, h = h, f g = zeros(array(f.shape) + array(h.shape) - 1,f.typecode()) for i in range(h.shape[0]): for j in range(h.shape[1]): g[i:i+f.shape[0], j:j+f.shape[1]] += h[i,j] * f return g
def CoordinatesFromCartesianCoordinates(self,coor): """ Returns the Cartesian coordinates (i.e 'coordinates')""" return asarray(coor)
def ReadFromArray(self, array): """Reads vtkScalars from array""" # The array is copied to make it contiguous self.scalardata = vtkFloatArrayFromNumPyArray( copy.copy(asarray(array)[..., NewAxis])) self.GetvtkScalars().SetScalars(self.scalardata.GetvtkFloatArray())
def closeto(x,y): try: assert(abs(asarray(x)-asarray(y))<1e-10) except AssertionError: raise AssertionError('Failed: %s and %s not close' %(x,y))
def CoordinatesFromCartesianCoordinates(self, coor): """ Returns the Cartesian coordinates (i.e 'coordinates')""" return asarray(coor)
def CartesianCoordinatesFromCoordinates(self,coordinates): return dot(asarray(coordinates),self.GetBasis())
def CartesianCoordinatesFromCoordinates(self, coordinates): return dot(asarray(coordinates), self.GetBasis())
def SeqToProfile(seq, alphabet=None, char_order=None,\ split_degenerates=False): """Generates a Profile object from a Sequence object. seq: Sequence object alphabet (optional): Alphabet object (if you want to split degenerate symbols, the alphabet object should have a Degenerates property. Default is the Alphabet associated with the Sequence object. char_order (optional): The order the characters occur in the Profile. Default is the list(alphabet) split_degenerates (optional): Whether you want the counts for the degenerate symbols to be divided over the non-degenerate symbols they code for. A Profile is a position x character matrix describing which characters occur at each position. In a sequence (as opposed to an alignment) only one character occurs at each position. In general a sequence profile will only contain ones and zeros. However, you have the possibility of splitting degenerate characters. For example, if a position is R, it means that you have 50/50% chance of A and G. It's also possible to ignore characters, which in a sequence profile will lead to positions (rows) containing only zeros. Example: Sequence = ACGU Profile(seq, CharOrder=UCAG): U C A G 0 0 1 0 first pos 0 1 0 0 second pos 0 0 0 1 third pos 1 0 0 0 fourth pos Sequence= GURY Profile(seq,CharOrder=UCAG, split_degenerates=True) U C A G 0 0 0 1 first pos 1 0 0 0 second pos 0 0 .5 .5 third pos .5 .5 0 0 fourth pos Characters can also be ignored Sequence = ACN- Profile(seq, CharOrder=UCAGN, split_degenerates=True) U C A G 0 0 1 0 first pos 0 1 0 0 second pos .25 .25 .25 .25 third pos 0 0 0 0 fourth pos <--contains only zeros """ if alphabet is None: alphabet = seq.Alphabet if char_order is None: char_order = list(alphabet) #Determine the meaning of each character based on the alphabet, the #character order, and the option to split degenerates char_meaning = CharMeaningProfile(alphabet, char_order,\ split_degenerates) #construct profile data result_data = take(char_meaning.Data, asarray(seq.upper(), UInt8)) return Profile(result_data, alphabet, char_order)
def SetCoordinates(self,coordinates): """Sets the coordinates of the vector in the basis of the 'VectorSpace'.""" self.Coordinates=asarray(coordinates)
def SetCoordinates(self, coordinates): """Sets the coordinates of the vector in the basis of the 'VectorSpace'.""" self.Coordinates = asarray(coordinates)
def closeto(x, y): try: assert (abs(asarray(x) - asarray(y)) < 1e-10) except AssertionError: raise AssertionError('Failed: %s and %s not close' % (x, y))
def ReadFromArray(self, array): """Read vtkPoints from array""" self.pointdata = vtkFloatArrayFromNumPyArray(asarray(array)) self.GetvtkPoints().SetData(self.pointdata.GetvtkFloatArray())
def CoordinatesFromCartesianCoordinates(self, coordinates): from LinearAlgebra import solve_linear_equations return solve_linear_equations(transpose(self.GetBasis()), asarray(coordinates))
def CoordinatesFromGridCoordinates(self,gridcoor): """Returns a list containing the scaled coordinates """ from Numeric import Float return list(asarray(gridcoor,Float)/self.GetSpatialShape())
def AlnToProfile(aln, alphabet=None, char_order=None, split_degenerates=False,\ weights=None): """Generates a Profile object from an Alignment. aln: Alignment object alphabet (optional): an Alphabet object (or list of chars, but if you want to split degenerate symbols, the alphabet must have a Degenerates property. Default is the alphabet of the first seq in the alignment. char_order (optional): order of the characters in the profile. Default is list(alphabet) split_degenerates (optional): Whether you want the counts for the degenerate symbols to be divided over the non-degenerate symbols they code for. weights (optional): dictionary of seq_id: weight. If not entered all seqs are weighted equally A Profile is a position x character matrix describing which characters occur at each position of an alignment. The Profile is always normalized, so it gives the probabilities of each character at each position. Ignoring chars: you can ignore characters in the alignment by not putting the char in the CharOrder. If you ignore all characters at a particular position, an error will be raised, because the profile can't be normalized. Splitting degenerates: you can split degenerate characters over the non-degenerate characters they code for. For example: R = A or G. So, an R at a position counts for 0.5 A and 0.5 G. Example: seq1 TCAG weight: 0.5 seq2 TAR- weight: 0.25 seq3 YAG- weight: 0.25 Profile(aln,alphabet=DnaAlphabet,char_order="TACG",weights=w, split_degenerates=True) Profile: T A C G [[ 0.875 0. 0.125 0. ] [ 0. 0.5 0.5 0. ] [ 0. 0.625 0. 0.375] [ 0. 0. 0. 1. ]] """ if alphabet is None: alphabet = aln.values()[0].Alphabet if char_order is None: char_order = list(alphabet) if weights is None: weights = dict.fromkeys(aln.keys(),1/len(aln)) char_meaning = CharMeaningProfile(alphabet, char_order,\ split_degenerates) profiles = [] for k,v in aln.items(): profiles.append(take(char_meaning.Data, asarray(v.upper(), UInt8))\ * weights[k]) s = reduce(add,profiles) result = Profile(s,alphabet, char_order) try: result.normalizePositions() except: raise ValueError,\ "Probably one of the rows in your profile adds up to zero,\n "+\ "because you are ignoring all of the characters in the "+\ "corresponding\n column in the alignment" return result
def iagaussian(s,mu,sigma): """ o Purpose Generate a 2D Gaussian image. o Synopsis g = iagaussian(s,mu,sigma) o Input s: [rows columns] mu: Mean vector. 2D point (x;y). Point of maximum value. sigma: covariance matrix (square). [ Sx^2 Sxy; Syx Sy^2] o Output g: o Description A 2D Gaussian image is an image with a Gaussian distribution. It can be used to generate test patterns or Gaussian filters both for spatial and frequency domain. The integral of the gaussian function is 1.0. o Examples import Numeric f = iagaussian([8,4], [3,1], [[1,0],[0,1]]) print Numeric.array2string(f, precision=4, suppress_small=1) g = ianormalize(f, [0,255]).astype(Numeric.UnsignedInt8) print g f = iagaussian(100, 50, 10*10) g = ianormalize(f, [0,1]) g,d = iaplot(g) showfig(g) f = iagaussian([50,50], [25,10], [[10*10,0],[0,20*20]]) g = ianormalize(f, [0,255]).astype(Numeric.UnsignedInt8) iashow(g) """ from Numeric import asarray,product,arange,NewAxis,transpose,matrixmultiply,reshape,concatenate,resize,sum,zeros,Float,ravel,pi,sqrt,exp from LinearAlgebra import inverse,determinant if type(sigma).__name__ in ['int', 'float', 'complex']: sigma = [sigma] s, mu, sigma = asarray(s), asarray(mu), asarray(sigma) if (product(s) == max(s)): x = arange(product(s)) d = x - mu if len(d.shape) == 1: tmp1 = d[:,NewAxis] tmp3 = d else: tmp1 = transpose(d) tmp3 = tmp1 if len(sigma) == 1: tmp2 = 1./sigma else: tmp2 = inverse(sigma) k = matrixmultiply(tmp1, tmp2) * tmp3 else: aux = arange(product(s)) x, y = iaind2sub(s, aux) xx = reshape(concatenate((x,y)), (2, product(x.shape))) d = transpose(xx) - resize(reshape(mu,(len(mu),1)), (s[0]*s[1],len(mu))) if len(sigma) == 1: tmp = 1./sigma else: tmp = inverse(sigma) k = matrixmultiply(d, tmp) * d k = sum(transpose(k)) g = zeros(s, Float) aux = ravel(g) if len(sigma) == 1: tmp = sigma else: tmp = determinant(sigma) aux[:] = 1./(2*pi*sqrt(tmp)) * exp(-1./2 * k) return g