Example #1
0
    def __init__(self, contpts, contnorm, vertDup=0, firstDup=0):
        """
        contpts   : list of 3D coordinates of the control points describing the
                    shape2D.
        contnorm  : list of 3D vector specifying the normals at each vertex
                    of the shape2D.
        vertDup   : Flag specifying whether or not to duplicate each vertex and
                    normal.
        firstDup  : Flag specifying whether or not to duplicate the first
                    first vertex.
        """
        self.vertDup = vertDup
        self.firstDup = firstDup
        self.contpts = list(contpts)
        self.contnorm = list(contnorm)
        if vertDup:
            firstDupInd = 2
        else:
            firstDupInd = 1

        if firstDup:
            cont = self.contpts
            newcont = cont + cont[:firstDupInd]
            self.contpts = Numeric.array(newcont)

            contn = self.contnorm
            newcontn = contn + contn[:firstDupInd]
            self.contnorm = Numeric.array(newcontn)
            
        self.lenShape = len(self.contpts)
Example #2
0
    def test_getSliceArray(self):

        assert hasattr(UTisocontour, 'getSliceArray')
        isovar=0
        timestep=0
        axis='x'
        sliceNum=10
        step=1
        sh = (1,1, self.auC.NELEMENTS[0], self.auC.NELEMENTS[1], self.auC.NELEMENTS[2])
        da = Numeric.zeros(sh).astype('f')
        da[0][0] = Numeric.array( Numeric.reshape( Numeric.swapaxes( self.auC.array, 0, 2), self.auC.NELEMENTS ) ).astype('f')
        daSmall = Numeric.array(da[:,:,::step,::step,::step]).astype('f')
        center = Numeric.array(self.auC.CENTER).astype('f')
        dim = Numeric.array(self.auC.NELEMENTS).astype('f')
        span = Numeric.array(self.auC.SPACING).astype('f')
        print("span:", span)
        orig = center - ((dim-1)/2)*span
        print("orig: ", orig)
        the_data = UTisocontour.newDatasetRegFloat3D(daSmall,
                                        orig.astype('f'), (span*step,)*3 )
        #the_data = UTisocontour.newDatasetRegFloat3D(daSmall)

        sld = UTisocontour.getSliceArray(the_data, isovar,
                                       timestep, axis, sliceNum)
        print('sld.shape' ,sld.shape)
        assert sld.shape == (61, 41)
 def getFaces(self, faceDescr):
     ################################################################
     # This function parses the face description and creates an array
     # of faces.
     # If the first line starts by a # then the 3 following are comments
     # lines
     # Comment #1: Comment + filename of the sphere set
     # Comment #2: Comment on content of comment #3
     # Comment #3: Nb triangles, nb of spheres, triangulation density,
     #             probe sphere radius.
     # vertInd1, vertInd2, vertInd3, Flag, FaceInd
     #
     # All the indices are 1 based !!!
     ################################################################
     # faceComments are all the lines with a # in front and the line after
     if faceDescr[0][0]=='#':
         facesComments = faceDescr[:3]
         facesLines = faceDescr[3:]
     else:
         facesLines = faceDescr
         facesComments = []
     facesInfo = map(lambda x: x.split(), facesLines)
     self.faces = Numeric.array(map(lambda x: [int(x[0])-1, int(x[1])-1,
                                               int(x[2])-1],
                                    facesInfo)).astype('i')
     self.facesProp = Numeric.array(
         map(lambda x: [int(x[3]), int(x[4])], facesInfo)).astype('i')
 def getVert(self, vertDescr):
     ################################################################
     # This function parses the vertices description and creates an array
     # of vertices.
     # Comment #1: Comment + filename of the sphere set
     # Comment #2: Comment on content of comment #3
     # Comment #3: Nb triangles, nb of spheres, triangulation density,
     #             probe sphere radius.
     # x y z nx ny nz fInd sphInd flag AtmName
     #
     # All the indices are 1 based !!!
     ################################################################
     if vertDescr[0][0]=='#':
         vertComments = vertDescr[:3]
         vertLines = vertDescr[3:]
     else:
         vertComments = []
         vertLines = vertDescr
     vertInfo = map(lambda x: x.split(), vertLines)
     self.vertices = Numeric.array(
         map(lambda x: [float(x[0]), float(x[1]), float(x[2])],
             vertInfo)).astype('f')
     self.normals = Numeric.array(map(
         lambda x: [float(x[3]), float(x[4]), float(x[5])], vertInfo)
                                  ).astype('f')
     self.vertProp = Numeric.array(map(
         lambda x: [int(x[6]), int(x[7]), int(x[8])], vertInfo)).astype('i')
Example #5
0
def histogram(data, nbins, range = None):
    """
    Comes from Konrad Hinsen: Scientific Python
    """
    
    data = Numeric.array(data, Numeric.Float)
    
    if range is None:
        min = Numeric.minimum.reduce(data)
        max = Numeric.maximum.reduce(data)
    else:
        min, max = range
        data = Numeric.repeat(data,
                  Numeric.logical_and(Numeric.less_equal(data, max),
                          Numeric.greater_equal(data,
                                    min)))
    # end if
    bin_width = (max-min)/nbins
    
    data = Numeric.floor((data - min)/bin_width).astype(Numeric.Int)
    histo = Numeric.add.reduce(Numeric.equal(
    Numeric.arange(nbins)[:,Numeric.NewAxis], data), -1)
    histo[-1] = histo[-1] + Numeric.add.reduce(Numeric.equal(nbins, data))
    bins = min + bin_width*(Numeric.arange(nbins)+0.5)
    return Numeric.transpose(Numeric.array([bins, histo]))
Example #6
0
def matrix_hsv_to_rgb(hMapArray,sMapArray,vMapArray):
    """
    First matrix sets the Hue (Color).
    Second marix sets the Sauration (How much color)
    Third matrix sets the Value (How bright the pixel will be)

    The three input matrices should all be the same size, and have
    been normalized to 1.  There should be no side-effects on the
    original input matrices.
    """

    shape = hMapArray.shape
    rmat = array(hMapArray,Float)
    gmat = array(sMapArray,Float)
    bmat = array(vMapArray,Float)

    ## This code should never be seen.  It means that calling code did
    ## not take the precaution of clipping the input matrices.
    if max(rmat.ravel()) > 1 or max(gmat.ravel()) > 1 or max(bmat.ravel()) > 1:
        param.Parameterized().warning('HSVBitmap inputs exceed 1. Clipping to 1.0')
        if max(rmat.ravel()) > 0: rmat = clip(rmat,0.0,1.0)
        if max(gmat.ravel()) > 0: gmat = clip(gmat,0.0,1.0)
        if max(bmat.ravel()) > 0: bmat = clip(bmat,0.0,1.0)

    # List comprehensions were not used because they were slower.
    for j in range(shape[0]):
        for i in range(shape[1]):
            rgb = hsv_to_rgb(rmat[j,i],gmat[j,i],bmat[j,i])
            rmat[j,i] = rgb[0]
            gmat[j,i] = rgb[1]
            bmat[j,i] = rgb[2]

    return (rmat, gmat, bmat)
    def firstDerivative(self):
        fstDeriveV = Numeric.array([ [-0.125,  -0.25, -0.125],
                                     [ 0.0  ,    0.0,  0.0  ],
                                     [ 0.125,   0.25,  0.125] ], 'f')

        self.redraw(filter=fstDeriveV)
        derivV = self.imageAsArray()
        if derivV is None:
            return None
        fstDeriveV = Numeric.array([ [ 0.125,   0.25,  0.125],
                                     [ 0.0  ,    0.0,  0.0  ],
                                     [-0.125,  -0.25, -0.125] ], 'f')

        self.redraw(filter=fstDeriveV)
        derivV += self.imageAsArray()

        fstDeriveH = Numeric.array([ [-0.125,    0.0, 0.125],
                                     [-0.25 ,    0.0, 0.25  ],
                                     [-0.125,    0.0, 0.125] ], 'f')
        self.redraw(filter=fstDeriveH)
        derivH = self.imageAsArray()

        fstDeriveH = Numeric.array([ [ 0.125,    0.0, -0.125],
                                     [ 0.25 ,    0.0, -0.25  ],
                                     [ 0.125,    0.0, -0.125] ], 'f')
        self.redraw(filter=fstDeriveH)
        derivH += self.imageAsArray()

        deriv = Numeric.fabs(derivH*0.5)+Numeric.fabs(derivV*0.5)

        return deriv.astype('B')
