def tripples( self, lst, n ): """ Group items of lst into n tripples with minimal overlap. """ all = [] l = len( lst ) ## get all possible tripples for i in range( l ): for j in range( i+1, l ): for k in range( j+1, l ): all += [ ( lst[i], lst[j], lst[k] ) ] ## calculate pairwise "distance" between tripples pw = N.zeros( (len(all), len(all)), N.Float32 ) for i in range( len( all ) ): for j in range( i, len(all) ): pw[i,j] = pw[j,i] = len( MU.intersection(all[i],all[j]) )**2 pos = 0 r = [] while len( r ) < n: r += [ pos ] ## overlap of selected tripples with all others overlap = N.sum( N.array( [ pw[ i ] for i in r ] ) ) ## select one with lowest overlap to all tripples selected before pos = N.argmin( overlap ) return N.take( all, r )
def get_min_distance_sse(self, ptnode): """ Get the SSE with minimum distance from supplied SSE, from the data members already computed by calc_sse_dist_matrix() Optionally, set the element that was found to infinity so that this routine can be used iteratively to find only elements that have not already been found. Paremeters: ptnode - PTNode representing an SSE (helix,strand) Uses data members (readonly): sse_index_map reverse_sse_index_map sse_dist_matrix Return value: PTNode representing SSE that has min distance from supplied SSE """ # NB: use of argmin depends on having set diagonal (self distance) # elements to inf instead of 0 in calc_sse_dist_matrix(). row = self.sse_index_map[ptnode] mindist_index = Numeric.argmin(self.sse_dist_matrix[row]) mindist_ptnode = self.reverse_sse_index_map[mindist_index] return mindist_ptnode
def tripples(self, lst, n): """ Group items of lst into n tripples with minimal overlap. """ all = [] l = len(lst) ## get all possible tripples for i in range(l): for j in range(i + 1, l): for k in range(j + 1, l): all += [(lst[i], lst[j], lst[k])] ## calculate pairwise "distance" between tripples pw = N.zeros((len(all), len(all)), N.Float32) for i in range(len(all)): for j in range(i, len(all)): pw[i, j] = pw[j, i] = len(MU.intersection(all[i], all[j]))**2 pos = 0 r = [] while len(r) < n: r += [pos] ## overlap of selected tripples with all others overlap = N.sum(N.array([pw[i] for i in r])) ## select one with lowest overlap to all tripples selected before pos = N.argmin(overlap) return N.take(all, r)
def usr_descriptors(points): """return 12-tuple of geoemtric descriptors for points Reference for method: Ballester, PJ & Richards, WG (2007) Proc.R.Soc.A doi:10.1098/rspa.2007.1823 """ # centroid ctr = centroid(points) ctr_da = dist_array(ctr, points) ctr_m, ctr_v, ctr_s = mean_var_skew(ctr_da) # closest to centroid cst = points[N.argmin(ctr_da)] cst_da = dist_array(cst, points) cst_m, cst_v, cst_s = mean_var_skew(cst_da) # farthest from centroid fct = points[N.argmax(ctr_da)] fct_da = dist_array(fct, points) fct_m, fct_v, fct_s = mean_var_skew(fct_da) # farthest from fct ftf = points[N.argmax(fct_da)] ftf_da = dist_array(ftf, points) ftf_m, ftf_v, ftf_s = mean_var_skew(ftf_da) return (ctr_m, ctr_v, ctr_s, cst_m, cst_v, cst_s, fct_m, fct_v, fct_s, ftf_m, ftf_v, ftf_s)
def _curve_values(self, i_value, j_value, curve): """ Return the x, y, and x ticks values for the specified curve from the curve_dict. With the current implementation, there may be cases (i.e., when the lowest contrast curve gives a lot of zero y_values) in which the maximum is not in the center. This may eventually be changed so that the preferred orientation is in the center. """ if self.first_curve==True: x_values= sorted(curve.keys()) y_values=[curve[key].view()[0][i_value,j_value] for key in x_values] min_arg=argmin(y_values) x_min=x_values[min_arg] y_min=y_values[min_arg] y_values=self._rotate(y_values, n=min_arg) self.ticks=self._rotate(x_values, n=min_arg) self.ticks+=[x_min] x_max=min(x_values)+self.cyclic_range x_values.append(x_max) y_values.append(y_min) self.x_values=x_values else: y_values=[curve[key].view()[0][i_value,j_value] for key in self.ticks] return self.x_values,y_values,self.ticks
def median(self): """ Median of distribution. """ cum = N.add.accumulate(self.p) * self.delta_x index = N.argmin(abs(cum - 0.5)) return self.x[index]
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 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 argmin(self, key): """ @param key: item attribute @type key: any @return: index of item with lowest item[infokey] value @rtype: int """ vLst = self.valuesOf(key) return N.argmin(vLst)
def compute_memo(self, chunk): """ If drawing chunk in this display mode can be optimized by precomputing some info from chunk's appearance, compute that info and return it. If this computation requires preference values, access them as env.prefs[key], and that will cause the memo to be removed (invalidated) when that preference value is changed by the user. This computation is assumed to also depend on, and only on, chunk's appearance in ordinary display modes (i.e. it's invalidated whenever havelist is). There is not yet any way to change that, so bugs will occur if any ordinarily invisible chunk info affects this rendering, and potential optimizations will not be done if any ordinarily visible info is not visible in this rendering. These can be fixed if necessary by having the real work done within class Chunk's _recompute_ rules, with this function or drawchunk just accessing the result of that (and sometimes causing its recomputation), and with whatever invalidation is needed being added to appropriate setter methods of class Chunk. If the real work can depend on more than chunk's ordinary appearance can, the access would need to be in drawchunk; otherwise it could be in drawchunk or in this method compute_memo. """ # for this example, we'll turn the chunk axes into a cylinder. # 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 (unless we're sure it's already unit length, which is likely) center = chunk.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 ## r_xy = sqrt(r_xy_2) # not needed # 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)] bcenter = chunk.abs_to_base(center) # return, in chunk-relative coords, end1, end2, and radius of the cylinder, and color. color = chunk.color if color is None: color = V(0.5, 0.5, 0.5) # make sure it's longer than zero (in case of a single-atom chunk); in fact, add a small margin all around # (note: this is not sufficient to enclose all atoms entirely; that's intentional) margin = 0.2 min_z -= margin max_z += margin radius += margin return (bcenter + min_z * axis, bcenter + max_z * axis, radius, color)
def getDistance(V, X, mask): """ d(V, X) = (1/|X|) Sum[i = 1 to |X|]{ min[j = 1 to |V|] {|| x_i - v_j||} } where x_i is in X and v_j is in V. """ min = [] sum = 0 for x in X: for v in V: min.append(euclideanDistance(x,v,mask)) sum += min[Numeric.argmin(min)] return sum / len(X)
def argmin( self, infoKey ): """ Get index of complex c with lowest c.infos[infokey] value @param infoKey: key for info dict @type infoKey: str @return: index of complex c with lowest c.infos[infokey] value @rtype: int """ vLst = self.valuesOf( infoKey ) return N.argmin( vLst )
def get_min_distance_objid(self, objid, not_objid_set, sheets_only=False): """ Get the sheet or helix with minimum distance from the supplied sheet or helix, specified by id (e.g. 'A' for a sheet or 'HELIX_A_10' for a helix). Optionally, set the element that was found to infinity so that this routine can be used iteratively to find only elements that have not already been found. Paremeters: objid - sheet id (e.g. 'A') or helix id (e.g. 'HELIX_A_10') of the object to find the id of the closest object for. not_objid_set - set of objids that we do NOT want to find. Used so we can find the nearest element to an already positioned element that is not itself an already positioned element. sheets_only - (Default False) only find sheets, not helices. Uses data members (readonly): sheet_index_map reverse_sheet_index_map sheet_dist_matrix Return value: tuple (id, dist) where id (as per the objid paramter) of the closest sheet or helix to the speicfied one and dist is that smallest distance, and it is not in the not_objid_set. """ row = self.sheet_index_map[objid] mindist_index = Numeric.argmin(self.sheet_dist_matrix[row]) # get 1d array of object ids sorted (ascending) by their distance # from the target objid in the sheet dist matrix # NB: use of argsort depends on having set diagonal (self distance) # elements to inf instead of 0 in calc_sse_dist_matrix(). objids_sorted_by_dist = Numeric.argsort(self.sheet_dist_matrix[row]) # find the first (i.e. smallest distance) id that is not in # the not_objid_set mindist_index = None for mindist_index in objids_sorted_by_dist: mindist_objid = self.reverse_sheet_index_map[mindist_index] if ((mindist_objid not in not_objid_set) and (not sheets_only or len(mindist_objid) == 1)): dist = self.sheet_dist_matrix[row, mindist_index] break return (mindist_objid, dist)
def getDistance(V, X, mask): """ d(V, X) = (1/|X|) Sum[i = 1 to |X|]{ min[j = 1 to |V|] {|| x_i - v_j||} } where x_i is in X and v_j is in V. """ min = [] sum = 0 for x in X: for v in V: min.append(euclideanDistance(x, v, mask)) sum += min[Numeric.argmin(min)] return sum / len(X)
def get_min_distance_objid(self, objid, not_objid_set, sheets_only=False): """ Get the sheet or helix with minimum distance from the supplied sheet or helix, specified by id (e.g. 'A' for a sheet or 'HELIX_A_10' for a helix). Optionally, set the element that was found to infinity so that this routine can be used iteratively to find only elements that have not already been found. Paremeters: objid - sheet id (e.g. 'A') or helix id (e.g. 'HELIX_A_10') of the object to find the id of the closest object for. not_objid_set - set of objids that we do NOT want to find. Used so we can find the nearest element to an already positioned element that is not itself an already positioned element. sheets_only - (Default False) only find sheets, not helices. Uses data members (readonly): sheet_index_map reverse_sheet_index_map sheet_dist_matrix Return value: tuple (id, dist) where id (as per the objid paramter) of the closest sheet or helix to the speicfied one and dist is that smallest distance, and it is not in the not_objid_set. """ row = self.sheet_index_map[objid] mindist_index = Numeric.argmin(self.sheet_dist_matrix[row]) # get 1d array of object ids sorted (ascending) by their distance # from the target objid in the sheet dist matrix # NB: use of argsort depends on having set diagonal (self distance) # elements to inf instead of 0 in calc_sse_dist_matrix(). objids_sorted_by_dist = Numeric.argsort(self.sheet_dist_matrix[row]) # find the first (i.e. smallest distance) id that is not in # the not_objid_set mindist_index = None for mindist_index in objids_sorted_by_dist: mindist_objid = self.reverse_sheet_index_map[mindist_index] if ( (mindist_objid not in not_objid_set) and (not sheets_only or len(mindist_objid) == 1) ): dist = self.sheet_dist_matrix[row, mindist_index] break return (mindist_objid, dist)
def compute_memo(self, chunk): """ If drawing chunk in this display mode can be optimized by precomputing some info from chunk's appearance, compute that info and return it. If this computation requires preference values, access them as env.prefs[key], and that will cause the memo to be removed (invalidated) when that preference value is changed by the user. This computation is assumed to also depend on, and only on, chunk's appearance in ordinary display modes (i.e. it's invalidated whenever havelist is). There is not yet any way to change that, so bugs will occur if any ordinarily invisible chunk info affects this rendering, and potential optimizations will not be done if any ordinarily visible info is not visible in this rendering. These can be fixed if necessary by having the real work done within class Chunk's _recompute_ rules, with this function or drawchunk just accessing the result of that (and sometimes causing its recomputation), and with whatever invalidation is needed being added to appropriate setter methods of class Chunk. If the real work can depend on more than chunk's ordinary appearance can, the access would need to be in drawchunk; otherwise it could be in drawchunk or in this method compute_memo. """ # for this example, we'll turn the chunk axes into a cylinder. # 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 (unless we're sure it's already unit length, which is likely) center = chunk.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 ## r_xy = sqrt(r_xy_2) # not needed # 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)] bcenter = chunk.abs_to_base(center) # return, in chunk-relative coords, end1, end2, and radius of the cylinder, and color. color = chunk.color if color is None: color = V(0.5,0.5,0.5) # make sure it's longer than zero (in case of a single-atom chunk); in fact, add a small margin all around # (note: this is not sufficient to enclose all atoms entirely; that's intentional) margin = 0.2 min_z -= margin max_z += margin radius += margin return (bcenter + min_z * axis, bcenter + max_z * axis, radius, color)
def selectFasta( self, ids_in_cluster ): """ select one member of cluster of sequences. @param ids_in_cluster: list of sequence ids defining the cluster @type ids_in_cluster: [str] @return: Bio.Fasta.Record @rtype: Bio.Fasta.Record """ resolutions = [] for id in ids_in_cluster: resolutions += [ getattr( self.record_dic[id],'resolution', 99. ) ] return ids_in_cluster[ Numeric.argmin( resolutions ) ]
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 updateWinner(self): """ Calculate the current winner based on which model vector is closest to the moving average. """ min = [] for m in self.models: min.append(euclideanDistance(m.vector, self.movingAverage, self.mask)) if min == []: self.winner = 'No Winner' else: self.previousWinnerIndex= self.newWinnerIndex self.newWinnerIndex = Numeric.argmin(min) if self.previousWinnerIndex == self.newWinnerIndex: self.winnerCount += 1 else: self.winnerCount = 0 winner = self.models[self.newWinnerIndex] winner.counter += 1 #if winner.maxSize != -1: winner.addItem(self.buffer[0]) self.winner = winner.vector
def updateWinner(self): """ Calculate the current winner based on which model vector is closest to the moving average. """ min = [] for m in self.models: min.append( euclideanDistance(m.vector, self.movingAverage, self.mask)) if min == []: self.winner = 'No Winner' else: self.previousWinnerIndex = self.newWinnerIndex self.newWinnerIndex = Numeric.argmin(min) if self.previousWinnerIndex == self.newWinnerIndex: self.winnerCount += 1 else: self.winnerCount = 0 winner = self.models[self.newWinnerIndex] winner.counter += 1 #if winner.maxSize != -1: winner.addItem(self.buffer[0]) self.winner = winner.vector
def findConfidenceInterval(self, x): """ findConfidenceInterval(self, x) Find the smallest possible density interval that still includes x. @param x: value @type x: float @return: convidence level, interval start and end @rtype: float, (float,float) """ closest = N.argmin(abs(self.x - x)) ind = N.nonzero(N.greater_equal(self.p, self.p[closest])).tolist() intervals = self.__find_intervals(ind) ## lens = N.array([len(i) for i in intervals]) levels = [N.sum(N.take(self.p, i)) for i in intervals] level = N.sum(levels) * self.delta_x boundaries = [(self.x[i[0]], self.x[i[-1]]) for i in intervals] return level, tuple(boundaries)
def closest(point, points): """works, but @@DEPRECATED!! return index into points of closest-to-point """ da = dist_array(point, points) return N.argmin(da)