def dS(self, Z, dadT, b, B, R, T): """ This calculate the residual Entropy (Z,dadT,b,B,R,T)->dA)""" u = self.u w = self.w L = log((2 * Z - B * (u - sqrt(u * u - 4 * w))) / (2 * Z + B * (u - sqrt(u * u - 4 * w)))) return R * log(Z - B) - dadT / (b * sqrt(u * u - 4 * w)) * L
def dA(self, Z, a, b, B, R, T): """ This calculate the residual helmozt energy (Z,a,b,B,R,T)->dA)""" u = self.u w = self.w L = log((2 * Z - B * (u - sqrt(u * u - 4 * w))) / (2 * Z + B * (u - sqrt(u * u - 4 * w)))) return a / (b * sqrt(u * u - 4 * w)) * L - R * T * log(Z - B)
def pairwiseRmsd( self, aMask=None, noFit=0 ): """ Calculate rmsd between each 2 coordinate frames. @param aMask: atom mask @type aMask: [1|0] @return: frames x frames array of float @rtype: array """ frames = self.frames if aMask != None: frames = N.compress( aMask, frames, 1 ) result = N.zeros( (len( frames ), len( frames )), N.Float32 ) for i in range(0, len( frames ) ): for j in range( i+1, len( frames ) ): if noFit: d = N.sqrt(N.sum(N.power(frames[i]-frames[j], 2), 1)) result[i,j] = result[j,i] = N.sqrt( N.average(d**2) ) else: rt, rmsdLst = rmsFit.match( frames[i], frames[j], 1 ) result[i,j] = result[j,i] = rmsdLst[0][1] return result
def _getinfo_TEST(self): # please leave in for debugging POV-Ray lmotor macro. mark 060324 a = self.axen() xrot = -atan2(a[1], sqrt(1-a[1]*a[1]))*180/pi yrot = atan2(a[0], sqrt(1-a[0]*a[0]))*180/pi return "[Object: Linear Motor] [Name: " + str(self.name) + "] " + \ "[Force = " + str(self.force) + " pN] " + \ "[Stiffness = " + str(self.stiffness) + " N/m] " + \ "[Axis = " + str(self.axis[0]) + ", " + str(self.axis[1]) + ", " + str(self.axis[2]) + "]" + \ "[xRotation = " + str(xrot) + ", yRotation = " + str(yrot) + "]"
def norm (A): """ Return normalized vector A. """ if type(A) == types.ListType: A=Numeric.array(A,'f') res= A/Numeric.sqrt(Numeric.dot(A,A)) return res.tolist() elif type(A)==Numeric.ArrayType: return A/Numeric.sqrt(Numeric.dot(A,A)) else: print "Need a list or Numeric array" return None
def __init__(self, points, k, normalization=NORM_NORM_T0_1, force=False): """ calculate k polynomials of degree 0 to k-1 orthogonal on a set of distinct points map points to interval [-1,1] INPUT: points: array of dictinct points where polynomials are orthogonal k: number of polynomials of degree 0 to k-1 force=True creates basis even if orthogonality is not satisfied due to numerical error USES: x: array of points mapped to [-1,1] T_: matrix of values of polynomials calculated at x, shape (k,len(x)) TT_ = T_ * Numeric.transpose(T_) TTinv_ = inverse(TT_) sc_: scaling factors a, b: coefficients for calculating T (2k-4 different from 0, i.e. 6 for k=5) n: number of points = len(points) normalization = {0|1|2} """ self.k = k # number of basis polynomials of order 0 to k-1 self._force = force self.points = Numeric.asarray(points, Numeric.Float) self.pointsMin = min(points) self.pointsMax = max(points) # scaling x to [-1,1] results in smaller a and b, T is not affected; overflow is NOT a problem! self.xMin = -1 self.xMax = 1 self.x = self._map(self.points, self.pointsMin, self.pointsMax, self.xMin, self.xMax) # calculate basis polynomials self.n = len(points) # the number of approximation points t = Numeric.zeros((k,self.n),Numeric.Float) a = Numeric.zeros((k,1),Numeric.Float) b = Numeric.zeros((k,1),Numeric.Float) t[0,:] = Numeric.ones(self.n,Numeric.Float) if k > 1: t[1,:] = self.x - sum(self.x)/self.n for i in range(1,k-1): a[i+1] = Numeric.innerproduct(self.x, t[i,:] * t[i,:]) / Numeric.innerproduct(t[i,:],t[i,:]) b[i] = Numeric.innerproduct(t[i,:], t[i,:]) / Numeric.innerproduct(t[i-1,:],t[i-1,:]) t[i+1,:] = (self.x - a[i+1]) * t[i,:] - b[i] * t[i-1,:] self.a = a self.b = b # prepare for approximation self._T0 = t # orthonormal _TT0 = Numeric.matrixmultiply(self._T0, Numeric.transpose(self._T0)) self.sc1 = Numeric.sqrt(Numeric.reshape(Numeric.diagonal(_TT0),(self.k,1))) # scaling factors = sqrt sum squared self._T0 self._T1 = self._T0 / self.sc1 # orthonormal and T[0] == 1 self.sc2 = Numeric.sqrt(Numeric.reshape(Numeric.diagonal(_TT0),(self.k,1)) / self.n) # scaling factors = sqrt 1/n * sum squared self._T0 self._T2 = self._T0 / self.sc2 # T[:,-1] == 1 self.sc3 = Numeric.take(self._T0, (-1,), 1) # scaling factors = self._T0[:,-1] self._T3 = self._T0 / self.sc3 # set the variables according to the chosen normalization self.setNormalization(normalization)
def calc_sse_sse_midpoint_dist(sse1, sse2, pdb_struct): """ Calculate the midpoint distance between two SSEs (helices or strands, represented by PTNode objects). This distance is defined as the distance between the midpoints of the two SSE axes (as calculated by fit_axis() methods). Parameters: sse1 - PTNode representing one SSE sse2 - PTNode representing the other SSE pdb_struct - The Bio.PDB parsed PDB struct (atomic co-ordinates) for this protein. Return value: distance (Angstroms) between the midpoints of the axes fitted to each SSE; or None if no axis could be found. """ sse1_axis = sse1.fit_axis(pdb_struct) sse2_axis = sse2.fit_axis(pdb_struct) if sse1_axis == None or sse2_axis == None: return None (sse1_dircos, sse1_centroid) = sse1_axis (sse2_dircos, sse2_centroid) = sse2_axis diff_vector = sse1_centroid - sse2_centroid return Numeric.sqrt(Numeric.sum(diff_vector * diff_vector))
def calc_point_residue_dist(residue_one, point) : """Returns the distance between the C_alpha of a residue and a point. Paramters residue_one - Bio.PDB Residue object point - Bio.PDB Vector representatin of a point in 3d space Return value: distance in Angstroms between Carbon alpha atom of residue_one and point Uses globals (read/write): residue_errmsg_dict - map Residue to bool flagging error msg issued """ try: res1_ca_coord = residue_one["CA"].coord except KeyError: # this happens ocassionaly on some PDB files e.g. 1BRD if not residue_errmsg_dict.has_key(residue_one): sys.stderr.write('WARNING: no Carbon-alpha atom for residue ' + str(residue_one) + '\nDistance in matrix set to infinity\n') residue_errmsg_dict[residue_one] = True return float('inf') diff_vector = res1_ca_coord - point.get_array() # print 'debug pointresdist',res1_ca_coord,point.get_array(),diff_vector return Numeric.sqrt(Numeric.sum(diff_vector * diff_vector))
def projectOnSphere( xyz, radius=None, center=None ): """ Project the coordinates xyz on a sphere with a given radius around a given center. @param xyz: cartesian coordinates @type xyz: array N x 3 of float @param radius: radius of target sphere, if not provided the maximal distance to center will be used (default: None) @type radius: float @param center: center of the sphere, if not given the average of xyz will be assigned to the center (default: None) @type center: array 0 x 3 of float @return: array of cartesian coordinates (x, y, z) @rtype: array """ if center is None: center = N.average( xyz ) if radius is None: radius = max( N.sqrt( N.sum( N.power( xyz - center, 2 ), 1 ) ) ) rtp = cartesianToPolar( xyz - center ) rtp[ :, 0 ] = radius return polarToCartesian( rtp ) + center
def concentricrings(x, y, white_thickness, gaussian_width, spacing): """ Concetric rings with the solid ring-shaped region, then Gaussian fall-off at the edges. """ # To have zero value in middle point this pattern calculates zero-value rings instead of # the one-value ones. But to be consistent with the rest of functions the parameters # are connected to one-value rings - like half_thickness is now recalculated for zero-value ring: half_thickness = ((spacing-white_thickness)/2.0)*greater_equal(spacing-white_thickness,0.0) distance_from_origin = sqrt(x**2+y**2) distance_from_ring_middle = fmod(distance_from_origin,spacing) distance_from_ring_middle = minimum(distance_from_ring_middle,spacing - distance_from_ring_middle) distance_from_ring = distance_from_ring_middle - half_thickness ring = 0.0 + greater_equal(distance_from_ring,0.0) sigmasq = gaussian_width*gaussian_width with float_error_ignore(): falloff = exp(divide(-distance_from_ring*distance_from_ring, 2.0*sigmasq)) return maximum(falloff,ring)
def Zo(self, a, b): a = 2 * a c = pow(a, 2) - 12 * b ## print "cuadra",a,b,c ## print c if c < 0: return (0.05, 1.0) else: x1 = (a - sqrt(c)) / 6 x2 = (a + sqrt(c)) / 6 if x1 < 0: x1 = 1.0 if x2 < 0: x2 = 0.05 return (x1, x2)
def logConfidence( x, R, clip=0 ): """ Estimate the probability of x NOT beeing a random observation from a lognormal distribution that is described by a set of random values. @param x: observed value @type x: float @param R: sample of random values @type R: [float] @param clip: clip zeros at this value 0->don't clip (default: 0) @type clip: float @return: confidence that x is not random, median of random distr. @rtype: (float, float) """ if clip and 0 in R: R = N.clip( R, clip, max( R ) ) if clip and x == 0: x = clip ## remove 0 instead of clipping R = N.compress( R, R ) if x == 0: return 0, 0 ## get mean and stdv of log-transformed random sample alpha = N.average( N.log( R ) ) n = len( R ) beta = N.sqrt(N.sum(N.power(N.log( R ) - alpha, 2)) / (n - 1.)) return logArea( x, alpha, beta ), logMedian( alpha )
def function(self,params): """Archemidean spiral function.""" aspect_ratio = params['aspect_ratio'] x = self.pattern_x/aspect_ratio y = self.pattern_y thickness = params['thickness'] gaussian_width = params['smoothing'] size = params['size'] half_thickness = thickness/2.0 spacing = size*2*pi distance_from_origin = sqrt(x**2+y**2) distance_from_spiral_middle = fmod(spacing + distance_from_origin - size*arctan2(y,x),spacing) distance_from_spiral_middle = minimum(distance_from_spiral_middle,spacing - distance_from_spiral_middle) distance_from_spiral = distance_from_spiral_middle - half_thickness spiral = 1.0 - greater_equal(distance_from_spiral,0.0) sigmasq = gaussian_width*gaussian_width with float_error_ignore(): falloff = exp(divide(-distance_from_spiral*distance_from_spiral, 2.0*sigmasq)) return maximum(falloff, spiral)
def function(self,params): """Hyperbolic function.""" aspect_ratio = params['aspect_ratio'] x = self.pattern_x/aspect_ratio y = self.pattern_y thickness = params['thickness'] gaussian_width = params['smoothing'] size = params['size'] half_thickness = thickness / 2.0 distance_from_vertex_middle = fmod(sqrt(absolute(x**2 - y**2)),size) distance_from_vertex_middle = minimum(distance_from_vertex_middle,size - distance_from_vertex_middle) distance_from_vertex = distance_from_vertex_middle - half_thickness hyperbola = 1.0 - greater_equal(distance_from_vertex,0.0) sigmasq = gaussian_width*gaussian_width with float_error_ignore(): falloff = exp(divide(-distance_from_vertex*distance_from_vertex, 2.0*sigmasq)) return maximum(falloff, hyperbola)
def function(self,params): """Concentric rings.""" aspect_ratio = params['aspect_ratio'] x = self.pattern_x/aspect_ratio y = self.pattern_y thickness = params['thickness'] gaussian_width = params['smoothing'] size = params['size'] half_thickness = thickness / 2.0 distance_from_origin = sqrt(x**2+y**2) distance_from_ring_middle = fmod(distance_from_origin,size) distance_from_ring_middle = minimum(distance_from_ring_middle,size - distance_from_ring_middle) distance_from_ring = distance_from_ring_middle - half_thickness ring = 1.0 - greater_equal(distance_from_ring,0.0) sigmasq = gaussian_width*gaussian_width with float_error_ignore(): falloff = exp(divide(-distance_from_ring*distance_from_ring, 2.0*sigmasq)) return maximum(falloff, ring)
def init_diamond(): # a chunk of diamond grid, to be tiled out in 3d drawing_globals.sp0 = sp0 = 0.0 #bruce 051102 replaced 1.52 with this constant (1.544), # re bug 900 (partial fix.) drawing_globals.sp1 = sp1 = DIAMOND_BOND_LENGTH / sqrt(3.0) sp2 = 2.0*sp1 sp3 = 3.0*sp1 drawing_globals.sp4 = sp4 = 4.0*sp1 digrid=[[[sp0, sp0, sp0], [sp1, sp1, sp1]], [[sp1, sp1, sp1], [sp2, sp2, sp0]], [[sp2, sp2, sp0], [sp3, sp3, sp1]], [[sp3, sp3, sp1], [sp4, sp4, sp0]], [[sp2, sp0, sp2], [sp3, sp1, sp3]], [[sp3, sp1, sp3], [sp4, sp2, sp2]], [[sp2, sp0, sp2], [sp1, sp1, sp1]], [[sp1, sp1, sp1], [sp0, sp2, sp2]], [[sp0, sp2, sp2], [sp1, sp3, sp3]], [[sp1, sp3, sp3], [sp2, sp4, sp2]], [[sp2, sp4, sp2], [sp3, sp3, sp1]], [[sp3, sp3, sp1], [sp4, sp2, sp2]], [[sp4, sp0, sp4], [sp3, sp1, sp3]], [[sp3, sp1, sp3], [sp2, sp2, sp4]], [[sp2, sp2, sp4], [sp1, sp3, sp3]], [[sp1, sp3, sp3], [sp0, sp4, sp4]]] drawing_globals.digrid = A(digrid) drawing_globals.DiGridSp = sp4 return
def centerSurfDist( model, surf_mask, mask=None ): """ Calculate the longest and shortest distance from the center of the molecule to the surface. @param mask: atoms not to be considerd (default: None) @type mask: [1|0] @param surf_mask: atom surface mask, needed for minimum surface distance @type surf_mask: [1|0] @return: max distance, min distance @rtype: float, float """ if mask is None: mask = model.maskHeavy() ## calculate center of mass center = model.centerOfMass() ## surface atom coordinates surf_xyz = N.compress( mask*surf_mask, model.getXyz(), 0 ) ## find the atom closest and furthest away from center dist = N.sqrt( N.sum( (surf_xyz-center)**2 , 1 ) ) minDist = min(dist) maxDist = max(dist) return maxDist, minDist
def __init__(self): r22 = numerix.sqrt(2.)/2. uknots = [0., 0., 0., 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1., 1.,1.] cntrl = [[0., r22, 1., r22, 0., -r22, -1., -r22, 0.], [-1., -r22, 0., r22, 1., r22, 0., -r22, -1.], [0., 0., 0., 0., 0., 0., 0., 0., 0.], [1., r22, 1., r22, 1., r22, 1., r22, 1.]] Crv.__init__(self, cntrl, uknots)
def findQuaternionMatrix(collection, point_ref, conf1, conf2 = None, matrix = True ): universe = collection.universe() if conf1.universe != universe: raise ValueError, "conformation is for a different universe" if conf2 is None: conf1, conf2 = conf2, conf1 else: if conf2.universe != universe: raise ValueError, "conformation is for a different universe" ref = conf1 conf = conf2 weights = universe.masses() weights = weights/collection.mass() ref_cms = point_ref.position().array pos = N.zeros((3,), N.Float) pos = point_ref.position(conf).array possq = 0. cross = N.zeros((3, 3), N.Float) for a in collection.atomList(): r = a.position(conf).array - pos r_ref = a.position(ref).array-ref_cms w = weights[a] possq = possq + w*N.add.reduce(r*r) \ + w*N.add.reduce(r_ref*r_ref) cross = cross + w*r[:, N.NewAxis]*r_ref[N.NewAxis, :] k = N.zeros((4, 4), N.Float) k[0, 0] = -cross[0, 0]-cross[1, 1]-cross[2, 2] k[0, 1] = cross[1, 2]-cross[2, 1] k[0, 2] = cross[2, 0]-cross[0, 2] k[0, 3] = cross[0, 1]-cross[1, 0] k[1, 1] = -cross[0, 0]+cross[1, 1]+cross[2, 2] k[1, 2] = -cross[0, 1]-cross[1, 0] k[1, 3] = -cross[0, 2]-cross[2, 0] k[2, 2] = cross[0, 0]-cross[1, 1]+cross[2, 2] k[2, 3] = -cross[1, 2]-cross[2, 1] k[3, 3] = cross[0, 0]+cross[1, 1]-cross[2, 2] for i in range(1, 4): for j in range(i): k[i, j] = k[j, i] k = 2.*k for i in range(4): k[i, i] = k[i, i] + possq - N.add.reduce(pos*pos) import numpy.oldnumeric.linear_algebra as LinearAlgebra e, v = LinearAlgebra.eigenvectors(k) i = N.argmin(e) v = v[i] if v[0] < 0: v = -v if e[i] <= 0.: rms = 0. else: rms = N.sqrt(e[i]) if matrix: emax = N.argmax(e) QuatMatrix = v return Quaternion.Quaternion(QuatMatrix),v, e, e[i],e[emax], rms else: return Quaternion.Quaternion(v), Vector(ref_cms), Vector(pos), rms
def arc_by_radian(x, y, height, radian_range, thickness, gaussian_width): """ Radial arc with Gaussian fall-off after the solid ring-shaped region with the given thickness, with shape specified by the (start,end) radian_range. """ # Create a circular ring (copied from the ring function) radius = height/2.0 half_thickness = thickness/2.0 distance_from_origin = sqrt(x**2+y**2) distance_outside_outer_disk = distance_from_origin - radius - half_thickness distance_inside_inner_disk = radius - half_thickness - distance_from_origin ring = 1.0-bitwise_xor(greater_equal(distance_inside_inner_disk,0.0),greater_equal(distance_outside_outer_disk,0.0)) sigmasq = gaussian_width*gaussian_width if sigmasq==0.0: inner_falloff = x*0.0 outer_falloff = x*0.0 else: with float_error_ignore(): inner_falloff = exp(divide(-distance_inside_inner_disk*distance_inside_inner_disk, 2.0*sigmasq)) outer_falloff = exp(divide(-distance_outside_outer_disk*distance_outside_outer_disk, 2.0*sigmasq)) output_ring = maximum(inner_falloff,maximum(outer_falloff,ring)) # Calculate radians (in 4 phases) and cut according to the set range) # RZHACKALERT: # Function float_error_ignore() cannot catch the exception when # both dividend and divisor are 0.0, and when only divisor is 0.0 # it returns 'Inf' rather than 0.0. In x, y and # distance_from_origin, only one point in distance_from_origin can # be 0.0 (circle center) and in this point x and y must be 0.0 as # well. So here is a hack to avoid the 'invalid value encountered # in divide' error by turning 0.0 to 1e-5 in distance_from_origin. distance_from_origin += where(distance_from_origin == 0.0, 1e-5, 0) with float_error_ignore(): sines = divide(y, distance_from_origin) cosines = divide(x, distance_from_origin) arcsines = arcsin(sines) phase_1 = where(logical_and(sines >= 0, cosines >= 0), 2*pi-arcsines, 0) phase_2 = where(logical_and(sines >= 0, cosines < 0), pi+arcsines, 0) phase_3 = where(logical_and(sines < 0, cosines < 0), pi+arcsines, 0) phase_4 = where(logical_and(sines < 0, cosines >= 0), -arcsines, 0) arcsines = phase_1 + phase_2 + phase_3 + phase_4 if radian_range[0] <= radian_range[1]: return where(logical_and(arcsines >= radian_range[0], arcsines <= radian_range[1]), output_ring, 0.0) else: return where(logical_or(arcsines >= radian_range[0], arcsines <= radian_range[1]), output_ring, 0.0)
def angle(self, other): "Returns the angle to vector |other|." if not isVector(other): raise TypeError, "Angle between vector and non-vector" cosa = Numeric.add.reduce(self.array*other.array) / \ Numeric.sqrt(Numeric.add.reduce(self.array*self.array) * \ Numeric.add.reduce(other.array*other.array)) cosa = max(-1.,min(1.,cosa)) return Numeric.arccos(cosa)
def computeEndPointsFromChunk(self, chunk, update = True): """ Derives and returns the endpoints and radius of a Peptide chunk. @param chunk: a Peptide chunk @type chunk: Chunk @return: endPoint1, endPoint2 and radius @rtype: Point, Point and float @note: computing the endpoints works fine when n=m or m=0. Otherwise, the endpoints can be slightly off the central axis, especially if the Peptide is short. @attention: endPoint1 and endPoint2 may not be the original endpoints, and they may be flipped (opposites of) the original endpoints. """ # Since chunk.axis is not always one of the vectors chunk.evecs # (actually chunk.poly_evals_evecs_axis[2]), it's best to just use # the axis and center, then recompute a bounding cylinder. if not chunk.atoms: return None axis = chunk.axis axis = norm(axis) # needed center = chunk._get_center() points = chunk.atpos - center # not sure if basepos points are already centered # compare following Numeric Python code to findAtomUnderMouse and its caller matrix = matrix_putting_axis_at_z(axis) v = dot( points, matrix) # compute xy distances-squared between axis line and atom centers r_xy_2 = v[:,0]**2 + v[:,1]**2 # to get radius, take maximum -- not sure if max(r_xy_2) would use Numeric code, but this will for sure: i = argmax(r_xy_2) max_xy_2 = r_xy_2[i] radius = sqrt(max_xy_2) # to get limits along axis (since we won't assume center is centered between them), use min/max z: z = v[:,2] min_z = z[argmin(z)] max_z = z[argmax(z)] # Adjust the endpoints such that the ladder rungs (rings) will fall # on the ring segments. # TO DO: Fix drawPeptideLadder() to offset the first ring, then I can # remove this adjustment. --Mark 2008-04-12 z_adjust = self.getEndPointZOffset() min_z += z_adjust max_z -= z_adjust endpoint1 = center + min_z * axis endpoint2 = center + max_z * axis if update: #print "Original endpoints:", self.getEndPoints() self.setEndPoints(endpoint1, endpoint2) #print "New endpoints:", self.getEndPoints() return (endpoint1, endpoint2, radius)
def average(x, return_sd = 0): av = Numeric.sum(array(x)) / len(x) if return_sd: sd = standardDeviation(x, avg = av) / Numeric.sqrt(len(x)) return av, sd else: return av
def __init__(self, crv, pnt = [0., 0., 0.], vector = [1., 0., 0.], theta = 2.*math.pi): if not isinstance(crv, Crv.Crv): raise NURBSError, 'Parameter crv not derived from Crv class!' # Translate and rotate the curve into alignment with the z-axis T = translate(-numerix.asarray(pnt, numerix.Float)) # Normalize vector vector = numerix.asarray(vector, numerix.Float) len = numerix.sqrt(numerix.add.reduce(vector*vector)) if len == 0: raise ZeroDivisionError, "Can't normalize a zero-length vector" vector = vector/len if vector[0] == 0.: angx = 0. else: angx = math.atan2(vector[0], vector[2]) RY = roty(-angx) vectmp = numerix.ones((4,), numerix.Float) vectmp[0:3] = vector vectmp = numerix.dot(RY, vectmp) if vectmp[1] == 0.: angy = 0. else: angy = math.atan2(vector[1], vector[2]) RX = rotx(angy) crv.trans(numerix.dot(RX, numerix.dot(RY, T))) arc = Crv.Arc(1., [0., 0., 0.], 0., theta) narc = arc.cntrl.shape[1] ncrv = crv.cntrl.shape[1] coefs = numerix.zeros((4, narc, ncrv), numerix.Float) angle = numerix.arctan2(crv.cntrl[1,:], crv.cntrl[0,:]) vectmp = crv.cntrl[0:2,:] radius = numerix.sqrt(numerix.add.reduce(vectmp*vectmp)) for i in xrange(0, ncrv): coefs[:,:,i] = numerix.dot(rotz(angle[i]), numerix.dot(translate((0., 0., crv.cntrl[2,i])), numerix.dot(scale((radius[i], radius[i])), arc.cntrl))) coefs[3,:,i] = coefs[3,:,i] * crv.cntrl[3,i] Srf.__init__(self, coefs, arc.uknots, crv.uknots) T = translate(pnt) RX = rotx(-angy) RY = roty(angx) self.trans(numerix.dot(T, numerix.dot(RY, RX)))
def __str__(self): a= "<q:%6.2f @ " % (2.0 * math.acos(self.w) * 180 / math.pi) l = Numeric.sqrt(self.x**2 + self.y**2 + self.z**2) if l: z = V(self.x, self.y, self.z) / l a += "[%4.3f, %4.3f, %4.3f] " % (z[0], z[1], z[2]) else: a += "[%4.3f, %4.3f, %4.3f] " % (self.x, self.y, self.z) a += "|%8.6f|>" % vlen(self.vec) return a
def __init__(self, u, w): """ This help to develovep the server EOS(u,w)-> class""" self.u = u self.w = w self.delta = sqrt(power(u, 2) - 4 * w) self.Thermo = Thermo() self.name = str(self)
def logSigma( alpha, beta ): """ @param alpha: mean of log-transformed distribution @type alpha: float @param beta: standarddev of log-transformed distribution @type beta: float @return: 'standard deviation' of the original lognormal distribution @rtype: float """ return logMean( alpha, beta ) * N.sqrt( N.exp(beta**2) - 1.)
def hyperbola(x, y, thickness, gaussian_width, axis): """ Two conjugate hyperbolas with Gaussian fall-off which share the same asymptotes. abs(x^2/a^2 - y^2/b^2) = 1 As a = b = axis, these hyperbolas are rectangular. """ difference = absolute(x**2 - y**2) hyperbola = 1.0 - bitwise_xor(greater_equal(axis**2,difference),greater_equal(difference,(axis + thickness)**2)) distance_inside_hyperbola = sqrt(difference) - axis distance_outside_hyperbola = sqrt(difference) - axis - thickness sigmasq = gaussian_width*gaussian_width with float_error_ignore(): inner_falloff = exp(divide(-distance_inside_hyperbola*distance_inside_hyperbola, 2.0*sigmasq)) outer_falloff = exp(divide(-distance_outside_hyperbola*distance_outside_hyperbola, 2.0*sigmasq)) return maximum(hyperbola,maximum(inner_falloff,outer_falloff))
def distance_matrix(points): """return NxN point to point distance matrix this works but is not needed for USR """ points = N.array(points) num, dim = points.shape delta = N.zeros((num, num), "d") for d in xrange(dim): data = points[:, d] delta += (data - data[:, N.NewAxis]) ** 2 return N.sqrt(delta)
def exponential(x, y, xscale, yscale): """ Two-dimensional oriented exponential decay pattern. """ if xscale==0.0 or yscale==0.0: return x*0.0 with float_error_ignore(): x_w = divide(x,xscale) y_h = divide(y,yscale) return exp(-sqrt(x_w*x_w+y_h*y_h))
def disk(x, y, height, gaussian_width): """ Circular disk with Gaussian fall-off after the solid central region. """ disk_radius = height/2.0 distance_from_origin = sqrt(x**2+y**2) distance_outside_disk = distance_from_origin - disk_radius sigmasq = gaussian_width*gaussian_width if sigmasq==0.0: falloff = x*0.0 else: with float_error_ignore(): falloff = exp(divide(-distance_outside_disk*distance_outside_disk, 2*sigmasq)) return where(distance_outside_disk<=0,1.0,falloff)
def init_icos(): global icosa, icosix # the golden ratio global phi phi = (1.0+sqrt(5.0))/2.0 vert = norm(V(phi,0,1)) a = vert[0] b = vert[1] c = vert[2] # vertices of an icosahedron icosa = ((-a,b,c), (b,c,-a), (b,c,a), (a,b,-c), (-c,-a,b), (-c,a,b), (b,-c,a), (c,a,b), (b,-c,-a), (a,b,c), (c,-a,b), (-a,b,-c)) icosix = ((9, 2, 6), (1, 11, 5), (11, 1, 8), (0, 11, 4), (3, 1, 7), (3, 8, 1), (9, 3, 7), (0, 6, 2), (4, 10, 6), (1, 5, 7), (7, 5, 2), (8, 3, 10), (4, 11, 8), (9, 7, 2), (10, 9, 6), (0, 5, 11), (0, 2, 5), (8, 10, 4), (3, 9, 10), (6, 0, 4)) return
def pca(M): "Perform PCA on M, return eigenvectors and eigenvalues, sorted." T, N = shape(M) # if there are fewer rows T than columns N, use snapshot method if T < N: C = dot(M, t(M)) evals, evecsC = eigenvectors(C) # HACK: make sure evals are all positive evals = where(evals < 0, 0, evals) evecs = 1. / sqrt(evals) * dot(t(M), t(evecsC)) else: # calculate covariance matrix K = 1. / T * dot(t(M), M) evals, evecs = eigenvectors(K) # sort the eigenvalues and eigenvectors, descending order order = (argsort(evals)[::-1]) evecs = take(evecs, order, 1) evals = take(evals, order) return evals, t(evecs)
def calc_residue_dist(residue_one, residue_two): """Returns the C-alpha distance between two residues Paramters residue_one - Bio.PDB Residue object residue_two - Bio.PDB Residue object Return value: distance in Angstroms between Carbon alpha atoms of residue_one and residue_two Uses globals (read/write): residue_errmsg_dict - map Residue to bool flagging error msg issued Based on Peter C**k's Python programming pages: http://www2.warwick.ac.uk/fac/sci/moac/currentstudents/peter_cock/python/protein_contact_map/ but of course life is never quite that simple with PDB files... note this function is almost entirely error handling, only two lines actually do the calculation, everything else handles exceptions. """ try: res1_ca_coord = residue_one["CA"].coord except KeyError: # this happens ocassionaly on some PDB files e.g. 1BRD if not residue_errmsg_dict.has_key(residue_one): sys.stderr.write('WARNING: no Carbon-alpha atom for residue ' + str(residue_one) + '\nDistance in matrix set to infinity\n') residue_errmsg_dict[residue_one] = True return float('inf') try: res2_ca_coord = residue_two["CA"].coord except KeyError: if not residue_errmsg_dict.has_key(residue_two): sys.stderr.write('WARNING: no Carbon-alpha atom for residue ' + str(residue_two) + '. Distance in matrix set to infinity\n') residue_errmsg_dict[residue_two] = True return float('inf') diff_vector = res1_ca_coord - res2_ca_coord return Numeric.sqrt(Numeric.sum(diff_vector * diff_vector))
def pairwiseDistances(u, v): """ Pairwise distances between two arrays. @param u: first array @type u: array @param v: second array @type v: array @return: Numeric.array( len(u) x len(v) ) of double @rtype: array """ diag1 = N.diagonal(N.dot(u, N.transpose(u))) diag2 = N.diagonal(N.dot(v, N.transpose(v))) dist = -N.dot( v,N.transpose(u) )\ -N.transpose( N.dot( u, N.transpose(v) ) ) dist = N.transpose( N.asarray( map( lambda column,a:column+a, \ N.transpose(dist), diag1) ) ) return N.transpose( N.sqrt(N.asarray(map(lambda row, a: row + a, dist, diag2))))
def getFluct_global(self, mask=None): """ Get RMS of each atom from it's average position in trajectory. The frames should be superimposed (fit() ) to a reference. @param mask: N x 1 list/Numpy array of 0|1, (N=atoms), atoms to be considered. @type mask: [1|0] @return: Numpy array ( N_unmasked x 1 ) of float. @rtype: array """ frames = self.frames if mask is not None: frames = N.compress(mask, frames, 1) ## mean position of each atom in all frames avg = N.average(frames) return N.average(N.sqrt(N.sum(N.power(frames - avg, 2), 2)))
def cartesianToPolar(xyz): """ Convert cartesian coordinate array to polar coordinate array: C{ x,y,z -> r, S{theta}, S{phi} } @param xyz: array of cartesian coordinates (x, y, z) @type xyz: array @return: array of polar coordinates (r, theta, phi) @rtype: array """ r = N.sqrt(N.sum(xyz**2, 1)) p = N.arccos(xyz[:, 2] / r) ## have to take care of that we end up in the correct quadrant t = [] for i in range(len(xyz)): ## for theta (arctan) t += [math.atan2(xyz[i, 1], xyz[i, 0])] return N.transpose(N.concatenate(([r], [t], [p])))
def xyzOfNearestCovalentNeighbour(i, model): """ Closest atom in the same residue as atom with index i @param model: PDBModel @type model: PDBModel @param i: atom index @type i: int @return: coordinates of the nearest atom @rtype: [float, float, float] """ resModel = model.filter(residue_number=model.atoms['residue_number'][i]) dist = N.sqrt(N.sum((resModel.xyz - model.xyz[i])**2, 1)) ## set distance to self to something high dist[N.argmin(dist)] = 100. pos_shortest = N.nonzero(dist == min(dist))[0] return resModel.xyz[pos_shortest]
def rowDistances(x, y): """ Calculate the distances between the items of two arrays (of same shape) after least-squares superpositioning. @param x: first set of coordinates @type x: array('f') @param y: second set of coordinates @type y: array('f') @return: array( len(x), 'f' ), distance between x[i] and y[i] for all i @rtype: array """ ## find transformation for best match r, t = findTransformation(x, y) ## transform coordinates z = N.dot(y, N.transpose(r)) + t ## calculate row distances return N.sqrt(N.sum(N.power(x - z, 2), 1))
def scale(self): """ Return the maximum distance from self's geometric center to any point in self (i.e. the corner-center distance). Note: This is the radius of self's bounding sphere, which is as large as, and usually larger than, the bounding sphere of self's contents. Note: self's box dimensions are slightly larger than needed to enclose its data, due to hardcoded constants in its construction methods. [TODO: document, make optional] """ if not self.data: return 10.0 #x=1.2*maximum.reduce(subtract.reduce(self.data)) dd = 0.5 * subtract.reduce(self.data) # dd = halfwidths in each dimension (x,y,z) x = sqrt(dd[0] * dd[0] + dd[1] * dd[1] + dd[2] * dd[2]) # x = half-diameter of bounding sphere of self #return max(x, 2.0) return x
def rmsd_res(self, coord1, coord2): """ Calculate the rsmd on residue level for c-alpha between a model and its reference. @param coord1: first set of coordinates @type coord1: array @param coord2: second set of coordinates @type coord2: array @return: rmsd_res: rmsd per c-alpha @rtype: [float] """ rmsd_res = [] for i in range(len(coord1)): rmsd = N.sqrt( (N.power(coord1[i][0]-coord2[i][0],2) + \ N.power(coord1[i][1]-coord2[i][1],2 )+ \ N.power(coord1[i][2]-coord2[i][2],2 ))) rmsd_res.append(rmsd) return rmsd_res
def init_cube(): drawing_globals.cubeVertices = cubeVertices = [ [-1.0, 1.0, -1.0], [-1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, -1.0], [-1.0, -1.0, -1.0], [-1.0, -1.0, 1.0], [1.0, -1.0, 1.0], [1.0, -1.0, -1.0]] #bruce 051117: compute this rather than letting a subroutine hardcode it as # a redundant constant flatCubeVertices = [] for threemore in cubeVertices: flatCubeVertices.extend(threemore) flatCubeVertices = list(flatCubeVertices) #k probably not needed drawing_globals.flatCubeVertices = flatCubeVertices if 1: # remove this when it works flatCubeVertices_hardcoded = [-1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0] assert flatCubeVertices == flatCubeVertices_hardcoded sq3 = sqrt(3.0)/3.0 drawing_globals.cubeNormals = [ [-sq3, sq3, -sq3], [-sq3, sq3, sq3], [sq3, sq3, sq3], [sq3, sq3, -sq3], [-sq3, -sq3, -sq3], [-sq3, -sq3, sq3], [sq3, -sq3, sq3], [sq3, -sq3, -sq3]] drawing_globals.cubeIndices = [ [0, 1, 2, 3], [0, 4, 5, 1], [1, 5, 6, 2], [2, 6, 7, 3], [0, 3, 7, 4], [4, 7, 6, 5]] return
def logConfidence(x, R, clip=1e-32): """ Estimate the probability of x NOT beeing a random observation from a lognormal distribution that is described by a set of random values. The exact solution to this problem is in L{Biskit.Statistics.lognormal}. @param x: observed value @type x: float @param R: sample of random values; 0 -> don't clip (default: 1e-32) @type R: [float] @param clip: clip zeros at this value @type clip: float @return: confidence that x is not random, mean of random distrib. @rtype: (float, float) """ if clip and 0 in R: R = N.clip(R, clip, max(R)) ## get mean and stdv of log-transformed random sample mean = N.average(N.log(R)) n = len(R) stdv = N.sqrt(N.sum(N.power(N.log(R) - mean, 2)) / (n - 1.)) ## create dense lognormal distribution representing the random sample stop = max(R) * 50.0 step = stop / 100000 start = step / 10.0 X = [(v, p_lognormal(v, mean, stdv)) for v in N.arange(start, stop, step)] ## analyse distribution d = Density(X) return d.findConfidenceInterval(x * 1.0)[0], d.average()
def ring(x, y, height, thickness, gaussian_width): """ Circular ring (annulus) with Gaussian fall-off after the solid ring-shaped region. """ radius = height/2.0 half_thickness = thickness/2.0 distance_from_origin = sqrt(x**2+y**2) distance_outside_outer_disk = distance_from_origin - radius - half_thickness distance_inside_inner_disk = radius - half_thickness - distance_from_origin ring = 1.0-bitwise_xor(greater_equal(distance_inside_inner_disk,0.0),greater_equal(distance_outside_outer_disk,0.0)) sigmasq = gaussian_width*gaussian_width if sigmasq==0.0: inner_falloff = x*0.0 outer_falloff = x*0.0 else: with float_error_ignore(): inner_falloff = exp(divide(-distance_inside_inner_disk*distance_inside_inner_disk, 2.0*sigmasq)) outer_falloff = exp(divide(-distance_outside_outer_disk*distance_outside_outer_disk, 2.0*sigmasq)) return maximum(inner_falloff,maximum(outer_falloff,ring))
def findHandles_exact(self, p1, p2, cutoff = 0.0, backs_ok = 1, offset = V(0,0,0)): """ @return: a list of (dist, handle) pairs, in arbitrary order, which includes, for each handle (spherical surface) hit by the ray p1 thru p2, its front-surface intersection with the ray, unless that has dist < cutoff and backs_ok, in which case include its back-surface intersection (unless *that* has dist < cutoff). """ #e For now, just be simple, don't worry about speed. # Someday we can preprocess self.handlpos using Numeric functions, # like in nearSinglets and/or findSinglets # (I have untested prototype code for this in extrude-outs.py). hh = self.handles res = [] v = norm(p2-p1) # is this modifying the vector in-place, causing a bug?? ## offset += self.origin # treat our handles' pos as relative to this # I don't know, but one of the three instances of += was doing this!!! # probably i was resetting the atom or mol pos.... offset = offset + self.origin # treat our handles' pos as relative to this radius_multiplier = self.radius_multiplier for (pos,radius,info) in hh: ## bug in this? pos += offset pos = pos + offset radius *= radius_multiplier dist, wid = orthodist(p1, v, pos) if radius >= wid: # the ray hits the sphere delta = sqrt(radius*radius - wid*wid) front = dist - delta # depth p1 of front surface of sphere, where it's hit if front >= cutoff: res.append((front,(pos,radius,info))) elif backs_ok: back = dist + delta if back >= cutoff: res.append((back,(pos,radius,info))) return res
def d2adT2(self, ac, T): return 3 * ac / (4 * T * T * sqrt(T))
def estimate_reference_single(entry, stats, bounds, ref=0.0, verbose=False, exclude=None, entry_name=None, atom_type='H', exclude_outliers=False,molType='protein'): A = 0. B = 0. S = 0. N = 1 ## loop through all atom types classes = decompose_classes(entry, bounds, atom_type,molType=molType) if exclude and not entry_name: raise TypeError, 'attribute entry_name needs to be set.' n_excluded = 0 n_total = 0 for key, shifts in classes.items(): ## print entry_name, key if not key in stats: if verbose: print key,'no statistics.' continue if exclude and (entry_name, key) in exclude: print entry_name, key, 'excluded from ref estimation.' continue ## get statistics for current atom type mu, sd = stats[key][:2] k = 1./sd**2 if exclude_outliers is not False: ## calculate Z scores and exclude shifts with high Z scores from analysis Z = abs(shifts-mu)/sd mask_include = Numeric.less(Z, exclude_outliers) shifts = Numeric.compress(mask_include, shifts) n_excluded += len(Z)-Numeric.sum(mask_include) n_total += len(Z) n = len(shifts) if not n: continue A += k*n*(median(shifts)-mu) B += k*n S += -0.5*len(shifts)*Numeric.log(k)+0.5*k*sum((Numeric.array(shifts)-mu-ref)**2) N += n if B > 0.: ref_mu = A/B ref_sd = 1./Numeric.sqrt(B) else: ref_mu = None ref_sd = None if exclude_outliers is not False and n_excluded == n_total: print '%d/%d outliers discarded' % (n_excluded, n_total) return ref_mu, ref_sd, S/N
def length(self): "Returns the length (norm)." return Numeric.sqrt(Numeric.add.reduce(self.array * self.array))
def mat_to_quat(matrix, transpose=1): """ takes a four by four matrix (optionally with shape (16,) and converts it into the axis of rotation and angle to rotate by (x,y,z,theta). It does not expect an OpenGL style, transposed matrix, so is consistent with rotax """ if N.shape(matrix) not in ((16, ), (4, 4)): raise ValueError("Argument must Numeric array of shape (4,4) or (16,)") if N.shape(matrix) == (4, 4): matrix = N.reshape(matrix, (16, )) cofactor1 = matrix[5] * matrix[10] - matrix[9] * matrix[6] cofactor2 = matrix[8] * matrix[6] - matrix[4] * matrix[10] cofactor3 = matrix[4] * matrix[9] - matrix[8] * matrix[5] det = matrix[0] * cofactor1 + matrix[1] * cofactor2 + matrix[2] * cofactor3 if not (0.999 < det < 1.001): print "Not a unit matrix: so not a pure rotation" print 'Value of Determinant is: ', det trace = matrix[0] + matrix[5] + matrix[10] + matrix[15] if trace > 0.0000001: # rotation other than 180deg S = 0.5 / sqrt(trace) Qw = 0.25 / S Qx = (matrix[9] - matrix[6]) * S Qy = (matrix[2] - matrix[8]) * S Qz = (matrix[4] - matrix[1]) * S else: #180deg rotation, just need to figure out the axis Qw = 0. diagonal = ((matrix[0], 0), (matrix[5], 5), (matrix[10], 10)) idx = max(diagonal)[1] if idx == 0: S = sqrt(1.0 + matrix[0] - matrix[5] - matrix[10]) * 2 Qy = (matrix[1] + matrix[4]) / S Qz = (matrix[2] + matrix[8]) / S Qx = N.sqrt(1 - Qy * Qy - Qz * Qz) elif idx == 5: S = sqrt(1.0 + matrix[5] - matrix[0] - matrix[10]) * 2 Qx = (matrix[1] + matrix[4]) / S Qz = (matrix[6] + matrix[9]) / S Qy = N.sqrt(1 - Qx * Qx - Qz * Qz) elif idx == 10: S = sqrt(1.0 + matrix[10] - matrix[0] - matrix[5]) * 2 Qx = (matrix[2] + matrix[8]) / S Qy = (matrix[6] + matrix[9]) / S Qz = N.sqrt(1 - Qx * Qx - Qy * Qy) # check if identity or not if Qw != 1.: angle = N.arccos(Qw) theta = angle * 360. / N.pi Z = sqrt(Qx * Qx + Qy * Qy + Qz * Qz) if transpose: Qx = -Qx / Z Qy = -Qy / Z Qz = -Qz / Z else: Qx = Qx / Z Qy = Qy / Z Qz = Qz / Z Qw = theta return [Qx, Qy, Qz, Qw] else: return [0., 0., 0., 0.]
def addInternal(self, i, na, nb, nc, r, theta, phi): """ Add another point, given its internal coordinates. Once added via this routine, the cartesian coordinates for the point can be retrieved with getCartesian(). @param i: Index of the point being added. After this call, a call to getCartesian with this index value will succeed. Index values less than 4 are ignored. Index values should be presented here in sequence beginning with 4. @param na: Index value for point A. Point 'i' will be 'r' distance units from point A. @param nb: Index value for point B. Point 'i' will be located such that the angle i-A-B is 'theta' degrees. @param nc: Index value for point C. Point 'i' will be located such that the torsion angle i-A-B-C is 'torsion' degrees. @param r: Radial distance (in same units as resulting cartesian coordinates) between A and i. @param theta: Angle in degrees of i-A-B. @param phi: Torsion angle in degrees of i-A-B-C """ if (i < 4): return if (i != self._nextIndex): raise IndexError, "next index is %d not %r" % (self._nextIndex, i) cos_theta = cos(DEG2RAD * theta) xb = self._coords[nb][0] - self._coords[na][0] yb = self._coords[nb][1] - self._coords[na][1] zb = self._coords[nb][2] - self._coords[na][2] rba = 1.0 / sqrt(xb * xb + yb * yb + zb * zb) if abs(cos_theta) >= 0.999: # Linear case # Skip angles, just extend along A-B. rba = r * rba * cos_theta xqd = xb * rba yqd = yb * rba zqd = zb * rba else: xc = self._coords[nc][0] - self._coords[na][0] yc = self._coords[nc][1] - self._coords[na][1] zc = self._coords[nc][2] - self._coords[na][2] xyb = sqrt(xb * xb + yb * yb) inv = False if xyb < 0.001: # A-B points along the z axis. tmp = zc zc = -xc xc = tmp tmp = zb zb = -xb xb = tmp xyb = sqrt(xb * xb + yb * yb) inv = True costh = xb / xyb sinth = yb / xyb xpc = xc * costh + yc * sinth ypc = yc * costh - xc * sinth sinph = zb * rba cosph = sqrt(abs(1.0 - sinph * sinph)) xqa = xpc * cosph + zc * sinph zqa = zc * cosph - xpc * sinph yzc = sqrt(ypc * ypc + zqa * zqa) if yzc < 1e-8: coskh = 1.0 sinkh = 0.0 else: coskh = ypc / yzc sinkh = zqa / yzc sin_theta = sin(DEG2RAD * theta) sin_phi = -sin(DEG2RAD * phi) cos_phi = cos(DEG2RAD * phi) # Apply the bond length. xd = r * cos_theta yd = r * sin_theta * cos_phi zd = r * sin_theta * sin_phi # Compute the atom position using bond and torsional angles. ypd = yd * coskh - zd * sinkh zpd = zd * coskh + yd * sinkh xpd = xd * cosph - zpd * sinph zqd = zpd * cosph + xd * sinph xqd = xpd * costh - ypd * sinth yqd = ypd * costh + xpd * sinth if inv: tmp = -zqd zqd = xqd xqd = tmp self._coords[i][0] = xqd + self._coords[na][0] self._coords[i][1] = yqd + self._coords[na][1] self._coords[i][2] = zqd + self._coords[na][2] self._nextIndex = self._nextIndex + 1
def SRK(model, case): R = 0.08206 ## xm = case.ExtProp["x"] yf = case.ExtProp["yf"] xf = case.ExtProp["xf"] pv = case.ExtProp["pv"] FrVap = case.ExtProp["FracVap"] T = case.ExtProp["T"] P = case.ExtProp["P"] Ac = model.Const["SRK_A"] b_i = model.Const["RK_B"] W_i = model.Const["OMEGA"] TC_i = model.Const["TC"] ## print "Ac",Ac,b_i fwi = 0.48 + 0.1574 * W_i - 0.176 * power(W_i, 2) Tr_i = T / TC_i ## print Tr_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) ## print "AiBi",A_i,B_i Zl_i = SRK.ZL(A_i, B_i) Zv_i = SRK.ZG(A_i, B_i) print "z", Zl_i, Zv_i CoeFugo_v = CoeFugo(Zv_i, A_i, B_i) CoeFugo_l = CoeFugo(Zl_i, A_i, B_i) #print CoeFugo_v/CoeFugo_l for i in range(3): A_vi = MixingRules.MolarK2(yf, A_i, k=0.5) B_vi = MixingRules.Molar(yf, B_i) A_li = MixingRules.MolarK2(xf, A_i, k=0.5) B_li = MixingRules.Molar(xf, B_i) B_v = MixingRules.Molar(yf, B_i) A_v = MixingRules.MolarK(yf, A_i, k=0.5) B_l = MixingRules.Molar(xf, B_i) A_l = MixingRules.MolarK(xf, A_i, k=0.5) Z_v = SRK.ZG(A_v, B_v) Z_l = SRK.ZL(A_l, B_l) CoeFugM_v = SRK.FugMix(Z_v, A_i, B_i, A_v, B_v) CoeFugM_l = SRK.FugMix(Z_l, A_i, 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 print CoeFugM_v, "\n", ki, "\n", FrVap, "\n", xf, "\n", yf, "\n", CoeFugM_l, "\n", Z_v, Z_l
def standardDeviation(x, avg=None): return Numeric.sqrt(variance(x, avg))
def Isotermicx(self, model, case): yf = case.Prop["yf"] T = case.Prop["T"] P = case.Prop["P"] Ac = model["RK_A"] b_i = model["RK_B"] case.Prop["dadT"] = self.dadT(Ac, T) case.Prop["d2adT2"] = self.d2adT2(Ac, T) ## case.Prop["MolWt"] = sum( xm* model["MoleWt"] ) PreVap = self.PV.P(T, model) case.Prop["PreVap"] = PreVap AlphaT = 1 / sqrt(T) case.Prop["AlphaT"] = AlphaT a_i = Ac * AlphaT case.Prop["a"] = a_i A_i = (a_i * P) / pow(R * T, 2) B_i = (b_i * P) / (R * T) case.Prop["A"] = A_i case.Prop["B"] = B_i Zl_i = self.EOS.ZL(A_i, B_i) Zv_i = self.EOS.ZG(A_i, B_i) case.Prop["Zli"] = Zl_i case.Prop["Zvi"] = Zv_i case.Prop["Vli"] = Zl_i * R * T / P case.Prop["Vvi"] = Zv_i * R * T / P CoeFugo_v = self.FugaP(Zv_i, A_i, B_i) CoeFugo_l = self.FugaP(Zl_i, A_i, B_i) ## yf = xm xf = yf / (PreVap / P) sk = sum(PreVap / P) B_v = MixingRules.Molar(yf, B_i) A_v = power(sum(yf * sqrt(A_i)), 2) Z_v = self.EOS.ZG(A_v, B_v) CoeFugM_v = self.FugaM(Z_v, A_i, B_i, A_v, B_v) k_i = 1 RFrac = 2 ## FrVap, xf, yf = Flash(PreVap/P,xm) #Iteration to calculate the Fractio Vapor while k_i <= 10: B_l = MixingRules.Molar(xf, B_i) A_l = power(sum(xf * sqrt(A_i)), 2) Z_l = self.EOS.ZL(A_l, B_l) CoeFugM_l = self.FugaM(Z_l, A_i, B_i, A_l, B_l) fi = P * CoeFugM_v * yf ki = CoeFugM_l / CoeFugM_v ## Z = FrVap*Z_v + (1- FrVap)* Z_l if abs(sk - sum(ki)) <= 1e-8: print xf ## case.Solve = 1 break xf = yf / ki sk = sum(ki) k_i += 1 FrVap, xm = Flash(ki, x=xf, y=yf) print "Frac", FrVap Z = FrVap * Z_v + (1 - FrVap) * Z_l V_l = Z_l * R * T / P V_v = Z_v * R * T / P
def hbonds(model): """ Collect a list with all potential hydrogen bonds in model. @param model: PDBModel for which @type model: PDBModel @return: a list of potential hydrogen bonds containing a lists with donor index, acceptor index, distance and angle. @rtype: [ int, int, float, float ] """ hbond_lst = [] donors = molU.hbonds['donors'] accept = molU.hbonds['acceptors'] ## indices if potential donors d_ind = [] for res, aList in donors.items(): for a in aList: if a in molU.hydrogenSynonyms.keys(): aList.append(molU.hydrogenSynonyms[a]) d_ind += model.filterIndex(residue_name=res, name=aList) ## indices if potential acceptors a_ind = [] for res, aList in accept.items(): a_ind += model.filterIndex(residue_name=res, name=aList) ## calculate pairwise distances and angles for d in d_ind: d_xyz = model.xyz[d] d_nr = model.atoms['residue_number'][d] d_cid = model.atoms['chain_id'][d] d_segi = model.atoms['segment_id'][d] for a in a_ind: a_xyz = model.xyz[a] a_nr = model.atoms['residue_number'][a] a_cid = model.atoms['chain_id'][a] a_segi = model.atoms['segment_id'][a] dist = N.sqrt(sum((d_xyz - a_xyz)**2)) ## don't calculate angles within the same residue and ## for distances definately are not are h-bonds if dist < 3.0 and not\ ( d_nr == a_nr and d_cid == a_cid and d_segi == a_segi ): ## calculate angle for potenital hbond d_xyz_cov = xyzOfNearestCovalentNeighbour(d, model) a_xyz_cov = xyzOfNearestCovalentNeighbour(a, model) d_vec = d_xyz_cov - d_xyz a_vec = a_xyz - a_xyz_cov d_len = N.sqrt(sum((d_vec)**2)) a_len = N.sqrt(sum((a_vec)**2)) da_dot = N.dot(d_vec, a_vec) angle = 180 - N.arccos(da_dot / (d_len * a_len)) * 180 / N.pi if hbondCheck(angle, dist): hbond_lst += [[d, a, dist, angle]] return hbond_lst
def normal(self): "Returns a normalized copy." len = Numeric.sqrt(Numeric.add.reduce(self.array * self.array)) if len == 0: raise ZeroDivisionError, "Can't normalize a zero-length vector" return Vector(Numeric.divide(self.array, len))
def Isotermic(self, model, case): xm = case.Prop["x"] T = case.Prop["T"] P = case.Prop["P"] Ac = model["RK_A"] b_i = model["RK_B"] case.Prop["dadT"] = self.dadT(Ac, T) case.Prop["d2adT2"] = self.d2adT2(Ac, T) case.Prop["MolWt"] = sum(xm * model["MoleWt"]) PreVap = self.PV.P(T, model) case.Prop["PreVap"] = PreVap AlphaT = 1 / sqrt(T) case.Prop["AlphaT"] = AlphaT a_i = Ac * AlphaT case.Prop["a"] = a_i A_i = (a_i * P) / pow(R * T, 2) B_i = (b_i * P) / (R * T) case.Prop["A"] = A_i case.Prop["B"] = B_i Zl_i = self.EOS.ZL(A_i, B_i) Zv_i = self.EOS.ZG(A_i, B_i) case.Prop["Zli"] = Zl_i case.Prop["Zvi"] = Zv_i case.Prop["Vli"] = Zl_i * R * T / P case.Prop["Vvi"] = Zv_i * R * T / P CoeFugo_v = self.FugaP(Zv_i, A_i, B_i) CoeFugo_l = self.FugaP(Zl_i, A_i, B_i) yf = xm xf = xm k_i = 1 RFrac = 2 FrVap, xf, yf = Flash(case.Prop["PreVap"] / P, xm) #Iteration to calculate the Fractio Vapor while k_i <= 10: B_v = MixingRules.Molar(yf, B_i) A_v = power(sum(yf * sqrt(A_i)), 2) B_l = MixingRules.Molar(xf, B_i) A_l = power(sum(xf * sqrt(A_i)), 2) 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_i, B_i, A_v, B_v) CoeFugM_l = self.FugaM(Z_l, A_i, B_i, A_l, B_l) fi = P * CoeFugM_v * yf ki = CoeFugM_l / CoeFugM_v FrVap, xf, yf = Flash(ki, xm) Z = FrVap * Z_v + (1 - FrVap) * Z_l if abs(RFrac - FrVap) <= 1e-10: case.Solve = 1 break RFrac = FrVap k_i += 1
def arc_by_radian(x, y, height, radian_range, thickness, gaussian_width): """ Radial arc with Gaussian fall-off after the solid ring-shaped region with the given thickness, with shape specified by the (start,end) radian_range. """ # Create a circular ring (copied from the ring function) radius = height / 2.0 half_thickness = thickness / 2.0 distance_from_origin = sqrt(x**2 + y**2) distance_outside_outer_disk = distance_from_origin - radius - half_thickness distance_inside_inner_disk = radius - half_thickness - distance_from_origin ring = 1.0 - bitwise_xor(greater_equal(distance_inside_inner_disk, 0.0), greater_equal(distance_outside_outer_disk, 0.0)) sigmasq = gaussian_width * gaussian_width if sigmasq == 0.0: inner_falloff = x * 0.0 outer_falloff = x * 0.0 else: with float_error_ignore(): inner_falloff = exp( divide( -distance_inside_inner_disk * distance_inside_inner_disk, 2.0 * sigmasq)) outer_falloff = exp( divide( -distance_outside_outer_disk * distance_outside_outer_disk, 2.0 * sigmasq)) output_ring = maximum(inner_falloff, maximum(outer_falloff, ring)) # Calculate radians (in 4 phases) and cut according to the set range) # RZHACKALERT: # Function float_error_ignore() cannot catch the exception when # both dividend and divisor are 0.0, and when only divisor is 0.0 # it returns 'Inf' rather than 0.0. In x, y and # distance_from_origin, only one point in distance_from_origin can # be 0.0 (circle center) and in this point x and y must be 0.0 as # well. So here is a hack to avoid the 'invalid value encountered # in divide' error by turning 0.0 to 1e-5 in distance_from_origin. distance_from_origin += where(distance_from_origin == 0.0, 1e-5, 0) with float_error_ignore(): sines = divide(y, distance_from_origin) cosines = divide(x, distance_from_origin) arcsines = arcsin(sines) phase_1 = where(logical_and(sines >= 0, cosines >= 0), 2 * pi - arcsines, 0) phase_2 = where(logical_and(sines >= 0, cosines < 0), pi + arcsines, 0) phase_3 = where(logical_and(sines < 0, cosines < 0), pi + arcsines, 0) phase_4 = where(logical_and(sines < 0, cosines >= 0), -arcsines, 0) arcsines = phase_1 + phase_2 + phase_3 + phase_4 if radian_range[0] <= radian_range[1]: return where( logical_and(arcsines >= radian_range[0], arcsines <= radian_range[1]), output_ring, 0.0) else: return where( logical_or(arcsines >= radian_range[0], arcsines <= radian_range[1]), output_ring, 0.0)
def FugaM(self, Z, A_i, B_i, A, B): LogFug = B_i / B * (Z - 1) - log( Z - B) + A / B * (B_i / B - 2 * sqrt(A_i / A)) * log(1 + B / Z) Fug = exp(LogFug) return Fug
def standardDeviation(data): data = Numeric.array(data) return Numeric.sqrt(variance(data))
def dadT(self, ac, T): return -ac / (2 * T * sqrt(T))