Example #8
0
 def setup_ligand(self, lig_lines):
     lig_coords = []
     first_lig = False
     if not hasattr(self, 'lig_vdw_rad'):
         self.lig_vdw_rad = []
         first_lig = True
     for ll in lig_lines:
         #THESE LINES START WITH 'DOCKED: ' so indices +8
         if ll.find("HETATM")>-1 or ll.find("ATOM")>-1:
             lig_coords.append([float(ll[38:46]), float(ll[46:54]),float(ll[54:62])])
             #lig_coords.append([float(ll[30:38]), float(ll[38:46]),float(ll[46:54])])
             if first_lig: 
                 #indices  +8
                 be_key = strip(ll[84:])
                 if be_key=='A':
                     be_key = 'C'
                 elif be_key=='OA':
                     be_key = 'O'
                 elif be_key=='NA':
                     be_key = 'N'
                 elif be_key=='SA':
                     be_key = 'S'
                 elif be_key=='HD':
                     be_key = 'H'
                 self.lig_vdw_rad.append(self.babel_elements[be_key]['vdw_rad'])
     self.lig_coords = lig_coords
     self.smallM = Numeric.array(lig_coords, 'f')
     #setup variables for ligand arrays
     if first_lig:
         self.lenK=len(lig_coords)
         self.keyRadii = Numeric.array(self.lig_vdw_rad, 'f')
         self.keyRadii.shape = (self.lenK,1)
     self.smallM.shape = (self.lenK,1,3)
    def Set(self, check=1, redo=1, updateOwnGui=True, **kw):
        """set data for this object:
check=1 : verify that all the keywords present can be handle by this func 
redo=1 : append self to viewer.objectsNeedingRedo
updateOwnGui=True : allow to update owngui at the end this func
"""
        if kw.has_key('materials') and kw['materials'] is not None:
            materials = Numeric.array((kw['materials']),'f')
        else:
            materials = Numeric.array(((0.,0.,1.,1.),),'f')

        redoFlags = apply( Triangle_strip.Set, (self, check, 0), kw )

        nm = kw.get( 'normalStyle')
        # nm can be TUBE_NORM_FACET, TUBE_NORM_EDGE, TUBE_NORM_PATH_EDGE
        if nm:
            self.normalStyle = self.normalStyle & ~gle.TUBE_NORM_MASK
            self.normalStyle = self.normalStyle | nm
            gle.gleSetJoinStyle (self.normalStyle | self.joinStyle)

        ja = kw.get( 'joinStyle')
        # ja can be TUBE_JN_RAW, TUBE_JN_ANGLE, TUBE_JN_CUT, TUBE_JN_ROUND,
        #           TUBE_JN_CAP 
        if ja:
            self.joinStyle = self.joinStyle & ~gle.TUBE_JN_MASK
            self.joinStyle = self.joinStyle | ja
            gle.gleSetJoinStyle (self.normalStyle | self.joinStyle)

        return self.redoNow(redo, updateOwnGui, redoFlags)
    def SetMaterial(self, values, prop=1, tagModified=True):
	"""Set the materials
WARNING: when back face colors are set, two sided lighting has to be enabled
        
we set RGB values for all properties except for shininess and opacity
If an alpha value are specified they will be ignored
Since IndexedGeomDSPL requires alpha values for all properties
we set them automatically to 1.0 for all properties except for
diffuse. The alpha channel of the diffuse component will be set later
in fixOpacity which should be called after all properties of the
material have been updated.
"""
        if tagModified:
            self._modified = True

        if prop is None: prop = self.diff
        elif type(prop) is types.StringType:
            prop = getattr(self, prop)

        assert prop in (0,1,2,3,4,5)

        values = array( values, 'f' )
	if prop < self.shini:
            assert len(values.shape)==2 and values.shape[1] in [3,4]
            alpha = ones( (values.shape[0], 1), 'f' )
            values = concatenate( (values[:,:3], alpha), 1 )
        else:
            if len(values.shape) != 1:
                values = array([values], 'f' )
            
        self.prop[prop] = values
    def Set(self, check=1, redo=1, updateOwnGui=True, **kw):
        """set data for this object
check=1 : verify that all the keywords present can be handle by this func 
redo=1 : append self to viewer.objectsNeedingRedo
updateOwnGui=True : allow to update owngui at the end this func
"""
        redoFlags = apply( GleExtrude.Set, (self, check, 0), kw)

        if kw.has_key('materials') and kw['materials'] is not None:
            materials = Numeric.array((kw['materials']),'f')
        else:
            materials = Numeric.array(((0.,0.,1.,1.),),'f')
        self.trace3D = kw.get('trace3D')
        if not self.trace3D:
            v,n,s = (None,None,None)
            redoFlags |= self._redoFlags['redoDisplayListFlag']
        else:
            v,n,s = self.extrude()
            redoFlags |= self._redoFlags['redoDisplayListFlag']
        if v is not None:
            kw['vertices']=v
        if n is not None:
            kw['vnormals']=n
        if s is not None:
            kw['stripBegin']=[0] + list( s[:,0] )
            
        return self.redoNow(redo, updateOwnGui, redoFlags)
    def extrude(self):
        """Virtual Method to do the extrusion along a 3D path with a 2D shape
        using the gle extrusion. We then get the geometry information
        using the extrusion method in Feedback mode. This will then be
        used to build a triangle strip."""
        
        from gle import glec
        gle.gleSetJoinStyle ( self.normalStyle | self.joinStyle )
        glec.gleFeedBack()

        contpts = Numeric.array(self.shape2D.contpts)
        contourPoints = contpts[:,:2]
        contnorm = Numeric.array(self.shape2D.contnorm)
        contourNormals = contnorm[:,:2]
        
        gle.gleExtrusion(contourPoints, contourNormals,
                         self.contourUp,
                         self.trace3D,
                         self.materials[1028].prop[0][:,:3] )

        glec.gleTextureMode(0)
        v,n,s = glec.gleGetTriangleMesh()

        vinv = Numeric.zeros( v.shape, 'd')
        vinv[::2] = v[1::2]
        vinv[1::2] = v[::2]

        ninv = Numeric.zeros( n.shape, 'd')
        ninv[::2] = n[1::2]
        ninv[1::2] = n[::2]

        return vinv, ninv, s
 def _drawLegend(self,dc,graphics,rhsW,topH,legendBoxWH, legendSymExt, legendTextExt):
     """Draws legend symbols and text"""
     # top right hand corner of graph box is ref corner
     trhc= self.plotbox_origin+ (self.plotbox_size-[rhsW,topH])*[1,-1]
     legendLHS= .091* legendBoxWH[0]  # border space between legend sym and graph box
     lineHeight= max(legendSymExt[1], legendTextExt[1]) * 1.1 #1.1 used as space between lines
     dc.SetFont(self._getFont(self._fontSizeLegend))
     for i in range(len(graphics)):
         o = graphics[i]
         s= i*lineHeight
         if isinstance(o,PolyMarker):
             # draw marker with legend
             pnt= (trhc[0]+legendLHS+legendSymExt[0]/2., trhc[1]+s+lineHeight/2.)
             o.draw(dc, self.printerScale, coord= _Numeric.array([pnt]))
         elif isinstance(o,PolyLine):
             # draw line with legend
             pnt1= (trhc[0]+legendLHS, trhc[1]+s+lineHeight/2.)
             pnt2= (trhc[0]+legendLHS+legendSymExt[0], trhc[1]+s+lineHeight/2.)
             o.draw(dc, self.printerScale, coord= _Numeric.array([pnt1,pnt2]))
         else:
             raise TypeError, "object is neither PolyMarker or PolyLine instance"
         # draw legend txt
         pnt= (trhc[0]+legendLHS+legendSymExt[0], trhc[1]+s+lineHeight/2.-legendTextExt[1]/2)
         dc.DrawText(o.getLegend(),pnt[0],pnt[1])
     dc.SetFont(self._getFont(self._fontSizeAxis)) # reset
Example #14
0
def histogram(data, nbins, range = None):
    """
    Create a histogram.
    Comes from Konrad Hinsen: Scientific Python

    @param data: data list or array
    @type  data: [any]
    @param nbins: number of bins
    @type  nbins: int
    @param range: data range to create histogram from (min val, max val)
    @type  range: (float, float) OR None

    @return: array (2 x len(data) ) with start of bin and witdh of bin. 
    @rtype: array
    """
    data = Numeric.array(data, Numeric.Float)
    if range is None:
        min = Numeric.minimum.reduce(data)
        max = Numeric.maximum.reduce(data)
    else:
        min, max = range
        data = Numeric.repeat(data,
                              Numeric.logical_and(Numeric.less_equal(data, max),
                                                  Numeric.greater_equal(data, min)))
    bin_width = (max-min)/nbins
    data = Numeric.floor((data - min)/bin_width).astype(Numeric.Int)
    histo = Numeric.add.reduce(Numeric.equal(
        Numeric.arange(nbins)[:,Numeric.NewAxis], data), -1)
    histo[-1] = histo[-1] + Numeric.add.reduce(Numeric.equal(nbins, data))
    bins = min + bin_width*(Numeric.arange(nbins)+0.5)
    return Numeric.transpose(Numeric.array([bins, histo]))
def Map(values, colorMap, mini=None, maxi=None):
    """Get colors corresponding to values in a colormap"""

    values = Numeric.array(values)
    if len(values.shape)==2 and values.shape[1]==1:
	values.shape = ( values.shape[0], )
    elif len(values.shape) > 1:
	print 'ERROR: values array has bad shape'
	return None

    cmap = Numeric.array(colorMap)
    if len(cmap.shape) !=2 or cmap.shape[1] not in (3,4):
	print 'ERROR: colorMap array has bad shape'
	return None

    if mini is None: mini = min(values)
    else: values = Numeric.maximum(values, mini)
    if maxi is None: maxi = max(values)
    else: values = Numeric.minimum(values, maxi)
    valrange = maxi-mini
    if valrange < 0.0001:
	ind = Numeric.ones( values.shape )
    else:
	colrange = cmap.shape[0]-1
	ind = ((values-mini) * colrange) / valrange
    col = Numeric.take(colorMap, ind.astype(viewerConst.IPRECISION))
    return col
Example #16
0
    def __call__(self,fullmatrix,simple_sheet_name=None,complex_sheet_name=None,bins=frange(0,2.0,0.1,inclusive=True),**params):
        p=ParamOverrides(self,params)

        from topo.analysis.vision import complexity
        if (topo.sim.objects().has_key(simple_sheet_name) and topo.sim.objects().has_key(complex_sheet_name)):
            v1s = complexity(fullmatrix[topo.sim[simple_sheet_name]]).flatten()
            v1c = complexity(fullmatrix[topo.sim[complex_sheet_name]]).flatten()
            #double the number of complex cells to reflect large width of layer 2/3
            v1c = numpy.concatenate((array(v1c),array(v1c)),axis=1)
            pylab.figure()
            n = pylab.subplot(311)
            pylab.hist(v1s,bins)
            pylab.axis([0,2.0,0,4100])
	    n.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(3))

	    n = pylab.subplot(312)
            pylab.hist(v1c,bins)
            pylab.axis([0,2.0,0,4100])
	    n.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(3))

	    n = pylab.subplot(313)
            pylab.hist(numpy.concatenate((array(v1s),array(v1c)),axis=1),bins)
            pylab.axis([0,2.0,0,4100])
	    n.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(3))

        self._generate_figure(p)
Example #17
0
    def applyStateOld(self, state):
        """
        """
        q = state.quaternion
        t = Numeric.array(state.translation)
        o = Numeric.array(state.origin)

        # center the coordinates
##          self.resultCoords = (self.resultCoords -
##                               Numeric.array([o[0], o[1], o[2], 0.0]))

        # center the coordinates (node-by-node)
        def __center(node, o): node.coords = node.coords - o
        root = self.torTree.rootNode
        root.pre_traverse(__center, root, Numeric.array([o[0], o[1], o[2], 0.0]))

        # construct rootNode transformation matrix
        mtx = Transformation(t+o, q).getMatrix(transpose=1)

        # apply the torsions
        coords = self.applyAngList(state.torsions, mtx)

        # must "reset" each nodes coords
        def __uncenter(node, o): node.coords = node.coords + o
        root.pre_traverse(__uncenter, root, Numeric.array([o[0], o[1], o[2], 0.0]))

        return coords
def blurCoordsRadii(coords, radii, blobbyness=-0.1, res=0.5,
                    weights=None, dims=None, padding = 0.0):
    """blur a set of coordinates with radii
"""
    # Setup grid
    resX = resY = resZ = res
    if not dims:
        minb, maxb = blur.getBoundingBox(coords, radii, blobbyness, padding)
        Xdim = int(round( (maxb[0] - minb[0])/resX + 1))
        Ydim = int(round( (maxb[1] - minb[1])/resY + 1))
        Zdim = int(round( (maxb[2] - minb[2])/resZ + 1))
    else:
        Xdim, Ydim, Zdim = dims
    print "Xdim = %d, Ydim =%d, Zdim = %d"%(Xdim, Ydim, Zdim)
    # Generate blur map
    volarr, origin, span = blur.generateBlurmap(
        coords, radii, [Xdim, Ydim, Zdim], blobbyness, weights=weights, padding=padding)
    # Take data from blur map 
    volarr.shape = [Zdim, Ydim, Xdim]
    volarr = Numeric.transpose(volarr).astype('f')
    origin = Numeric.array(origin).astype('f')
    stepsize = Numeric.array(span).astype('f')
    arrayf = Numeric.reshape( Numeric.transpose(volarr),
                              (1, 1)+tuple(volarr.shape) )
    # Return data
    return arrayf, origin, stepsize
Example #19
0
    def __applyTorsion(self, node, parent_mtx):
        """Transform the subtree rooted at node.

        The new torsion angle must be pre-set.
        Children of the node are transformed recursively.
        """
        # get rotation matrix for node
        # my_mtx = self.rotax(node)
        mtx = rotax( Numeric.array(node.a.coords),
                     Numeric.array(node.b.coords),
                     node.angle * self.rads_per_degree, transpose=1)

        # node_mtx = Numeric.dot(parent_mtx, mtx)
        node_mtx = self.mult4_3Mat(parent_mtx, mtx)

        # set-up for the transformation
        mm11 = node_mtx[0][0]; mm12 = node_mtx[0][1]; mm13 = node_mtx[0][2]
        mm21 = node_mtx[1][0]; mm22 = node_mtx[1][1]; mm23 = node_mtx[1][2]
        mm31 = node_mtx[2][0]; mm32 = node_mtx[2][1]; mm33 = node_mtx[2][2]
        mm41 = node_mtx[3][0]; mm42 = node_mtx[3][1]; mm43 = node_mtx[3][2]
        atomSet = node.atomSet        
        # transform the coordinates for the node
        for i in node.atomRange:
            x,y,z = node.coords[i][:3] # get origin-subtracted originals
            c = atomSet[i].coords
            c[0] = x*mm11 + y*mm21 + z*mm31 + mm41
            c[1] = x*mm12 + y*mm22 + z*mm32 + mm42
            c[2] = x*mm13 + y*mm23 + z*mm33 + mm43

        # recurse through children
        for child in node.children:
            self.__applyTorsion(child, node_mtx)
Example #20
0
    def GetConvertedArrayRepresentation(self, unitSystem):
        xType = self.parent.xMin.GetType().unitType
        unit = unitSystem.GetCurrentUnit(xType)
        if unit:
            x = array(map(unit.ConvertFromSim42, self.x))
            self.xUnit = unit.name
        else:
            x = self.x
            self.xUnit = None
        
        yType = self.parent.yMin.GetType().unitType
        unit = unitSystem.GetCurrentUnit(yType)
        if unit:
            y = array(map(unit.ConvertFromSim42, self.y))
            self.yUnit = unit.name
        else:
            y = self.y
            self.yUnit = None
            
        self.zUnits = []
        zPropIdx = self.zPropIdx
        zType = self.parent.zTypes[zPropIdx]
        unit = unitSystem.GetCurrentUnit(zType)
        if unit:
            z = array(map(unit.ConvertFromSim42, self.z))
            self.zUnits.append(unit.name)
        else:
            z = self.z
            self.zUnits.append(None)
            
        self.convTable[1:,1:] = Numeric.reshape(z, (self.pointX, self.pointY))
        self.convTable[0,1:] = y
        self.convTable[1:,0] = x

        return self.convTable
    def setData(self, data,calib,config):
        try:
            if config["file"]:
                self._configure(config)
            x = Numeric.array(data[:,0]).astype(Numeric.Float)
            y = Numeric.array(data[:,1]).astype(Numeric.Float)
            xmin = float(config["min"])
            xmax = float(config["max"])
            self.mcafit.refreshWidgets()
            calib = Numeric.ravel(calib).tolist()
            kw = {}
            kw.update(config)
            kw['xmin'] = xmin
            kw['xmax'] = xmax
            kw['calibration'] = calib
            self.mcafit.setdata(x, y, **kw)# xmin=xmin, xmax=xmax, calibration=calib)
            self.mcafit._energyAxis = False
            self.mcafit.toggleEnergyAxis()
            result = self._fit()
            #pyarch file name and directory
            pf = config["legend"].split(".")
            pd = pf[0].split("/")
            outfile = pd[-1]
            outdir = config['htmldir']
            sourcename = config['legend']
            report = McaAdvancedFit.QtMcaAdvancedFitReport.QtMcaAdvancedFitReport(None, outfile=outfile, outdir=outdir,fitresult=result, sourcename=sourcename, plotdict={'logy':False}, table=2)

            text = report.getText()
            report.writeReport(text=text)
  
        except:
            logging.getLogger().exception('McaSpectrumBrick: problem fitting %s %s %s' % (str(data),str(calib),str(config)))
            raise
Example #22
0
    def test_piecewiselinear(self):
        # Test as a procedure

        fn1_a1 = array([[0.5,0.0,0.99],
                       [1.0,0.0,0.6]])

        fn2_a1 = array([[1.0, 0.0, 1.0],
                       [1.0,0.0, 1.0]])

        fn3_a2 = array([[0.1,0.0,0.7],
                       [0.4,0.3,1.0]])


        self.fn1(self.a1)
        for item1,item2 in zip(self.a1.ravel(),fn1_a1.ravel()):
            self.assertAlmostEqual(item1, item2)

        self.a1 = array([[0.5,-1.0,0.99],
                        [1.001,-0.001,0.6]])
        self.fn2(self.a1)
        for item1,item2 in zip(self.a1.ravel(),fn2_a1.ravel()):
            self.assertAlmostEqual(item1, item2)

            
        self.fn3(self.a2)
        for item1,item2 in zip(self.a2.ravel(),fn3_a2.ravel()):
            self.assertAlmostEqual(item1, item2)
Example #23
0
def get_coordinates(universe, E, indices=None, atom_names=('CA',),
                    residue_index_list=None, atom_index_list=None):

    from numpy.oldnumeric import array, take

    if indices is None:
        indices = range(len(E))

    chain = universe.get_polymer()

    if atom_index_list is None:
        atom_index_list, index_map = compile_index_list(chain, atom_names,
                                                        residue_index_list)

    l = []

    for i in indices:

        chain.set_torsions(E.torsion_angles[i], 1)

        X = array(take(universe.X, atom_index_list))

        l.append(X)

    return array(l)
Example #24
0
    def test_divisive_sum_normalize(self):
        # Test as a procedure

        fn1_a1 = self.a1/3.0

        fn1_a2 = self.a2/27.0

        fn2_a1 = (self.a1/3.0)*4.0

        fn2_a2 = (self.a2/27.0)*4.0


        self.fn1(self.a1)
        for item1,item2 in zip(self.a1.ravel(),fn1_a1.ravel()):
            self.assertAlmostEqual(item1, item2)

        self.fn1(self.a2)
        for item1,item2 in zip(self.a2.ravel(),fn1_a2.ravel()):
            self.assertAlmostEqual(item1, item2)
            
        self.a1 = array([[0.3,0.6,0.7],
                        [0.8,0.4,0.2]])

        self.a2 = array([[1.0,-1.0,7.0],
                        [4.0,3.0,11.0]])
            
        self.fn2(self.a1)
        for item1,item2 in zip(self.a1.ravel(),fn2_a1.ravel()):
            self.assertAlmostEqual(item1, item2)

        self.fn2(self.a2)
        for item1,item2 in zip(self.a2.ravel(),fn2_a2.ravel()):
            self.assertAlmostEqual(item1, item2)
Example #25
0
    def __init__(self, elements, nocheck = None):
	self.array = Numeric.array(elements)
	if nocheck is None:
	    if not Numeric.logical_and.reduce(
		Numeric.equal(Numeric.array(self.array.shape), 3)):
		raise ValueError, 'Tensor must have length 3 along any axis'
	self.rank = len(self.array.shape)
    def display(self):
	GL.glClearColor( 0.0, 0.0, 0.0, 0.0)
	GL.glClear( GL.GL_COLOR_BUFFER_BIT)
	GL.glColor3f( 1.0,1.0,0.0)
	self.x = self.x + self.move_x
	self.y = self.y + self.move_y
	self.age = self.age + 1
	which = Numeric.greater( self.age, MAX_AGE)
	self.x = Numeric.choose( which, (self.x, RandomArray.random( NUMDOTS)))
	selfy = Numeric.choose( which, (self.y, RandomArray.random( NUMDOTS)))
	self.age = Numeric.choose( which, (self.age, 0))
	self.x = Numeric.choose( Numeric.greater( self.x, 1.0), (self.x, self.x - 1.0)) 
	self.y = Numeric.choose( Numeric.greater( self.y, 1.0), (self.y, self.y - 1.0))
	x2 = RandomArray.random( NUMDOTS2)
	y2 = RandomArray.random( NUMDOTS2)
	v = Numeric.concatenate(
		(Numeric.transpose( Numeric.array( [self.x, self.y])),
		 Numeric.transpose( Numeric.array( [self.x - 0.005, self.y + 0.005])),
		 Numeric.transpose( Numeric.array( [self.x + 0.005, self.y - 0.005])),
		 Numeric.transpose( Numeric.array( [x2, y2]))))
        #from opengltk.util import GLdouble
        #av = bufarray.readArray( v, GLdouble)
	#GL.glVertexPointer( 2, av)
        GL.glVertexPointer( 2, v)
	GL.glEnableClientState( GL.GL_VERTEX_ARRAY)
	#glplus.DrawArrays( GL.POINTS, len( av))
        from opengltk import  glplus
        glplus.DrawArrays( GL.GL_POINTS, len( v))
	#GL.glDisableClientState( GL.VERTEX_ARRAY)
	GL.glFlush()
	GLUT.glutSwapBuffers()
Example #27
0
    def test_divisive_length_normalize(self):
        # Test as a procedure
        
        eucl_norm_a1 = sqrt(0.3**2+0.6**2+0.7**2+0.8**2+0.4**2+0.2**2)
        # eucl_norm_a2 = sqrt(307)
        
        fn1_a1 = self.a1/eucl_norm_a1
        fn1_a2 = self.a2/sqrt(307)
        fn2_a1 = (self.a1/eucl_norm_a1)*4.0
        fn2_a2 = (self.a2/sqrt(307))*4.0


        self.fn1(self.a1)
        for item1,item2 in zip(self.a1.ravel(),fn1_a1.ravel()):
            self.assertAlmostEqual(item1, item2)

        self.fn1(self.a2)
        for item1,item2 in zip(self.a2.ravel(),fn1_a2.ravel()):
            self.assertAlmostEqual(item1, item2)
            
        self.a1 = array([[0.3,0.6,0.7],
                        [0.8,0.4,0.2]])

        self.a2 = array([[1.0,-1.0,7.0],
                         [4.0,3.0,11.0],
                         [2.0,5.0,9.0]])

            
        self.fn2(self.a1)
        for item1,item2 in zip(self.a1.ravel(),fn2_a1.ravel()):
            self.assertAlmostEqual(item1, item2)

        self.fn2(self.a2)
        for item1,item2 in zip(self.a2.ravel(),fn2_a2.ravel()):
            self.assertAlmostEqual(item1, item2)
Example #28
0
    def mouseMove(self, event):
        # simple trackball, only works inside cirle
        # creates an XY rotation defined by pts intersecting the spheres
        xc = event.x - self.xm
        yc = self.ym - event.y
        # compute the intersection point between
        xc2 = xc*xc
        yc2 = yc*yc
        z2 = self.r2-xc2-yc2

        if z2 < 0:
            lInvMag = 1./math.sqrt(xc2 + yc2)
            xc *= lInvMag * (self.r)
            yc *= lInvMag * (self.r)
            z2 = 0

        # compute rotation angle
	a = self.lastPt3D
	b = (xc, yc, math.sqrt(z2))
        ang = math.acos((a[0]*b[0]+a[1]*b[1]+a[2]*b[2])/self.r2)
        if self.mode=='XY':
	    #compute rotation axis
            rotaxis = Numeric.array( (a[1]*b[2] - a[2]*b[1],
				  a[2]*b[0] - a[0]*b[2],
				  a[0]*b[1] - a[1]*b[0] ), 'f' )
        elif self.mode=='X': rotaxis = Numeric.array( (1.,0.,0.), 'f')
        elif self.mode=='Y': rotaxis = Numeric.array( (0.,1.,0.), 'f')
        elif self.mode=='Z': rotaxis = Numeric.array( (0.,0.,1.), 'f')
        mat = rotax( self.zeros, rotaxis, ang )
        self.lastPt3D = b
        self.updateVector(mat)
Example #29
0
 def __init__(self, results, master=None, mini=None, maxi=None, 
                 cmap=None, cmap_name='cmap', ramp=None, npixels=10):
     assert isinstance(results, type(Numeric.array(range(4))))
     assert len(results.shape)==2
     # a copy of the input array is used
     self.results = Numeric.array(results[:])
     self.results = results
     self.master = master
     #for a Numeric array,
     self.x_number = results.shape[0]   #number of rows 
     self.y_number = results.shape[1]   #number of columns
     self.results = results
     self.npixels = npixels
     if mini is None:
         mini=min(results.ravel())
     else:
         for x in xrange(self.x_number):
             for y in xrange(self.y_number):
                 if self.results[x][y]<mini:
                     self.results[x][y]=mini
     self.mini = mini
     if maxi is None:
         maxi=max(results.ravel())
     else:
         for x in xrange(self.x_number):
             for y in xrange(self.y_number):
                 if self.results[x][y]>maxi:
                     self.results[x][y]=maxi
     self.maxi = maxi
     self.cmap = cmap 
     if cmap is None:
         if ramp is None:
             ramp = RedWhiteRamp()
         self.cmap = ColorMap(cmap_name, mini=mini, maxi=maxi, ramp=ramp)
def read_data(filename, function):
    """Read data from an ASCII file."""

    import string
    result = []
    assert type(filename) == types.StringType
    assert function in (None, float, int)
    print "reading", filename
    f = open(filename, "r")
    while 1:
	line = f.readline();
	if not len(line):
	    break
	if function:
	    datum = map(function, string.split(line))
	    result.append(list(datum))
	else:
	    result.append(line)
    f.close()
    if function == float:
	ar = Numeric.array(result).astype(viewerConst.FPRECISION)
    elif function == int:
	ar = Numeric.array(result).astype(viewerConst.IPRECISION)
    else:
	ar = result

    return ar
Example #31
0
    def _apcorr(self,detector,filter):
        """Calculate the aperture corrections for this dataset for the given detector and filter.
        This is a factor to be added to the magnitudes calculated above array [m].
        This "apcor" is to be in magnitudes and apcor must be <= 0.  This new magnitude or
        array of magnitudes is then written into the multicolor.cat file and presented to
        BPZ as the magnitude to use, as indicated in the multicolor.columns file.
        Function returns a numeric array of aperture corrections.  The fiducial radius
        specified herein is specified in Bugzilla bug #2708, as are the other specifications
        for this method.
        """
        apcorr = []
        apcorrArray = None
        irad_fiducial = 14
        aperFiles = {
            "WFC" : os.path.join(self.aperData,"newWFC_0803.ee_new_csky.dat"),  #by xingxing
            "HRC" : os.path.join(self.aperData,"newHRC_0803.ee_new_csky.dat"),
            "UVIS" : os.path.join(self.aperData,"newUVIS_0803.ee_new_csky.dat"),
            "IR"   : os.path.join(self.aperData,"newIR_0803.ee_new_csky.dat"  )
            }
            
        try:
            aperDataFile = aperFiles[detector]
        except KeyError:
            raise KeyError,"No known aperture data for detector, "+detector

        # now get the filter aperture data for the indicated detector.
        # raise a filterError if the lookup fails.

        #pdb.set_trace()
        aperCatalog = open(aperDataFile).readlines()
        selectSet   = pUtil.makeHeaderDict(aperCatalog)
        colName     = "EE_"+filter
        try:
            aperIndex   = selectSet[colName]-1
        except KeyError:
            raise fUtil.filterError,"No aperture data for filter "+filter
        
        aperData    = tableio.get_data(aperDataFile,aperIndex)

        # the aperData contains the encircled energy as a function of radius in
        # pixels.  Conveniently, the pixel radius = index + 1 of the value we
        # want from the array for that radius.
        
        eeFiducial  = aperData[irad_fiducial -1]

        for irad in self.iradList:
            if irad > irad_fiducial:
                apcorr.append(0)
                continue
            
            # irad1, irad2 are the adjacent integers of the radius of the object.
            # used to do a linear interpolation on the encircled energy curve.

            irad1    = int(irad)
            irad2    = irad1 + 1
            iradFrac = irad - irad1
            ee_irad1 = aperData[irad1-1]
            ee_irad2 = aperData[irad2-1]
            k = (ee_irad2 - ee_irad1)
            ee_irad = k*iradFrac + ee_irad1
            apcorr.append(min(0,+2.5*math.log10(ee_irad/eeFiducial)))
        apcorrArray = Numeric.array(apcorr)
        return apcorrArray
Example #32
0
    def test_vertical_oddimage_evensheet__horizontal_evenimage_evensheet(self):
        """
        Test vertical positioning for even sheet, odd image and horizontal
        positioning for even image, even sheet.
        """
        image_array = array([[
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
        ], [
            0.,
            34.,
            68.,
            102.,
            136.,
            255.,
            0.,
            0.,
        ], [
            0.,
            34.,
            68.,
            102.,
            136.,
            255.,
            255.,
            0.,
        ], [
            0.,
            34.,
            68.,
            102.,
            136.,
            255.,
            255.,
            255.,
        ], [
            255.,
            0.,
            255.,
            0.,
            255.,
            0.,
            255.,
            0.,
        ], [
            0.,
            255.,
            0.,
            255.,
            0.,
            255.,
            0.,
            255.,
        ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ]], Float)

        image = FileImage(filename=resolve_path('tests/testimage.pgm'),
                          xdensity=8,
                          ydensity=8,
                          bounds=BoundingBox(radius=0.5),
                          output_fns=[])

        ps = image.pattern_sampler
        ps.size_normalization = 'original'
        ps.whole_pattern_output_fns = []

        assert_array_almost_equal(image_array, image())
Example #33
0
def standardDeviation(data):
    data = Numeric.array(data)
    return Numeric.sqrt(variance(data))
Example #34
0
    def createCanvas(self, master, wheelPad=6):
        bw = self.borderWidth = wheelPad  # distance between wheel and raise

        cd = {
            'width': self.width + bw,
            'height': self.height + bw,
            'relief': 'raised',
            'borderwidth': 3
        }

        for k, w in self.canvasCfg.items():
            cd[k] = w

        self.canvas = Tkinter.Canvas(self, cd)
        cbdw = int(self.canvas.cget('borderwidth'))
        bd = self.borderWidth + cbdw + 1  # +1 for pixel0 that is not drawn

        height = self.height - bw
        width = self.width - bw
        cp = self.canvas.create_polygon
        self.outline1 = cp(bd,
                           bd,
                           bd,
                           height + cbdw,
                           width + cbdw,
                           height + cbdw,
                           width + cbdw,
                           bd,
                           bd,
                           bd,
                           width=1,
                           outline='gray60',
                           fill='gray85')

        ul = bd + 1  # upper left pixel
        l = (width + cbdw - 1) - (bd + 1)  # length of the inner box
        cl25 = 2. * l / 25.
        cl = self.canvas.create_line
        self.outline2 = cl(ul + int(cl25),
                           ul,
                           ul,
                           ul,
                           ul,
                           height + cbdw - 1,
                           ul + int(cl25),
                           height + cbdw - 1,
                           width=1,
                           fill='gray20')
        self.outline3 = cl(ul + int(cl25),
                           ul,
                           ul + int(3 * cl25),
                           ul,
                           width=1,
                           fill='gray60')
        self.outline4 = cl(ul + int(cl25),
                           height + cbdw - 1,
                           ul + int(3 * cl25),
                           height + cbdw - 1,
                           width=1,
                           fill='gray60')
        self.outline5 = cl(ul + int(5 * cl25),
                           ul,
                           ul + int(7.5 * cl25),
                           ul,
                           width=1,
                           fill='white')
        self.outline4 = cl(ul + int(5 * cl25),
                           height + cbdw - 1,
                           ul + int(7.5 * cl25),
                           height + cbdw - 1,
                           width=1,
                           fill='white')
        self.outline6 = cl(ul + int(9.5 * cl25),
                           ul,
                           ul + int(11.5 * cl25),
                           ul,
                           width=1,
                           fill='gray60')
        self.outline7 = cl(ul + int(9.5 * cl25),
                           height + cbdw - 1,
                           ul + int(11.5 * cl25),
                           height + cbdw - 1,
                           width=1,
                           fill='gray60')

        re = ul + l
        self.outline8 = cl(ul + int(11.5 * cl25),
                           ul,
                           re,
                           ul,
                           re,
                           height + cbdw - 1,
                           ul + int(11.5 * cl25),
                           height + cbdw - 1,
                           width=1,
                           fill='gray20')

        # corners of the box where the lines have to be drawn
        self.innerbox = (ul + 1, ul + 1, re - 1, height + cbdw - 1)

        self.circlePtsAngles = []
        inc = 2 * math.pi / float(self.nblines)
        for i in range(self.nblines):
            self.circlePtsAngles.append(i * inc)
        self.circlePtsAngles = Numeric.array(self.circlePtsAngles, 'f')
        self.linesIds = []
        self.shLinesIds = []
        # this table should depend on the number of lines
        # currently it is of length 15 (self.nblines/2)
        # It should be resized automatically to self.nblines/2
        self.shadowLinesOptions = [
            (0, 'black', 1),  # offset, color, width
            (2, 'gray30', 1),
            (2, 'gray30', 1),
            (0, 'gray30', 1),
            (-1, 'white', 1),
            (-1, 'white', 1),
            (-1, 'white', 2),
            (-1, 'white', 2),
            (-1, 'white', 2),
            (-1, 'white', 2),
            (-1, 'white', 1),
            (-1, 'white', 1),
            (0, 'gray30', 1),
            (-2, 'gray30', 1),
            (-2, 'gray30', 1),
            (0, 'black', 1),  # offset, color, width
            (0, 'black', 1),  # offset, color, width
        ]

        for i in range(self.nblines):
            self.linesIds.append(cl(0, 0, 0, 0, width=1, fill='black'))
            self.shLinesIds.append(cl(0, 0, 0, 0))

        wlabCfg = {'padx': 0, 'pady': 0}
        wlabCfg.update(self.wheelLabCfg)
        self.valueLabel = apply(Tkinter.Label, (self.master, ), wlabCfg)

        self.drawLines()
        self.canvas.pack(side=Tkinter.LEFT)
        self.toggleWidgetLabel(self.showLabel)
Example #35
0
    for xyz in t.frames:
        result_xyz.append(xyz.astype('f'))

    for fname in t.frameNames:
        result_frameNames.append(fname)

    T.flushPrint('#')

print " Done"

result = Trajectory()

result.ref = result_ref
result.ref.disconnect()

if 'pdb' in o:
    result.ref.pdbCode = o['pdb']

result.frames = N.array(result_xyz, 'f')
result.frameNames = result_frameNames

del result_xyz
## too much memory required for this
## result = trajLst[0].concat( *trajLst[1:] )

T.flushPrint("Converting to EnsembleTraj...")
result = traj2ensemble(result, len(inLst))

T.flushPrint("Done\nDumping ensemble traj to " + o['o'])
T.dump(result, T.absfile(o['o']))
Example #36
0
    def nextComplex(self):
        """
        Take list of lines, extract all Hex info about one complex
        (Solution number, hex energy,..) also extract 16 numbers of
        the transformation matrix and put them into 4 by 4 numeric
        array.

        @return: Complex created from the output from Hex
        @rtype: Complex
        """
        ## get set of lines describing next complex:
        lines = self._nextBlock()
        if lines == None:
            ## EOF
            return None
        ## skip incomplete records
        if len(lines) < 13:
            lines = self._nextBlock()

        ## fill info dictionary
        i = {}
        matrix = None
        for l in lines:
            try:
                ## labels has to be in the same order as in hex.out
                m = self.ex_line.search(l)
                if m != None:
                    m = m.groups()

                    if m[0] == 'Orientation':
                        i['hex_clst'] = int(m[1])
                    elif m[0] == 'Solution':
                        i['soln'] = int(m[1])
                    elif m[0] == 'ReceptorModel':
                        if self.forceModel:
                            i['model1'] = self.forceModel[0]
                        else:
                            i['model1'] = int(m[1])
                    elif m[0] == 'LigandModel':
                        if self.forceModel:
                            i['model2'] = self.forceModel[1]
                        else:
                            i['model2'] = int(m[1])
                    elif m[0] == 'Bumps':
                        if int(m[1]) != -1:
                            i['bumps'] = int(m[1])
                    elif m[0] == 'ReferenceRMS':
                        i['rms'] = float(m[1])
                    elif m[0] == 'Vshape':
                        if float(m[1]) != 0.0:
                            i['hex_Vshape'] = float(m[1])
                    elif m[0] == 'Vclash':
                        if float(m[1]) != 0.0:
                            i['hex_Vclash'] = float(m[1])
                    elif m[0] == 'Etotal':
                        i['hex_etotal'] = float(m[1])
                    elif m[0] == 'Eshape':
                        i['hex_eshape'] = float(m[1])
                    elif m[0] == 'LigandMatrix':
                        ## get all numbers of matrix as list of strings
                        strings = self.ex_matrix.findall(l)
                        ## convert that to list of floats
                        numbers = []
                        for each in strings:
                            numbers += [float(each)]
                        ## convert that to list of lists of 4 floats each
                        matrix = []
                        for j in range(0, 4):
                            matrix.append(numbers[4 * j:4 * (j + 1)])
                        ## create 4 by 4 Numeric array from 4 by 4 list
                        matrix = Numeric.array(matrix, Numeric.Float32)
            except AttributeError:
                print "HexParser.nextComplex(): ", t.lastError()

        ## Create new complex taking PCR models from dictionary
        c = Complex(self.rec_models[i['model1']], self.lig_models[i['model2']],
                    matrix, i)
        return c
Example #37
0
 def applyTranslation(self, t=(0., 0., 0.)):
     """Translate by (x, y, z)
     """
     translation = Numeric.array([t[0], t[1], t[2], 0.0])
     self.resultCoords = self.resultCoords + translation
     return self.getResultCoords()
Example #38
0
    def test_fit_shortest(self):
        """
        Test that the shorter dimension is made to fit 1.0, while the other
        is scaled by the same factor.
        """
        ### 15 units represent 1.0 in sheet coordinates.
        image_array = array([[
            34.,
            68.,
            68.,
            68.,
            102.,
            102.,
            102.,
            136.,
            136.,
            136.,
            255.,
            255.,
            255.,
            0.,
            0.,
        ],
                             [
                                 34.,
                                 68.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                             ],
                             [
                                 34.,
                                 68.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                             ],
                             [
                                 34.,
                                 68.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                             ],
                             [
                                 34.,
                                 68.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                             ],
                             [
                                 34.,
                                 68.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                             ],
                             [
                                 34.,
                                 68.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                             ],
                             [
                                 34.,
                                 68.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                             ],
                             [
                                 34.,
                                 68.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                             ],
                             [
                                 0.,
                                 255.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                             ],
                             [
                                 0.,
                                 255.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                             ],
                             [
                                 0.,
                                 255.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                             ],
                             [
                                 255.,
                                 0.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                             ],
                             [
                                 255.,
                                 0.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                             ],
                             [
                                 255.,
                                 0.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                             ]])

        image = FileImage(filename=resolve_path('tests/testimage.pgm'),
                          xdensity=15,
                          ydensity=15,
                          output_fns=[],
                          bounds=BoundingBox(radius=0.5))

        ps = image.pattern_sampler
        ps.size_normalization = 'fit_shortest'
        ps.whole_pattern_output_fns = []

        assert_array_almost_equal(image_array, image())
Example #39
0
    def test_stretch_to_fit(self):
        """
        Test that both image dimensions are made to fit 1.0.
        """
        ### 8 units represent 1.0 in sheet coordinates.
        image_array = array([[
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
        ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 0.,
                                 34.,
                                 68.,
                                 102.,
                                 136.,
                                 255.,
                                 0.,
                                 0.,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 0.,
                                 34.,
                                 68.,
                                 102.,
                                 136.,
                                 255.,
                                 0.,
                                 0.,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 0.,
                                 34.,
                                 68.,
                                 102.,
                                 136.,
                                 255.,
                                 255.,
                                 0.,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 0.,
                                 34.,
                                 68.,
                                 102.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 0.,
                                 34.,
                                 68.,
                                 102.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 255.,
                                 0.,
                                 255.,
                                 0.,
                                 255.,
                                 0.,
                                 255.,
                                 0.,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 0.,
                                 255.,
                                 0.,
                                 255.,
                                 0.,
                                 255.,
                                 0.,
                                 255.,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 0.,
                                 255.,
                                 0.,
                                 255.,
                                 0.,
                                 255.,
                                 0.,
                                 255.,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ]])

        image = FileImage(filename=resolve_path('tests/testimage.pgm'),
                          xdensity=8,
                          ydensity=8,
                          output_fns=[],
                          bounds=BoundingBox(radius=1.0))

        ps = image.pattern_sampler
        ps.size_normalization = 'stretch_to_fit'
        ps.whole_pattern_output_fns = []

        assert_array_almost_equal(image_array, image())
Example #40
0
def A(a):
    return Numeric.array(a, Numeric.Float)
Example #41
0
File: CES.py Project: shao130/sim42
    def Solver(self, model, case):

        xm = case.Prop["x"]
        T = case.Prop["T"]
        P = case.Prop["P"]
        Ac = model["PR_A"]
        b_i = model["PR_B"]
        W_i = model["OMEGA"]
        TC_i = model["TC"]

        case.Prop["MolWt"] = sum(xm * model["MoleWt"])

        fwi = []
        for Wii in W_i:
            if Wii < 0.5:
                fwi.append(0.37464 + 1.54226 * Wii - 0.26992 * power(Wii, 2))
            else:
                fwi.append(0.3796 + 1.4850 * Wii - 0.1644 * power(Wii, 2) +
                           0.01666 * power(Wii, 3))

        fwi = array(fwi)
        Tr_i = T / TC_i
        AlphaT = power((1 + fwi * (1 - sqrt(Tr_i))), 2)

        a_i = Ac * AlphaT

        A_i = (a_i * P) / pow(R * T, 2)
        B_i = (b_i * P) / (R * T)

        Zl_i = self.EOS.ZL(A_i, B_i)
        Zv_i = self.EOS.ZG(A_i, B_i)

        CoeFugo_v = self.FugaP(Zv_i, A_i, B_i)
        CoeFugo_l = self.FugaP(Zl_i, A_i, B_i)

        yf = xm
        xf = xm

        for i in range(3):

            A_vi = MixingRules.MolarK2(yf, A_i, k=0.0)
            A_li = MixingRules.MolarK2(xf, A_i, k=0.0)

            B_v = MixingRules.Molar(yf, B_i)
            A_v = MixingRules.MolarK(yf, A_i, k=0.0)

            B_l = MixingRules.Molar(xf, B_i)
            A_l = MixingRules.MolarK(xf, A_i, k=0.0)

            Z_v = self.EOS.ZG(A_v, B_v)
            Z_l = self.EOS.ZL(A_l, B_l)

            CoeFugM_v = self.FugaM(Z_v, A_vi, B_i, A_v, B_v)
            CoeFugM_l = self.FugaM(Z_l, A_li, B_i, A_l, B_l)

            fi = P * CoeFugM_v * yf

            ki = CoeFugM_l / CoeFugM_v
            #print xm
            FrVap, xf, yf = Flash(ki, xm)
            Z = FrVap * Z_v + (1 - FrVap) * Z_l

        case.Prop["Z"] = Z
        case.Prop["Zl"] = Z_l
        case.Prop["Zv"] = Z_v
        case.Prop["Ki"] = ki
        case.Prop["FracVap"] = FrVap
        case.Prop["CoefPureLiq"] = CoeFugo_l
        case.Prop["CoefPureVap"] = CoeFugo_v
        case.Prop["CoefMixVLiq"] = CoeFugM_l
        case.Prop["CoefMixVap"] = CoeFugM_v
        case.Prop["xf"] = xf
        case.Prop["yf"] = yf
Example #42
0
 def P(self,T,m):
     logP = m["ANT_A"]-(m["ANT_B"]/ ( T + m["ANT_C"] ))
     for i in range(len(logP)):
         if logP[i]<-36:
             logP[i]= -18.420680743952367
     return array( exp( logP )*self.Factor)
Example #43
0
# Author: Michel F. SANNER
#
# Copyright: M. Sanner TSRI 2000
#
#############################################################################

#
# $Header: /opt/cvs/python/packages/share1.5/DejaVu/jitter.py,v 1.4 2007/07/24 17:30:42 vareille Exp $
#
# $Id: jitter.py,v 1.4 2007/07/24 17:30:42 vareille Exp $
#

from numpy.oldnumeric import array

# 2 jitter points
_jitter2 = array(((0.246490, 0.249999), (-0.246490, -0.249999)), 'f')

# 3 jitter points
_jitter3 = array(
    ((-0.373411, -0.250550), (0.256263, 0.368119), (0.117148, -0.117570)), 'f')

# 4 jitter points
_jitter4 = array(((-0.208147, 0.353730), (0.203849, -0.353780),
                  (-0.292626, -0.149945), (0.296924, 0.149994)), 'f')

# 8 jitter points
_jitter8 = array(
    ((-0.334818, 0.435331), (0.286438, -0.393495), (0.459462, 0.141540),
     (-0.414498, -0.192829), (-0.183790, 0.082102), (-0.079263, -0.317383),
     (0.102254, 0.299133), (0.164216, -0.054399)), 'f')
Example #44
0
 def T(self,P,m):
     return array( m["ANT_B"] / (m["ANT_A"] - log(P/self.Factor)) - m["ANT_C"])
Example #45
0
 def __init__(self, lines, MOL2FLAG):
     #
     # Given the atoms, this routine tells you everything you want to know about
     # the ligand
     #
     #
     # Store the atoms
     #
     if MOL2FLAG == False:
         self.atoms = {}
         import string
         for line in lines:
             split = string.split(line)
             name = split[0]
             self.atoms[name] = {
                 'coords':
                 Numeric.array(
                     [float(split[1]),
                      float(split[2]),
                      float(split[3])])
             }
             self.atoms[name]['bonds'] = []
         #
         # Get the likely types from names
         #
         trivial_types = ['N', 'O', 'C', 'H']
         for atom in self.atoms.keys():
             if atom[0] in trivial_types:
                 if atom[0] != 'H':  # Get rid of all the hydrogens
                     self.atoms[atom]['type'] = atom[0]
                     self.atoms[atom]['sybylType'] = 'Unknown'
         #
         # Get the bonds
         # First approximation: Anything closer than 2.0 A is bonded
         #
         self.dists = {}
         for atom1 in self.atoms.keys():
             self.dists[atom1] = {}
             for atom2 in self.atoms.keys():
                 if atom1 == atom2:
                     continue
                 #
                 # Calculate the distance
                 #
                 self.dists[atom1][atom2] = length(
                     self.atoms[atom1]['coords'] -
                     self.atoms[atom2]['coords'])
                 if self.dists[atom1][atom2] < 2.0:
                     self.atoms[atom1]['bonds'].append(atom2)
         #
         # Count number of bonds to non-H atoms and guess atom type
         #
         bond_lengths = {'C-C': [1.5, 0.2]}
         #
         # Get the torsion angles
         #
         atoms = self.atoms.keys()
         atoms.sort()
         for atom in atoms:
             self.atoms[atom]['torsions'] = self.get_torsions(atom)
         #
         # Produce the definition lines
         #
         self.lines = self.create_deflines()
         #
         # Now we try to guess the atom types
         #
         self.guess_atom_types()
     else:
         #
         # We have a mol2 file
         #
         LIG = lines
         self.atoms = {}
         for line in lines:
             name = line.name
             #            self.atoms[name] = name
             self.atoms[name] = {
                 'coords':
                 Numeric.array(
                     [float(line.x),
                      float(line.y),
                      float(line.z)])
             }
             self.atoms[name]['sybylType'] = line.sybylType
             #
             # we don't have this information when coming from PDB!
             self.atoms[name]['lBondedAtoms'] = line.lBondedAtoms
             self.atoms[name]['lBonds'] = line.lBonds
             ###PC
             # one bond is lost!
             self.atoms[name]['bonds'] = []
             for BBonds in line.lBondedAtoms:  #line.lBonds:
                 self.atoms[name]['bonds'].append(BBonds.name)
             ###PC
             # save the atomname & id
             self.atoms[name]['atomname'] = name
             self.atoms[name]['serial'] = line.serial
             #
             # USEFUL information
             # bonded heavy atoms
             self.atoms[name]['nbhvy'] = len([
                 x for x in self.atoms[name]['lBondedAtoms']
                 if x.sybylType != "H"
             ])
             # number of bonds (including hydrogens)
             self.atoms[name]['nbds'] = len(self.atoms[name]['lBonds'])
             # number of bonded hydrogens
             self.atoms[name]['nbhyd'] = self.atoms[name][
                 'nbds'] - self.atoms[name]['nbhvy']
             # element
             self.atoms[name]['ele'] = self.atoms[name]['sybylType'].split(
                 '.')[0]
         #
         # Get the torsion angles
         #
         atoms = self.atoms.keys()
         atoms.sort()
         for atom in atoms:
             self.atoms[atom]['torsions'] = self.get_torsions(atom)
         self.lines = self.create_deflines()
     #
     # we have the sybylType in self.atoms!!!
     return
Example #46
0
 def clear(self):
     #TODO make with clear
     x = Numeric.array([0]).astype(Numeric.Float)
     y = Numeric.array([0]).astype(Numeric.Float)
     self.mcafit_widget.setdata(x, y)
Example #47
0
def average(data):
    data = Numeric.array(data)
    return Numeric.add.reduce(data)/len(data)
Example #48
0
    def test_fit_longest(self):
        """
        Check that the longer image dimension is made to fit the default
        dimension of 1.0, while the other is scaled the same.
        """
        ### Twice the default BoundingBox dimensions, image size of 2.0.
        ### In this case, 8 units represent 1.0 in sheet coordinates.
        image_array = array([[
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
            96.59090909,
        ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 0.,
                                 0.,
                                 34.,
                                 34.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 0.,
                                 0.,
                             ],
                             [
                                 0.,
                                 0.,
                                 34.,
                                 34.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 0.,
                                 0.,
                             ],
                             [
                                 0.,
                                 0.,
                                 34.,
                                 34.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                             ],
                             [
                                 0.,
                                 0.,
                                 34.,
                                 34.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                             ],
                             [
                                 0.,
                                 0.,
                                 34.,
                                 34.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                             ],
                             [
                                 0.,
                                 0.,
                                 34.,
                                 34.,
                                 68.,
                                 68.,
                                 102.,
                                 102.,
                                 136.,
                                 136.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                                 255.,
                             ],
                             [
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                             ],
                             [
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                             ],
                             [
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                             ],
                             [
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                                 0.,
                                 0.,
                                 255.,
                                 255.,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ],
                             [
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                                 96.59090909,
                             ]], Float)

        image = FileImage(filename=resolve_path('tests/testimage.pgm'),
                          xdensity=8,
                          ydensity=8,
                          size=2.0,
                          output_fns=[],
                          bounds=BoundingBox(radius=1.0))

        ps = image.pattern_sampler
        ps.size_normalization = 'fit_longest'
        ps.whole_pattern_output_fns = []

        assert_array_almost_equal(image_array, image())
Example #49
0
    filetype = os.path.splitext(os.path.basename(filename))[1]
    if verbose: print "filetype=", filetype
    writer = None
    if filetype == '.pdbqt':
        writer = PdbqtWriter()
    elif filetype == '.pdbq':
        writer = PdbqWriter()
    elif filetype == '.pdbqs':
        writer = PdbqsWriter()
    elif filetype == '.pdb':
        writer = PdbWriter()
    else:
        print 'Sorry! Unable to write this filetype->', filetype

    center = Numeric.add.reduce(mol.allAtoms.coords) / len(mol.allAtoms)
    crds = Numeric.array(mol.allAtoms.coords)
    center = Numeric.add.reduce(crds) / len(mol.allAtoms)
    crds = crds - center
    crds = crds.tolist()
    mol.allAtoms.updateCoords(crds)
    lenCoords = len(crds)
    #rotate the atoms here
    if axis is not None and angle is not None:
        rot = (float(angle) * 3.14159 / 180.) % (2 * Numeric.pi)
        x = Numeric.array([0., 0., 0.])
        y = Numeric.array(map(float, axis.split(',')))
        matrix = rotax(x, y, rot)
        _ones = Numeric.ones(lenCoords, 'f')
        _ones.shape = (lenCoords, 1)
        mov_coords = Numeric.concatenate((crds, _ones), 1)
        newcoords = Numeric.dot(mov_coords, matrix)
    def test_divisive_lp_normalize(self):

        ### JCALERT! As already said above; this method does not work as a procedure
        ### because of a problem when using x *= factor instead of x = x * factor
        ### it is not understood why because it does work fine in all others transferfn?
        ### Therefore it is only tested as a function

        # Test as a function

        eucl_norm_a1 = sqrt(0.3**2 + 0.6**2 + 0.7**2 + 0.8**2 + 0.4**2 +
                            0.2**2)

        fn1_a1 = self.a1 / eucl_norm_a1
        fn1_a2 = self.a2 / sqrt(307)

        l3norm_a1 = pow(0.3**3 + 0.6**3 + 0.7**3 + 0.8**3 + 0.4**3 + 0.2**3,
                        1.0 / 3.0)
        l3norm_a2 = pow(
            2.0 + 7.0**3 + 4.0**3 + 3.0**3 + 11.0**3 + 2.0**3 + 5.0**3 +
            9.0**3, 1.0 / 3.0)
        fn2_a1 = self.a1 / l3norm_a1
        fn2_a2 = self.a2 / l3norm_a2

        self.fn1(self.a1)
        self.fn1(self.a2)
        for item1, item2 in zip(self.a1.ravel(), fn1_a1.ravel()):
            self.assertAlmostEqual(item1, item2)
        for item1, item2 in zip(self.a2.ravel(), fn1_a2.ravel()):
            self.assertAlmostEqual(item1, item2)

        self.a1 = array([[0.3, 0.6, 0.7], [0.8, 0.4, 0.2]])

        self.a2 = array([[1.0, -1.0, 7.0], [4.0, 3.0, -11.0], [2.0, 5.0, 9.0]])

        self.fn2(self.a1)
        self.fn2(self.a2)
        for item1, item2 in zip(self.a1.ravel(), fn2_a1.ravel()):
            self.assertAlmostEqual(item1, item2)
        for item1, item2 in zip(self.a2.ravel(), fn2_a2.ravel()):
            self.assertAlmostEqual(item1, item2)

        self.a1 = array([[0.3, 0.6, 0.7], [0.8, 0.4, 0.2]])

        self.a2 = array([[1.0, -1.0, 7.0], [4.0, 3.0, -11.0], [2.0, 5.0, 9.0]])

        l4norm_a1 = pow(
            0.3**4.0 + 0.6**4.0 + 0.7**4.0 + 0.8**4.0 + 0.4**4.0 + 0.2**4.0,
            1.0 / 4.0)
        l4norm_a2 = pow(
            1.0**4.0 + 1.0**4.0 + 7.0**4.0 + 4.0**4.0 + 3.0**4.0 + 11.0**4.0 +
            2.0**4.0 + 5.0**4.0 + 9.0**4.0, 1.0 / 4.0)
        fn3_a1 = (self.a1 / l4norm_a1) * 2.0
        fn3_a2 = (self.a2 / l4norm_a2) * 2.0

        self.fn3(self.a1)
        self.fn3(self.a2)
        for item1, item2 in zip(self.a1.ravel(), fn3_a1.ravel()):
            self.assertAlmostEqual(item1, item2)
        for item1, item2 in zip(self.a2.ravel(), fn3_a2.ravel()):
            self.assertAlmostEqual(item1, item2)

        # The rest of this procedure might be redundant (already covered above)

        self.a1 = array([[0.3, 0.6, 0.7], [0.8, 0.4, 0.2]])

        self.a2 = array([[1.0, -1.0, 7.0], [4.0, 3.0, -11.0], [2.0, 5.0, 9.0]])

        self.fn1(self.a1)
        for item1, item2 in zip(self.a1.ravel(), fn1_a1.ravel()):
            self.assertAlmostEqual(item1, item2)
        self.fn1(self.a2)
        for item1, item2 in zip(self.a2.ravel(), fn1_a2.ravel()):
            self.assertAlmostEqual(item1, item2)

        self.a1 = array([[0.3, 0.6, 0.7], [0.8, 0.4, 0.2]])

        self.a2 = array([[1.0, -1.0, 7.0], [4.0, 3.0, -11.0], [2.0, 5.0, 9.0]])

        self.fn2(self.a1)
        for item1, item2 in zip(self.a1.ravel(), fn2_a1.ravel()):
            self.assertAlmostEqual(item1, item2)
        self.fn2(self.a2)
        for item1, item2 in zip(self.a2.ravel(), fn2_a2.ravel()):
            self.assertAlmostEqual(item1, item2)

        self.a1 = array([[0.3, 0.6, 0.7], [0.8, 0.4, 0.2]])

        self.a2 = array([[1.0, -1.0, 7.0], [4.0, 3.0, -11.0], [2.0, 5.0, 9.0]])

        self.fn3(self.a1)
        for item1, item2 in zip(self.a1.ravel(), fn3_a1.ravel()):
            self.assertAlmostEqual(item1, item2)
        self.fn3(self.a2)
        for item1, item2 in zip(self.a2.ravel(), fn3_a2.ravel()):
            self.assertAlmostEqual(item1, item2)
Example #51
0
    def Draw(self):
        for i in xrange(len(self.vertexSet)):
            if len(self.radii) == 1:
                rad = self.radii[0]
            else:
                rad = self.radii[i]
            if len(self.angles) == 1:
                ang = self.angles[0]
            else:
                ang = self.angles[i]

            vx, vy, vz = norm = self.vertexSet.normals.array[i]
            if self.vectors is None:
                # get orthogonal vector
                dx, dy, dz = fabs(vx), fabs(vy), fabs(vz)
                mini = min([dx, dy, dz])
                if mini == dx:
                    nov = 1. / sqrt(vz * vz + vy * vy)
                    ovx = 0.
                    ovy = -vz * nov
                    ovz = vy * nov
                elif mini == dy:
                    nov = 1. / sqrt(vz * vz + vx * vx)
                    ovx = -vz * nov
                    ovy = 0.
                    ovz = vx * nov
                else:
                    nov = 1. / sqrt(vy * vy + vx * vx)
                    ovx = -vy * nov
                    ovy = vx * nov
                    ovz = 0.
                vec = [ovx, ovy, ovz]

            elif len(self.vectors) == 1:
                vec = self.vectors[0]
            else:
                vec = self.vectors[i]

            angRad = ang * pi * 0.00555555555556
            nsegments = int(ang / self.degreesPerSegment) + 1
            d = angRad / nsegments  # increment
            a = 0  # starting angle

            GL.glNormal3fv(norm.astype('f'))
            GL.glPushName(i)
            GL.glBegin(GL.GL_TRIANGLE_FAN)
            if self.materials[
                    GL.GL_FRONT].binding[0] == viewerConst.PER_VERTEX:
                col = self.materials[GL.GL_FRONT].prop[0]
                GL.glColor4fv(col[i])
            center = Numeric.array(self.vertexSet.vertices.array[i])
            vec = Numeric.array(vec).astype('f')
            #vec = vec/sqrt(Numeric.sum(vec*vec))
            vec2 = Numeric.zeros(3, 'f')
            vec2[0] = vec[1] * norm[2] - vec[2] * norm[1]
            vec2[1] = vec[2] * norm[0] - vec[0] * norm[2]
            vec2[2] = vec[0] * norm[1] - vec[1] * norm[0]
            GL.glVertex3fv(center)
            for j in range(nsegments + 1):
                p = center + cos(a) * vec * rad + sin(a) * vec2 * rad
                GL.glVertex3fv(p.astype('f'))
                a = a + d
            GL.glEnd()
            GL.glPopName()
        return 1
    def setUp(self):

        self.a = array([[0.3, 0.6, 0.7], [0.8, 0.4, 0.2]])

        self.hme = HomeostaticMaxEnt()
Example #53
0
def variance(data):
    data = Numeric.array(data)
    return Numeric.add.reduce(
        (data - average(data, axis=0))**2) / (len(data) - 1)
Example #54
0
    def rigidFit(self, mobileCoords):
        """
        the rigidFit method computes the necessary
        transformation matrices to superimpose the list of mobileCoords
        onto the list of referenceCoords, and stores the resulting matrices

        (rot, trans) <- rigidFit(mobileCoords)
        Rigid body fit. Finds transformation (rot,trans) such that
        r.m.s dist(x,rot*y+trans) --> min !
        mobileCoords: cartesian coordinates of mobile structure (3,n) (input)
        rot   : rotation matrix (3,3) (output)
        trans : translation vector (3) (output)
        status: 0 if OK, 1 if singular problem (n<3 ...)

        Method: W.Kabsch, Acta Cryst. (1976). A32,922-923
        W.Kabsch, Acta Cryst. (1978). A34,827-828
        """
        if self.refCoords is None:
            raise RuntimeError(" no reference coordinates specified")

        refCoords = self.refCoords
        if len(refCoords) != len(mobileCoords):
            raise RuntimeError("input vector length mismatch")

        refCoords = Numeric.array(refCoords)
        mobileCoords = Numeric.array(mobileCoords)

        #
        # 1. Compute centroids:
        refCentroid = Numeric.sum(refCoords) / len(refCoords)
        mobileCentroid = Numeric.sum(mobileCoords) / len(mobileCoords)

        #
        # 2. Wolfgang Kabsch's method for rotation matrix rot:
        rot = Numeric.identity(3).astype('f')
        # LOOK how to modify that code.
        for i in xrange(3):
            for j in xrange(3):
                rot[j][i] = Numeric.sum(
                    (refCoords[:, i] - refCentroid[i]) *
                    (mobileCoords[:, j] - mobileCentroid[j]))

        rotTransposed = Numeric.transpose(rot)
        e = Numeric.dot(rot, rotTransposed)

        evals, evecs = LinearAlgebra.eigenvectors(e)

        ev = Numeric.identity(3).astype('d')
        # set ev[0] to be the evec or the largest eigenvalue
        # and ev[1] to be the evec or the second largest eigenvalue
        eigenValues = list(evals)
        discard = eigenValues.index(min(eigenValues))
        i = j = 0
        while i < 3:
            if i == discard:
                i = i + 1
                continue
            ev[j] = evecs[i]
            j = j + 1
            i = i + 1
        evecs = ev

        evecs[2][0] = evecs[0][1] * evecs[1][2] - evecs[0][2] * evecs[1][1]
        evecs[2][1] = evecs[0][2] * evecs[1][0] - evecs[0][0] * evecs[1][2]
        evecs[2][2] = evecs[0][0] * evecs[1][1] - evecs[0][1] * evecs[1][0]

        b = Numeric.dot(evecs, rot)

        norm = math.sqrt(b[0][0] * b[0][0] + b[0][1] * b[0][1] +
                         b[0][2] * b[0][2])
        if math.fabs(norm) < 1.0e-20: return -1, -1
        b[0] = b[0] / norm

        norm = math.sqrt(b[1][0] * b[1][0] + b[1][1] * b[1][1] +
                         b[1][2] * b[1][2])
        if math.fabs(norm) < 1.0e-20: return -1, -1
        b[1] = b[1] / norm

        # vvmult(b[0],b[1],b[2])
        b[2][0] = b[0][1] * b[1][2] - b[0][2] * b[1][1]
        b[2][1] = b[0][2] * b[1][0] - b[0][0] * b[1][2]
        b[2][2] = b[0][0] * b[1][1] - b[0][1] * b[1][0]
        # mtrans3(e)
        e = evecs
        tempo = e[0][1]
        e[0][1] = e[1][0]
        e[1][0] = tempo
        tempo = e[0][2]
        e[0][2] = e[2][0]
        e[2][0] = tempo
        tempo = e[1][2]
        e[1][2] = e[2][1]
        e[2][1] = tempo
        # mmmult3(b,e,rot)
        rot[0][0] = b[0][0] * e[0][0] + b[1][0] * e[0][1] + b[2][0] * e[0][2]
        rot[0][1] = b[0][1] * e[0][0] + b[1][1] * e[0][1] + b[2][1] * e[0][2]
        rot[0][2] = b[0][2] * e[0][0] + b[1][2] * e[0][1] + b[2][2] * e[0][2]

        rot[1][0] = b[0][0] * e[1][0] + b[1][0] * e[1][1] + b[2][0] * e[1][2]
        rot[1][1] = b[0][1] * e[1][0] + b[1][1] * e[1][1] + b[2][1] * e[1][2]
        rot[1][2] = b[0][2] * e[1][0] + b[1][2] * e[1][1] + b[2][2] * e[1][2]

        rot[2][0] = b[0][0] * e[2][0] + b[1][0] * e[2][1] + b[2][0] * e[2][2]
        rot[2][1] = b[0][1] * e[2][0] + b[1][1] * e[2][1] + b[2][1] * e[2][2]
        rot[2][2] = b[0][2] * e[2][0] + b[1][2] * e[2][1] + b[2][2] * e[2][2]

        #
        # Compute translation vector trans:
        # mvmult3(rot,cy,cy);
        trans3 = [0, 0, 0]
        for i in range(3):
            trans3[i] = mobileCentroid[0]*rot[0][i] + mobileCentroid[1]*rot[1][i] + \
                        mobileCentroid[2]*rot[2][i]

        #bcopy(t3,cy,sizeof(t3));
        #vvdiff(cx,cy,trans);
        trans = (refCentroid[0] - trans3[0], refCentroid[1] - trans3[1],
                 refCentroid[2] - trans3[2])
        #
        #   That's it...

        self.rotationMatrix = rot
        self.translationMatrix = trans
        self.superimposed = 1
Example #55
0
    def asIndexedPolygons(self,
                          run=1,
                          quality=None,
                          centers=None,
                          radii=None,
                          **kw):
        if __debug__:
            if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
        """implement the sphere as an icosaedre.
run=0 returns 1 if this geom can be represented as an
IndexedPolygon and None if not. run=1 returns the IndexedPolygon object.
"""

        #print "Spheres.asIndexedPolygons", quality
        if run == 0:
            return 1  # yes, I can be represented as IndexedPolygons

        if quality in [1, 2, 3, 4, 5]:
            quality = quality
        elif quality < 0 and self.quality in [2, 3, 4, 5]:
            quality = self.quality - 2
        else:
            quality = self.quality - 1

        # get centers
        if centers is None:
            centers = self.vertexSet.vertices.array

        # get radii
        if radii is None:
            if self.oneRadius == viewerConst.NO:
                radii = self.vertexSet.radii.array
            else:
                radii = Numeric.ones(centers.shape[0]) * self.radius

        # create template sphere
        S = TriangulateIcosByEdgeCenterPoint(quality=quality)
        tmpltVertices = S.getVertices(quality=quality)
        tmpltFaces = S.getFaces(quality=quality)
        tmpltNormals = S.getVNormals(quality=quality)

        # these lists will store the data for the new spheres
        vertices = []
        faces = []
        normals = []

        # loop over spheres
        for i in range(len(centers)):
            vert = Numeric.array(tmpltVertices[:]) * radii[i] + centers[i]
            vertices.extend(list(vert))
            fac = Numeric.array(tmpltFaces[:]) + i * len(tmpltVertices)
            faces.extend(list(fac))
            norm = Numeric.array(tmpltNormals[:])
            normals.extend(list(norm))

        sphGeom = IndexedPolygons("sph",
                                  vertices=Numeric.array(vertices),
                                  faces=faces,
                                  vnormals=Numeric.array(normals),
                                  visible=1,
                                  invertNormals=self.invertNormals)

        # copy Spheres materials into sphGeom
        matF = self.materials[GL.GL_FRONT]
        matB = self.materials[GL.GL_BACK]
        sphGeom.materials[GL.GL_FRONT].binding = matF.binding[:]
        sphGeom.materials[GL.GL_FRONT].prop = matF.prop[:]
        sphGeom.materials[GL.GL_BACK].binding = matB.binding[:]
        sphGeom.materials[GL.GL_BACK].prop = matB.prop[:]

        if sphGeom.materials[GL.GL_FRONT].binding[1] == viewerConst.PER_VERTEX:
            newprop = []
            index = 0
            cnt = 0
            for i in range(len(vertices)):
                newprop.append(sphGeom.materials[GL.GL_FRONT].prop[1][index])
                cnt = cnt + 1
                if cnt == len(tmpltVertices):
                    index = index + 1
                    cnt = 0

            sphGeom.materials[GL.GL_FRONT].prop[1] = newprop

        #print "Spheres.asIndexedPolygons out", quality
        return sphGeom
Example #56
0
def dist(c1, c2):
    d = Numeric.array(c2) - Numeric.array(c1)
    ans = math.sqrt(Numeric.sum(d * d))
    return round(ans, 3)
Example #57
0
import sys
sys.path.append("/Users/jonathanxavier/Developer/sim42")
from numpy.oldnumeric import power, array
from ollin.Tools.tools import lagrange
##kk=
xx = array([
    0.021816, 0.614, 0.13974, 0.076043, 0.015103, 0.026015, 0.028254, 0.079035
])
yy = array([
    0.012954, 0.8885, 0.069839, 0.01834, 0.002254, 0.0031603, 0.0018852,
    0.0030934
])
z = [0.0139, 0.8592, 0.0773, 0.0245, 0.0036, 0.0056, 0.0047, 0.0112]

ki = yy / xx  #array([ 5.85789009,2.99441671,1.58239488,0.88726921,0.51283227])
zi = z  #[0.05,0.15,0.25,0.20,0.35]

F1 = sum(ki * zi) - 1
F2 = 2 * sum((ki - 1) * zi / (1 + ki))
F = F2 / (F2 - F1)
F3 = 2 * sum(zi / (1 + ki))
F4 = sum(zi / ki) - 1
fra = (F4 - 0.5 * F4) / (F3 - F4)
print F1, F2, F, F3, F4, fra

fr = 0.4
xx = array([
    0.021816, 0.614, 0.13974, 0.076043, 0.015103, 0.026015, 0.028254, 0.079035
])
yy = array([
    0.012954, 0.8885, 0.069839, 0.01834, 0.002254, 0.0031603, 0.0018852,
Example #58
0
 def cast(self, data):
     try:
         data = Numeric.array(data)
         return True, data
     except:
         return False, data
Example #59
0
def V(*v):
    return Numeric.array(v, Numeric.Float)
Example #60
0
    def Draw(self):
        if __debug__:
            if hasattr(DejaVu, 'functionName'): DejaVu.functionName()
        """Draw function of the geom
return status 0 or 1
If you want fast rendering, you need to set self.templateDSPL
using MakeTemplate.
"""
        #print "Spheres.Draw", self.name

        assert self.templateDSPL is not None

        currentcontext = self.viewer.currentCamera.tk.call(
            self.viewer.currentCamera._w, 'contexttag')
        if currentcontext != self.templateDSPL[1]:
            import traceback
            traceback.print_stack()
            warnings.warn(
                """draw failed because the current context is the wrong one""")
            #print "currentcontext != self.templateDSPL[1]", currentcontext, self.templateDSPL[1]
            return 0

        centers = self.vertexSet.vertices.array
        if len(centers) == 0:
            return 0

        # handle overall binding of material
        if self.inheritMaterial:
            fp = None
            fpProp = None
            bp = None
        else:
            mat = self.materials[GL.GL_FRONT]
            fpProp = []
            for propInd in range(4):
                b, p = mat.GetProperty(propInd)
                fpProp.append(p)
            fpProp.append(mat.prop[4])

            fp = self.materials[GL.GL_FRONT]
            #colorFront = Numeric.array(self.materials[GL.GL_FRONT].prop[1], copy=1)
            colorFront = Numeric.array(fpProp[1], copy=1)
            if self.frontAndBack:
                bp = None
                face = GL.GL_FRONT_AND_BACK
            else:
                bp = self.materials[GL.GL_BACK]
                face = GL.GL_FRONT

        if fp:
            for m in (0, 1, 2, 3, 4):
                if fp.binding[m] == viewerConst.OVERALL:
                    glMaterialWithCheck(face, viewerConst.propConst[m],
                                        fpProp[m][0])
            if fp.binding[1] == viewerConst.OVERALL:
                GL.glColor4fv(colorFront[0])

            if fp:
                for m in (0, 1, 2, 3, 4):
                    if fp.binding[m] != viewerConst.OVERALL:
                        glMaterialWithCheck(face, viewerConst.propConst[m],
                                            fpProp[m][0])

                if fp.binding[1] != viewerConst.OVERALL:
                    GL.glColor4fv(colorFront[0])
            if bp:
                for m in (0, 1, 2, 3, 4):
                    if bp.binding[m] != viewerConst.OVERALL:
                        glMaterialWithCheck(GL.GL_BACK,
                                            viewerConst.propConst[m],
                                            bp.prop[m][0])

        #print self.name
        #if fp: print fp.prop[1], fp.binding
        #else: print

        if self.fastSpheres:
            #print "self.fastSpheres", self.fastSpheres
            if self.oneRadius == viewerConst.NO:
                radii = self.vertexSet.radii.array
                #FIXME: quick fix because can be called from base class Set
                # method after centers have been set BUT before radii have been
                # set
                if len(self.vertexSet.vertices) != len(radii):
                    return 0
            else:
                radii = Numeric.ones(centers.shape[0]) * self.radius
            radii.shape = (-1, 1)
            coords = Numeric.concatenate((centers, radii), 1)

            ##             if not self.inheritMaterial:
            ##                 mat = self.materials[GL.GL_FRONT]
            ##                 fpProp = []
            ##                 for propInd in range(4):
            ##                     b, p = mat.GetProperty(propInd)
            ##                     fpProp.append(p)
            ##                 fpProp.append(mat.prop[4])
            ##                 #fpProp = self.materials[GL.GL_FRONT].prop[:5]
            ##             else:
            ##                 fpProp = None

            #print 'FUGU OVERWRITE COLOR', fpProp
            #import numpy
            #GL.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, numpy.array((.6,.6,.6,1), 'f'))
            #GL.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, numpy.array((1.,1.,1.,1), 'f'))
            #GL.glMaterialfv(GL.GL_FRONT, GL.GL_SPECULAR, numpy.array((.4,.4,.4,1), 'f'))
            #GL.glMaterialfv(GL.GL_FRONT, GL.GL_EMISSION, numpy.array((0,0,0,1), 'f'))
            #GL.glMaterialf(GL.GL_FRONT, GL.GL_SHININESS, 1.)

            status = glDrawSphereSet(
                self.templateDSPL[0],
                coords.astype('f'),
                fpProp,  #self.materials[GL.GL_FRONT].prop,
                highlight=self.highlight,
            )
            #print "Spheres, status: ", status
            return status
        else:
            resetMaterialMemory()
            #print "SLOW Spheres"
            if self.oneRadius == viewerConst.NO:
                radii = self.vertexSet.radii.array
            else:
                radii = Numeric.ones(centers.shape[0]) * self.radius

            if len(self.vertexSet.vertices) != len(radii):
                return 0

            for i in xrange(centers.shape[0]):
                GL.glPushName(i)
                GL.glPushMatrix()
                GL.glTranslatef(float(centers[i][0]), float(centers[i][1]),
                                float(centers[i][2]))
                if not self.oneRadius:
                    GL.glScalef(float(radii[i]), float(radii[i]),
                                float(radii[i]))
                else:
                    GL.glScalef(float(self.radius), float(self.radius),
                                float(self.radius))
                #print '#%d'%self.templateDSPL[0], "glCallList Spheres0"
                if fp:
                    for m in (0, 1, 2, 3, 4):
                        if fp.binding[m] != viewerConst.OVERALL:
                            glMaterialWithCheck(face,
                                                viewerConst.propConst[m],
                                                fp.prop[m][0],
                                                geom=self)
                GL.glCallList(self.templateDSPL[0])
                GL.glPopMatrix()
                GL.glPopName()
            return 1