def main (): # Draws the location of Dunkin and Starbucks respectively on the Turtle Canvas label ('Dunkin', 'red', Dunkin_x, Dunkin_y) label ('Starbucks', 'red', Starbucks_x, Starbucks_y) # Prompt to enter your x and y coordinates and combine as a single variable your_x = float (input("Enter your x coordinate \n")) your_y = float (input("Enter your y coordinate \n")) # Prompt to enter which distance to use Euclidean or Manhattan method = input("Enter which distance to use, euclidean or manhattan? \n") # Draws your location label('You', 'blue', your_x, your_y) # Figure out your distance from Dunkin and your distance from Starbucks if method == 'euclidean': distance_from_Dunkin = euclidean(your_x, your_y, Dunkin_x, Dunkin_y) distance_from_Starbucks = euclidean(your_x, your_y, Starbucks_x, Starbucks_y) if method == 'manhattan': distance_from_Dunkin = manhattan(your_x, your_y, Dunkin_x, Dunkin_y) distance_from_Starbucks = manhattan(your_x, your_y, Starbucks_x, Starbucks_y) # Determine if you are closer to Dunkin or Starbucks and print the result if distance_from_Dunkin < distance_from_Starbucks: print('You are closer to Dunkin') if distance_from_Starbucks < distance_from_Dunkin: print('You are closer to Starbucks')
def test_euclidean(): ''' function test_euclidean Input: none Returns: int, # of tests that failed Does: tests a few different inputs on the euclidean distance function, makes sure each distance value is as-expected. ''' num_failed = 0 # Test 1: (0, 0), (0, 0) # Distance should be 0 actual = euclidean(0, 0, 0, 0) expected = 0.0 print('Input (0, 0), (0, 0).\n' 'Expected result', expected, 'and actual result =', actual) if absolute(actual - expected) < EPSILON: print('SUCCESS!\n') else: print('FAIL :( \n') num_failed += 1 # Test 2: (2, -1), (-2, 2). # Distance is 5.0 actual = euclidean(2, -1, -2, 2) expected = 5.0 print('Input (2, -1), (-2, 2).\n' 'Expected result', expected, 'and actual result =', actual) if absolute(actual - expected) < EPSILON: print('SUCCESS!\n') else: print('FAIL :( \n') num_failed += 1 # Test 3: (1, 1), (0, 1) # Distance is 1.0 actual = euclidean(1, 1, 0, 1) expected = 1.0 print('Input (1, 1), (0, 1).\n' 'Expected result', expected, 'and actual result =', actual) if absolute(actual - expected) < EPSILON: print('SUCCESS!\n') else: print('FAIL :( \n') num_failed += 1 # Test 4: (-5.2, 3.8), (-13.4, 0.2) # Distance is 8.955445 actual = euclidean(-5.2, 3.8, -13.4, 0.2) expected = 8.955445 print('Input (-5.2, 3.8), (-13.4, 0.2).\n' 'Expected result', expected, 'and actual result =', actual) if absolute(actual - expected) < EPSILON: print('SUCCESS!\n') else: print('FAIL :(\n') num_failed += 1 return num_failed
def main(): b1 = np.array([50000, 4, 1], dtype=np.float64) b2 = np.array([15000, 1, 5], dtype=np.float64) b3 = np.array([60000, 3, 2], dtype=np.float64) b4 = np.array([25000, 5, 3], dtype=np.float64) b5 = np.array([78000, 4, 5], dtype=np.float64) # Cosine print("Cosine\nCosine B5, B4 : " + str(dis.cosine(b5, b4))) print("Cosine B5, B3 : " + str(dis.cosine(b5, b3))) print("Cosine B5, B2 : " + str(dis.cosine(b5, b2))) print("Cosine B5, B1 : " + str(dis.cosine(b5, b1))) # Jaccard print("Jaccard\nJaccard B5, B4 : " + str(dis.jaccard(b5, b4))) print("Jaccard B5, B3 : " + str(dis.jaccard(b5, b3))) print("Jaccard B5, B2 : " + str(dis.jaccard(b5, b2))) print("Jaccard B5, B1 : " + str(dis.jaccard(b5, b1))) # Dice print("Dice\nDice B5, B4 : " + str(dis.dice(b5, b4))) print("Dice B5, B3 : " + str(dis.dice(b5, b3))) print("Dice B5, B2 : " + str(dis.dice(b5, b2))) print("Dice B5, B1 : " + str(dis.dice(b5, b1))) # Euclidean print("Euclidean\nEuclidean B5, B4 : " + str(dis.euclidean(b5, b4))) print("Euclidean B5, B3 : " + str(dis.euclidean(b5, b3))) print("Euclidean B5, B2 : " + str(dis.euclidean(b5, b2))) print("Euclidean B5, B1 : " + str(dis.euclidean(b5, b1))) # Manhattan print("Manhattan\nManhattan B5, B4 : " + str(dis.manhattan(b5, b4))) print("Manhattan B5, B3 : " + str(dis.manhattan(b5, b3))) print("Manhattan B5, B2 : " + str(dis.manhattan(b5, b2))) print("Manhattan B5, B1 : " + str(dis.manhattan(b5, b1)))
def density_heatmap(image, box_centers, radias=100): import matplotlib.pyplot as plt from colour import Color import distance density_range = 100 gradient = np.linspace(0, 1, density_range) img_width = image.shape[1] img_height = image.shape[0] density_map = np.zeros((img_height, img_width)) color_map = np.empty([img_height, img_width, 3], dtype=int) # get gradient color using rainbow cmap = plt.get_cmap("rainbow") # 使用matplotlib获取颜色梯度 blue = Color("blue") # 使用Color来生成颜色梯度 hex_colors = list(blue.range_to(Color("red"), density_range)) rgb_colors = [[rgb * 255 for rgb in color.rgb] for color in hex_colors][::-1] for i in range(img_height): for j in range(img_width): for box in box_centers: dist = distance.euclidean(box, (j, i)) if dist <= radias * 0.25: density_map[i][j] += 10 elif dist <= radias: density_map[i][j] += (radias - dist) / (radias * 0.75) * 10 ratio = min(density_range - 1, int(density_map[i][j])) for k in range(3): # color_map[i][j][k] = int(cmap(gradient[ratio])[:3][k]*255) color_map[i][j][k] = rgb_colors[ratio][k] return color_map
def __init__(self, mapping=None, weights=None): self._distanceMetrics = { 'euclidean': lambda a, b: distance.euclidean([a], [b]), 'manhattan': distance.manhattanScalar, 'levenshtein': lambda a, b: distance.levenshtein([a], [b]), 'needleman_wunsch': lambda a, b: distance.needleman_wunsch([a], [b]), 'jaccard': distance.jaccard, 'dice': distance.dice } self._mapping = mapping if (self._mapping == None): self._mapping = [None] * NUM_FEATURES self._mapping[STARS] = self._distanceMetrics['manhattan'] self._mapping[TOTAL_REVIEW_COUNT] = self._distanceMetrics[ 'manhattan'] self._mapping[AVAILABLE_REVIEW_COUNT] = self._distanceMetrics[ 'manhattan'] self._mapping[MEAN_REVIEW_LEN] = self._distanceMetrics['manhattan'] self._mapping[MEAN_WORD_LEN] = self._distanceMetrics['manhattan'] self._mapping[NUM_WORDS] = self._distanceMetrics['manhattan'] self._mapping[MEAN_WORD_COUNT] = self._distanceMetrics['manhattan'] self._mapping[TOTAL_HOURS] = self._distanceMetrics['manhattan'] self._mapping[ATTRIBUTES] = self._distanceMetrics['jaccard'] self._mapping[CATEGORIES] = self._distanceMetrics['jaccard'] self._mapping[TOP_WORDS] = self._distanceMetrics['jaccard'] self._mapping[KEY_WORDS] = self._distanceMetrics['jaccard'] self._mapping[OPEN_HOURS] = self._distanceMetrics['jaccard'] self._weights = weights if (self._weights == None): self._weights = [1] * NUM_FEATURES
def parallelArgArg(pdbFrameName): edges = open( outputFolder + "/RIP-MD_Results/Edges/" + pdbFrameName[0] + ".edges", "a") edges.write( "ARG-ARG\nSource Node\tTarget Node\tEdge Name\tDistance (CZ)\n") u = MDAnalysis.Universe(pdbFrameName[1]) #it is based on CZ of ARG residues args = u.select_atoms("resname ARG and name CZ") #selecting carbons atoms lenArgs = len(args) i = 0 j = 0 while i < lenArgs: j = i + 1 node1 = str(args[i].resname) + ":" + str( args[i].segment.segid) + ":" + str(args[i].resid) while j < lenArgs: one = args[i].position two = args[j].position Distance = distance.euclidean(one, two) if Distance <= Dist: node2 = str(args[j].resname) + ":" + str( args[j].segment.segid) + ":" + str(args[j].resid) edge = node1 + "-(Arg-Arg)-" + node2 if nodes.has_key(node1) and nodes.has_key(node2): edges.write( str(nodes[node1]) + "\t" + str(nodes[node2]) + "\t" + str(edge) + "\t" + str(round(Distance, 3)) + "\n") j += 1 i += 1 edges.write("\n") edges.close() return
def parallelCA(parameters): pdbList = parameters edges = open( output + "/RIP-MD_Results/Edges/" + str(pdbList[0]) + ".edges", "a") edges.write( "Alpha carbon\nSource Node\tTarget Node\tEdge Name\tDistance\n") u = MDAnalysis.Universe(pdbList[1]) calphas = u.select_atoms("name CA") #selecting alpha carbons atoms lenCalpha = len(calphas) i = 0 j = 0 while i < lenCalpha: j = i + 1 node1 = str(calphas[i].resname) + ":" + str( calphas[i].segment.segid) + ":" + str(calphas[i].resid) one = calphas[i].position while j < lenCalpha: two = calphas[j].position Distance = distance.euclidean(one, two) if Distance <= dist: node2 = str(calphas[j].resname) + ":" + str( calphas[j].segment.segid) + ":" + str(calphas[j].resid) edge = node1 + "-(Ca)-" + node2 if Nodes.has_key(node1) and Nodes.has_key(node2): edges.write( str(Nodes[node1]) + "\t" + str(Nodes[node2]) + "\t" + str(edge) + "\t" + str(round(Distance, 3)) + "\n") j += 1 i += 1 edges.write("\n") edges.close() return
def parallelSalt(pdbFrameName): edges = open( outputFolder + "/RIP-MD_Results/Edges/" + pdbFrameName[0] + ".edges", "a") edges.write( "Salt bridges\nSource Node\tTarget Node\tEdge Name\tDistance\n") u = MDAnalysis.Universe(pdbFrameName[1]) # crude definition of salt bridges as contacts between NH/NZ in # ARG/LYS and OE*/OD* in ASP/GLU. acidic = u.select_atoms("(resname ASP GLU) and (name OE* OD*)") basic = u.select_atoms("(resname ARG LYS) and (name NH* NZ)") for acidicAtom in acidic: acidic_pos = acidicAtom.position for basicAtom in basic: basic_pos = basicAtom.position Distance = distance.euclidean(acidic_pos, basic_pos) if Distance <= maxDist: #print acidicAtom, basicAtom node1 = str(acidicAtom.resname) + ":" + str( acidicAtom.segment.segid) + ":" + str(acidicAtom.resid) node2 = str(basicAtom.resname) + ":" + str( basicAtom.segment.segid) + ":" + str(basicAtom.resid) name = node1 + ":" + acidicAtom.name + "-(salt)-" + node2 + ":" + basicAtom.name if nodes.has_key(node1) and nodes.has_key(node2): edges.write( str(nodes[node1]) + "\t" + str(nodes[node2]) + "\t" + str(name) + "\t" + str(round(Distance, 3)) + "\n") edges.write("\n") edges.close() return
def silhouete_coef(x, centroids): distances = [] if len(centroids) == 1: return 0 for centroid in centroids: distances.append(euclidean(x, centroid)) distances.sort() return (distances[1] - distances[0]) / max(distances[0], distances[1])
def test_euclideanBase(self): a = [0, 0] b = [0, 0] self.assertAlmostEqual(distance.euclidean(a, b), 0, places=3) self.assertAlmostEqual(distance.euclidean(a, b, distance.logNormalize), 0, places=3) a = [1, 0] b = [0, 0] self.assertAlmostEqual(distance.euclidean(a, b), 0.46199999, places=3) a = [0, 0] b = [0, 1] self.assertAlmostEqual(distance.euclidean(a, b), 0.46199999, places=3) a = [0, 0] b = [1, 1] self.assertAlmostEqual(distance.euclidean(a, b), 0.60884, places=3)
def compute_similarity(self): sim_matrix = np.zeros((self.rows, self.rows)) for i in xrange(self.rows): for j in xrange(i+1,self.rows): vec1 = self.main.iloc[i,:][self.main.iloc[i,:] != -1] vec2 = self.main.iloc[j,:][self.main.iloc[j,:] != -1] sim_matrix[i,j] = distance.euclidean(vec1,vec2) sim_matrix = sim_matrix.T + sim_matrix return sim_matrix
def get_distances(self, x, y): distance1 = cosine_distance(np.mean(x, 0), np.mean(y, 0)) * -1 distance2 = canberra(np.mean(x, 0), np.mean(y, 0)) distance3 = euclidean(np.mean(x, 0), np.mean(y, 0)) distance4, _, _ = directed_hausdorff(x, y) distance5 = jsd_kmean(x, y) distance6 = jsd_mixture(x, y) return np.array( [distance1, distance2, distance3, distance4, distance5, distance6])
def __init__(self, measure=None, X=None, Y=None, f=None): if (measure == None): self.measure = euclidean() else: self.measure = measure # if not weighted -> weights are an n*n adjacency matrix of 1 elements # if is weighted -> weights are an n*n adjacency matrix as received in input self.X = None self.Y = None # f represent the permutation of X to get to Y self.f = None
def neighbors(self, x): distances = [] for point in self.data: # Compute the distances distances.append(dist.euclidean(x, point)) # Find the n closest neighbors distances = np.array(distances) # Gives the indexes of the closest elements return distances.argsort()[:self.n_neighbors]
def singlelink(set1, set2, data): # Create a list of lists for each list in data corresponding to set 1 lists1 = [data[val] for val in set1]; # Create a list of lists for each list in data corresponding to set 2 lists2 = [data[val] for val in set2]; # Compute the Cartesian product of the vectors in set1 and set2 cartesian = [element for element in itertools.product(lists1, lists2)]; # Find the minimum distance in the Cartesian product. Min = float("inf"); for pair in cartesian: dist = distance.euclidean(pair[0], pair[1]); if(dist < Min): Min = dist; return Min;
def completelink(set1, set2, data): # Create a list of lists for each list in data corresponding to set 1 lists1 = [data[val] for val in set1]; # Create a list of lists for each list in data corresponding to set 2 lists2 = [data[val] for val in set2]; # Compute the Cartesian product of the vectors in set1 and set2 cartesian = [element for element in itertools.product(lists1, lists2)]; # Find the maximum distance in the Cartesian product. Max = -1; for pair in cartesian: dist = distance.euclidean(pair[0], pair[1]); if(dist > Max): Max = dist; return Max;
def singleParallelArgArg(parameters): toReturn = [] i, j = parameters one = ARGs[i].position two = ARGs[j].position Distance = distance.euclidean(one, two) if Distance <= Dist: node1 = str(ARGs[i].resname) + ":" + str( ARGs[i].segment.segid) + ":" + str(ARGs[i].resid) node2 = str(ARGs[j].resname) + ":" + str( ARGs[j].segment.segid) + ":" + str(ARGs[j].resid) edge = node1 + "-(Arg-Arg)-" + node2 if nodes.has_key(node1) and nodes.has_key(node2): toReturn.append( str(nodes[node1]) + "\t" + str(nodes[node2]) + "\t" + str(edge) + "\t" + str(round(Distance, 3)) + "\n") return toReturn
def curve_data(): data = np.transpose(np.matrix([ np.random.normal(0,1,20000), np.random.normal(0,1,20000), np.random.normal(0,1,20000) ])) indices = [] n, p = data.shape for i in range(n): if (euclidean(np.array(data[i,:])[0], np.array([0,0,0])) > .5) and \ (data[i,0] > 0 and data[i,1] > 1): indices.append(i) new_data = np.zeros([len(indices), 3]) for i, j in enumerate(indices): new_data[i,:] = data[j,:] new_data = np.matrix(new_data) return new_data
def clustering(centroid, data, distance='euclidean'): # list untuk menyimpan cluster baru dari data yang dihitung cluster_baru = [] for i in data: # menyimpan hasil distance dari data tertentu terhadap semua centroid hasil_per_centroid = [] # menghitung distance dari setiap centroid for k in centroid: if distance == 'euclidean': hasil_per_centroid.append(dt.euclidean(i, k)) elif distance == 'manhattan': hasil_per_centroid.append(dt.manhattan(i, k)) elif distance == 'minkowsky': hasil_per_centroid.append(dt.minkowsky(i, k)) cluster_baru.append(hasil_per_centroid.index(min(hasil_per_centroid))) return cluster_baru
def meanlink(set1, set2, data): # Create a list of lists for each list in data corresponding to set 1 lists1 = [data[val] for val in set1]; # Create a list of lists for each list in data corresponding to set 2 lists2 = [data[val] for val in set2]; # Compute the means of set1 and set2 s1 = [0 for r in range(len(lists1[0]))]; s2 = [0 for r in range(len(lists2[0]))]; for lis in lists1: for i in range(len(lis)): s1[i] += lis[i]/len(lists1); for lis in lists2: for i in range(len(lis)): s2[i] += lis[i]/len(lists2); # Return the norm of the means return distance.euclidean(s1,s2);
def parallelSingleCA(i): edgesToReturn = [] j = i + 1 one = Calphas[i].position node1 = str(Calphas[i].resname) + ":" + str( Calphas[i].segment.segid) + ":" + str(Calphas[i].resid) while j < len(Calphas): two = Calphas[j].position Distance = distance.euclidean(one, two) if Distance <= dist: node2 = str(Calphas[j].resname) + ":" + str( Calphas[j].segment.segid) + ":" + str(Calphas[j].resid) edge = node1 + "-(Ca)-" + node2 if Nodes.has_key(node1) and Nodes.has_key(node2): edgesToReturn.append( str(Nodes[node1]) + "\t" + str(Nodes[node2]) + "\t" + str(edge) + "\t" + str(round(Distance, 3)) + "\n") j += 1 return edgesToReturn
def clustering(dataset, centroid, distance='euclidean'): cluster = [] biaya = 0 for i in dataset: # menyimpan hasil distance dari data tertentu terhadap semua centroid hasil_per_centroid = [] # menghitung distance dari setiap centroid for k in centroid: if distance == 'euclidean': hasil_per_centroid.append(dt.euclidean(i, k)) elif distance == 'manhattan': hasil_per_centroid.append(dt.manhattan(i, k)) elif distance == 'minkowsky': hasil_per_centroid.append(dt.minkowsky(i, k)) minim = min(hasil_per_centroid) index = hasil_per_centroid.index(minim) biaya += minim cluster.append(index) return {'cluster_baru': cluster, 'biaya': biaya}
def singleParallelDisulfide(parameters): i, j = parameters toReturn = [] try: eu_dist = round( distance.euclidean(sel[i].SG.position, sel[j].SG.position), 3) if eu_dist <= dist: v1 = sel[i].CB.position - sel[ i].SG.position #vector 1 is between a C and the S atoms v2 = sel[j].CB.position - sel[j].SG.position #same thing angle = round(Angle.angle_twoVectors(v1, v2), 3) if angle >= float(angle1) and angle <= float(angle2): node1 = "CYS:" + sel[i].SG.segid + ":" + str(sel[i].SG.resnum) node2 = "CYS:" + sel[j].SG.segid + ":" + str(sel[j].SG.resnum) edgeName = node1 + "-(SS)-" + node2 if nodes.has_key(node1) and nodes.has_key(node2): toReturn.append( str(nodes[node1]) + "\t" + str(nodes[node2]) + "\t" + str(edgeName) + "\t" + str(round(eu_dist, 3)) + "\t" + str(round(angle, 3)) + "\n") except: pass return toReturn
(-5, 7), (2, 2), (-4, 5), (0, -2), (-4, 7), (-1, 3), (-3, 2), (-4, -5), (-3, 2), (5, 7), (5, 7), (2, 2), (9, 9), (-8, -9)] non_quadrant = [] quadrant_1 = ("Quadrant 1") quadrant_2 = ("Quadrant 2") quadrant_3 = ("Quadrant 3") quadrant_4 = ("Quadrant 4") total_quadrant_1 = 0 total_quadrant_2 = 0 total_quadrant_3 = 0 total_quadrant_4 = 0 closest_distance_to_the_center = [] from scipy.spatial import distance for point in points: print("Euclidean distance: ", distance.euclidean(point[0], point[1])) if point[0] + point[1] == 0: non_quadrant.append(point) elif point[0] == 0 or point[1] == 0: non_quadrant.append(point) # print(point) if point[0] == 0 or point[1] == 0: print("Out of quandrant") if point[0] > 0 and point[1] > 0: total_quadrant_1 += 1 print("The arrow hits the ", quadrant_1) if point[0] < 0 and point[1] > 0: total_quadrant_2 += 1 print("The arrow hits the ", quadrant_2) if point[0] < 0 and point[1] < 0:
def test_euclidean(): p = [1,1] q = [2,2] print euclidean(p,q)
def singleParallelCationPi(parameters): i,j=parameters #i is for the global variable cations #j is for piSystems toReturn=[] ########################################### #extracting data for the aromatic residue ########################################### aromaticCoords=None if piSystems[j].resname=="PHE" or piSystems[j].resname=="TYR": try: aromaticCoords=[piSystems[j].CG.position,piSystems[j].CD1.position,piSystems[j].CD2.position,piSystems[j].CE1.position,piSystems[j].CE2.position,piSystems[j].CZ.position] except: pass elif piSystems[j].resname=="TRP": try: aromaticCoords=[piSystems[j].CG.position,piSystems[j].CD1.position,piSystems[j].CD2.position,piSystems[j].NE1.position,piSystems[j].CE2.position,piSystems[j].CE3.position,piSystems[j].CZ2.position,piSystems[j].CZ3.position,piSystems[j].CH2.position] except: pass elif piSystems[j].resname=="HIS" or piSystems[j].resname=="HSD" or piSystems[j].resname=="HSE" or piSystems[j].resname=="HSP": try: aromaticCoords=[piSystems[j].CG.position,piSystems[j].ND1.position,piSystems[j].CE1.position,piSystems[j].NE2.position,piSystems[j].CD2.position] except: pass if aromaticCoords!=None: #getting the centroid aux=np.zeros(3) for coord in aromaticCoords: # if aux==None: # aux=coord # else: aux+=coord centroid=aux/len(aromaticCoords) ################################### #extracting charge information ################################### pointOfCharge=np.zeros(3) if cations[i].resname=="ARG": try: pointOfCharge=cations[i].NH1.position except: pass elif cations[i].resname=="LYS": try: pointOfCharge=cations[i].NZ.position except: pass elif cations[i].resname=="HSP" or cations[i].resname=="HIS": try: pointOfCharge=cations[i].NE2.postition except: pass if str(pointOfCharge)!=str(np.zeros(3)): ############################################################ #now we will compute normal vector for the aromatic residues ############################################################ normalVector=np.zeros(3) try: if piSystems[j].resname=="PHE" or piSystems[j].resname=="TYR": v1=piSystems[j].atoms.CG.position-piSystems[j].atoms.CZ.position v2=piSystems[j].atoms.CD1.position-piSystems[j].atoms.CE2.position v3=piSystems[j].atoms.CD2.position-piSystems[j].atoms.CE1.position prod1=np.cross(v1,v2) prod2=np.cross(v1,v3) prod3=np.cross(v2,v3) normalVector=(prod1+prod2+prod3)/3 if piSystems[j].resname=="TRP": v1=piSystems[j].atoms.NE1.position-piSystems[j].atoms.CZ3.position v2=piSystems[j].atoms.CG.position-piSystems[j].atoms.CH2.position v3=piSystems[j].atoms.CD1.position-((piSystems[j].atoms.CZ3.position+piSystems[j].atoms.CH2.position)/2.) prod1=np.cross(v1,v2) prod2=np.cross(v1,v3) prod3=np.cross(v2,v3) normalVector=(prod1+prod2+prod3)/3 if piSystems[j].resname=="HIS" or piSystems[j].resname=="HSD" or piSystems[j].resname=="HSE" or piSystems[j].resname=="HSP": v1=piSystems[j].atoms.ND1.position-piSystems[j].atoms.NE2.position v2=piSystems[j].atoms.CD2.position-piSystems[j].atoms.CE1.position v3=piSystems[j].atoms.CG.position-((piSystems[j].atoms.CE1.position+piSystems[j].atoms.NE2.position)/2.) prod1=np.cross(v1,v2) prod2=np.cross(v1,v3) prod3=np.cross(v2,v3) normalVector=(prod1+prod2+prod3)/3 except: pass if str(normalVector)!=str(np.zeros(3)): #computing distance between the charge and the dist=distance.euclidean(pointOfCharge,centroid) if dist<=Distance: #if distance between cation and center of the ring is less that cutoff angle=Angle.angle(pointOfCharge,centroid, normalVector)#calculate the angle between 2 vectors, the vector between centroid of the ring and cation and the normal vector if (angle>=a1 and angle<=a2) or (angle<=a3 and angle>=a4): node1=None node2=None try: node1=cations[i].resname+":"+cations[i].segment.segid+":"+str(cations[i].resid) node2=piSystems[j].resname+":"+piSystems[j].segment.segid+":"+str(piSystems[j].resid) except: pass if nodes.has_key(node1) and nodes.has_key(node2): edge_name=node1+"-(cation-pi)-"+node2 last_less_dist=1000 #a high value to be reemplaced at first loop closer_atom=None #we will loop over aromatic atoms positions to see what atom is the closer one, with this we will compute the dihedral angle for pos in aromaticCoords: aux=distance.euclidean(pointOfCharge,pos) if aux<last_less_dist: last_less_dist=aux closer_atom=pos # dihedral angle calculated between CA of the cation, the mass center of cation, closer atom and mass center of ring dihedral=None try: dihedral=Angle.dihedral(cations[i].CA.position,pointOfCharge, closer_atom, centroid) except: pass if dihedral!=None: kind="" if (dihedral<a5 and dihedral>=a6) or (dihedral<=a7 and dihedral>a8): kind="planar" elif (dihedral<=a9 and dihedral>=a10) or (dihedral>=a11 and dihedral<=a12): kind="oblique" elif (dihedral>a13 and dihedral<a14): kind="orthogonal" toReturn.append(str(nodes[node1])+"\t"+str(nodes[node2])+"\t"+str(edge_name)+"\t"+str(round(dist,3))+"\t"+str(kind)+"\n") return toReturn
def potential(i): toReturn = [] nodeList = [] groupList1 = [] resNode1 = sele[i].resname + ":" + sele[i].segment.segid + ":" + str( sele[i].resid) #geting node name (that is equal to atomindex +1 cause it begin from 0) for atom in sele[i].atoms: nodeList.append(str(atom.index + 1)) maxGroup1 = 0 #looking for the number of groups that the residue have for node in nodeList: try: group = int((topology.node[node]["group"].split("_"))[1]) if group > maxGroup1: maxGroup1 = group except: pass #if we found more than 1 group we create a list of list to have a local copy of wich atoms form each group if maxGroup1 != 0: #if the node have "group" attribute for k in range(maxGroup1): groupList1.append([]) #looping over atoms to append its to the list of groups for node in nodeList: try: group = int((topology.node[node]["group"].split("_"))[1]) groupList1[group].append( node ) #grouplist in the position group we will puth the node name except: pass #setting the next residues j = i + 1 while j < len(sele): resNode2 = sele[j].resname + ":" + sele[j].segment.segid + ":" + str( sele[j].resid) nodeList2 = [] groupList2 = [] #geting node name (that is equal to atomindex +1 cause it begin from 0) for atom in sele[j].atoms: nodeList2.append(str(atom.index + 1)) maxGroup2 = 0 #looking for the number of groups that the residue have for node in nodeList2: try: group = int((topology.node[node]["group"].split("_"))[1]) if group > maxGroup2: maxGroup2 = group except: pass #if we found more than 1 group we create a list of list to have a local copy of wich atoms form each group if maxGroup2 != 0: #if the node have "group" attribute for k in range(maxGroup2): groupList2.append([]) #looping over atoms to append its to the list of groups for node in nodeList2: try: group = int((topology.node[node]["group"].split("_"))[1]) groupList2[group].append( node ) #grouplist in the position group we will puth the node name except: pass ########################################### ## ## now we will compare atoms of differents ## groups with certain bond distance ## ########################################### for group in groupList1: for group2 in groupList2: Vcoulomb = 0 Vdi = 0 Vdd = 0 flag = 0 atomsFromGroup1 = [] #atom names distAverage = [] #for the i- sumatory for node in group: atomsFromGroup2 = [] #atom names atomsFromGroup1.append(topology.node[node]["atomName"]) # for the j- sumatory for node2 in group2: atomsFromGroup2.append( topology.node[node2]["atomName"]) euclidean_distance = distance.euclidean( positionDict[node], positionDict[node2]) if euclidean_distance <= Rrf: #for the threshold distAverage.append(euclidean_distance) cantShortestPath = None #1-4 potential if int(excluded) > 0: try: shortestPath = nx.shortest_path( topology, source=node, target=node2) cantShortestPath = len(shortestPath) - 1 except: cantShortestPath = int(excluded) #and this shortest path is higher than the coulomb excluded atoms if cantShortestPath >= int(excluded): ####################################################### ## ## i,j not excluded, j inside cutoff i ## ####################################################### Vcoulomb += ( float(topology.node[node]["charge"]) * float(topology.node[node2]["charge"]) ) / euclidean_distance flag = 1 #to know that we entered here if RF: Vdd += ( (-1 * float( topology.node[node]["charge"])) * float(topology.node[node2]["charge"]) * Crf * math.pow(euclidean_distance, 2) ) / (2 * math.pow(Rrf, 3)) Vdi += ( (-1 * float( topology.node[node]["charge"])) * float(topology.node[node2]["charge"]) * (1 - (0.5 * Crf))) / Rrf if flag != 0: Vcoulomb *= coulombCte Vdd *= coulombCte Vdi *= coulombCte Vcoulomb = Vcoulomb - (Vdd + Vdi) if Vcoulomb >= KbT: if nodes.has_key(resNode1) and nodes.has_key(resNode2): d = 0 for k in range(len(distAverage)): d += distAverage[k] d /= len(distAverage) toReturn.append( str(nodes[resNode1]) + "\t" + str(nodes[resNode2]) + "\t" + resNode1 + ":" + str(atomsFromGroup1) + "-(coulomb)-" + resNode2 + ":" + str(atomsFromGroup2) + "\t" + str(round(d, 3)) + "\t" + str(Vcoulomb) + "\n") j += 1 return toReturn
def potentialByFrame(parameters): frame, pdb = parameters edges = open(outputFolder + "/RIP-MD_Results/Edges/" + frame + ".edges", "a") edges.write( "Coulomb\nSource Node\tTarget Node\tEdge Name\tDistance\tCoulomb Potential (kJ/mole)\n" ) positions = {} #dict for position u = MDAnalysis.Universe(pdb) selection = None try: selection = u.select_atoms(sel) except: selection = u.selectAtoms(sel) for atom in selection: positions[str(atom.index + 1)] = atom.position try: selection = u.select_atoms(sel).residues except: selection = u.selectAtoms(sel).residues # for some in selection: # for atom in some.atoms: # print atom for i in range(len(selection)): nodeList = [] groupList1 = [] resNode1 = selection[i].resname + ":" + selection[ i].segment.segid + ":" + str(selection[i].resid) #geting node name (that is equal to atomindex +1 cause it begin from 0) for atom in selection[i].atoms: nodeList.append(str(atom.index + 1)) maxGroup1 = 0 #looking for the number of groups that the residue have for node in nodeList: try: group = int((topology.node[node]["group"].split("_"))[1]) if group > maxGroup1: maxGroup1 = group except: pass #if we found more than 1 group we create a list of list to have a local copy of wich atoms form each group if maxGroup1 != 0: #if the node have "group" attribute for k in range(maxGroup1): groupList1.append([]) #looping over atoms to append its to the list of groups for node in nodeList: try: group = int((topology.node[node]["group"].split("_"))[1]) groupList1[group].append( node ) #grouplist in the position group we will puth the node name except: pass #setting the next residues j = i + 1 while j < len(selection): resNode2 = selection[j].resname + ":" + selection[ j].segment.segid + ":" + str(selection[j].resid) nodeList2 = [] groupList2 = [] #geting node name (that is equal to atomindex +1 cause it begin from 0) for atom in selection[j].atoms: nodeList2.append(str(atom.index + 1)) maxGroup2 = 0 #looking for the number of groups that the residue have for node in nodeList2: try: group = int((topology.node[node]["group"].split("_"))[1]) if group > maxGroup2: maxGroup2 = group except: pass #if we found more than 1 group we create a list of list to have a local copy of wich atoms form each group if maxGroup2 != 0: #if the node have "group" attribute for k in range(maxGroup2): groupList2.append([]) #looping over atoms to append its to the list of groups for node in nodeList2: try: group = int((topology.node[node]["group"].split("_"))[1]) groupList2[group].append( node ) #grouplist in the position group we will puth the node name except: pass ########################################### ## ## now we will compare atoms of differents ## groups with certain bond distance ## ########################################### for group in groupList1: for group2 in groupList2: Vcoulomb = 0 Vdi = 0 Vdd = 0 flag = 0 atomsFromGroup1 = [] #atom names distAverage = [] #for the i- sumatory for node in group: atomsFromGroup2 = [] #atom names atomsFromGroup1.append(topology.node[node]["atomName"]) # for the j- sumatory for node2 in group2: atomsFromGroup2.append( topology.node[node2]["atomName"]) euclidean_distance = distance.euclidean( positions[node], positions[node2]) if euclidean_distance <= Rrf: #for the threshold distAverage.append(euclidean_distance) cantShortestPath = None #1-4 potential if int(excluded) > 0: try: shortestPath = nx.shortest_path( topology, source=node, target=node2) cantShortestPath = len( shortestPath) - 1 except: cantShortestPath = int(excluded) #and this shortest path is higher than the coulomb excluded atoms if cantShortestPath >= int(excluded): ####################################################### ## ## i,j not excluded, j inside cutoff i ## ####################################################### Vcoulomb += (float( topology.node[node]["charge"]) * float(topology.node[node2] ["charge"]) ) / euclidean_distance flag = 1 #to know that we entered here if RF: Vdd += ((-1 * float( topology.node[node]["charge"])) * float(topology.node[node2] ["charge"]) * Crf * math.pow( euclidean_distance, 2)) / ( 2 * math.pow(Rrf, 3)) Vdi += ((-1 * float( topology.node[node]["charge"])) * float(topology.node[node2] ["charge"]) * (1 - (0.5 * Crf))) / Rrf if flag != 0: Vcoulomb *= coulombCte Vdd *= coulombCte Vdi *= coulombCte Vcoulomb = Vcoulomb - (Vdd + Vdi) if Vcoulomb >= KbT: if nodes.has_key(resNode1) and nodes.has_key( resNode2): d = 0 for k in range(len(distAverage)): d += distAverage[k] d /= len(distAverage) edges.write( str(nodes[resNode1]) + "\t" + str(nodes[resNode2]) + "\t" + resNode1 + ":" + str(atomsFromGroup1) + "-(coulomb)-" + resNode2 + ":" + str(atomsFromGroup2) + "\t" + str(round(d, 3)) + "\t" + str(Vcoulomb) + "\n") j += 1 edges.write("\n") edges.close()
def singleParallelPiPi(parameters): i, j = parameters toReturn = [] piCoords1 = np.zeros(3) piCoords2 = np.zeros(3) centroid1 = np.zeros(3) centroid2 = np.zeros(3) normalVector1 = np.zeros(3) normalVector2 = np.zeros(3) #geting coords for the first ring if piSystems[i].resname == "PHE" or piSystems[i].resname == "TYR": try: piCoords1 = [ piSystems[i].atoms.CG.position, piSystems[i].atoms.CD1.position, piSystems[i].atoms.CD2.position, piSystems[i].atoms.CE1.position, piSystems[i].atoms.CE2.position, piSystems[i].atoms.CZ.position ] #computing normal vector vector1 = piCoords1[0] - piCoords1[5] vector2 = piCoords1[1] - piCoords1[4] vector3 = piCoords1[2] - piCoords1[3] prod1 = np.cross(vector1, vector2) prod2 = np.cross(vector1, vector3) prod3 = np.cross(vector2, vector3) normalVector1 = (prod1 + prod2 + prod3) / 3 except: pass elif piSystems[i].resname == "TRP": try: piCoords1 = [ piSystems[i].atoms.CG.position, piSystems[i].atoms.CD1.position, piSystems[i].atoms.CD2.position, piSystems[i].atoms.NE1.position, piSystems[i].atoms.CE2.position, piSystems[i].atoms.CE3.position, piSystems[i].atoms.CZ2.position, piSystems[i].atoms.CZ3.position, piSystems[i].atoms.CH2.position ] #computing normal vector vector1 = piCoords1[3] - piCoords1[7] vector2 = piCoords1[0] - piCoords1[8] vector3 = piCoords1[1] - ((piCoords1[7] + piCoords1[8]) / 2) prod1 = np.cross(vector1, vector2) prod2 = np.cross(vector1, vector3) prod3 = np.cross(vector2, vector3) normalVector1 = (prod1 + prod2 + prod3) / 3 except: pass elif piSystems[i].resname == "HIS" or piSystems[ i].resname == "HSD" or piSystems[i].resname == "HSE" or piSystems[ i].resname == "HSP": try: piCoords1 = [ piSystems[i].atoms.CG.position, piSystems[i].atoms.ND1.position, piSystems[i].atoms.CE1.position, piSystems[i].atoms.NE2.position, piSystems[i].atoms.CD2.position ] #computing normal vector vector1 = piCoords1[1] - piCoords1[3] vector2 = piCoords1[0] - piCoords1[2] vector3 = piCoords1[0] - ((piCoords1[2] + piCoords1[3]) / 2) prod1 = np.cross(vector1, vector2) prod2 = np.cross(vector1, vector3) prod3 = np.cross(vector2, vector3) normalVector1 = (prod1 + prod2 + prod3) / 3 except: pass #only if the first ring is complete we will compute this with the second one if str(piCoords1) != str(np.zeros(3)): for coord in piCoords1: if str(centroid1) == str(np.zeros(3)): centroid1 = coord else: centroid1 += coord centroid1 = centroid1 / len(piCoords1) #geting coords for the second ring if piSystems[j].resname == "PHE" or piSystems[j].resname == "TYR": try: piCoords2 = [ piSystems[j].atoms.CG.position, piSystems[j].atoms.CD1.position, piSystems[j].atoms.CD2.position, piSystems[j].atoms.CE1.position, piSystems[j].atoms.CE2.position, piSystems[j].atoms.CZ.position ] #computing normal vector vector1 = piCoords2[0] - piCoords2[5] vector2 = piCoords2[1] - piCoords2[4] vector3 = piCoords2[2] - piCoords2[3] prod1 = np.cross(vector1, vector2) prod2 = np.cross(vector1, vector3) prod3 = np.cross(vector2, vector3) normalVector2 = (prod1 + prod2 + prod3) / 3 except: pass elif piSystems[j].resname == "TRP": try: piCoords2 = [ piSystems[j].atoms.CG.position, piSystems[j].atoms.CD1.position, piSystems[j].atoms.CD2.position, piSystems[j].atoms.NE1.position, piSystems[j].atoms.CE2.position, piSystems[j].atoms.CE3.position, piSystems[j].atoms.CZ2.position, piSystems[j].atoms.CZ3.position, piSystems[j].atoms.CH2.position ] #computing normal vector vector1 = piCoords2[3] - piCoords2[7] vector2 = piCoords2[0] - piCoords2[8] vector3 = piCoords2[1] - ((piCoords2[7] + piCoords2[8]) / 2) prod1 = np.cross(vector1, vector2) prod2 = np.cross(vector1, vector3) prod3 = np.cross(vector2, vector3) normalVector2 = (prod1 + prod2 + prod3) / 3 except: pass elif piSystems[j].resname == "HIS" or piSystems[ j].resname == "HSD" or piSystems[ j].resname == "HSE" or piSystems[j].resname == "HSP": try: piCoords2 = [ piSystems[j].atoms.CG.position, piSystems[j].atoms.ND1.position, piSystems[j].atoms.CE1.position, piSystems[j].atoms.NE2.position, piSystems[j].atoms.CD2.position ] #computing normal vector vector1 = piCoords2[1] - piCoords2[3] vector2 = piCoords2[0] - piCoords2[2] vector3 = piCoords2[0] - ((piCoords2[2] + piCoords2[3]) / 2) prod1 = np.cross(vector1, vector2) prod2 = np.cross(vector1, vector3) prod3 = np.cross(vector2, vector3) normalVector2 = (prod1 + prod2 + prod3) / 3 except: pass #computing centroid for the second ring if str(piCoords2) != str(np.zeros(3)): for coord in piCoords2: if str(centroid2) == str(np.zeros(3)): centroid2 = coord else: centroid2 += coord centroid2 /= len(piCoords2) #computing distance to know if it can be an interaction dist = distance.euclidean(centroid1, centroid2) if dist <= Dist: node1 = piSystems[i].resname + ":" + piSystems[ i].segment.segid + ":" + str(piSystems[i].resid) node2 = piSystems[j].resname + ":" + piSystems[ j].segment.segid + ":" + str(piSystems[j].resid) if nodes.has_key(node1) and nodes.has_key(node2): edge_name = str(node1) + "-(pi-pi)-" + str(node2) #now we define the dihedral angle and two distances defined as n and p #n represents the distance in A between the origin of the orthogonal system (the ring centroid) and the projection of the mass center of the coupled ring j on the Z-axis of the so defined orthogonal system #p is the distance in A between the origin of the orthogonal system and the projection of the mass center of the ring j on the XY plane. #calculating angle between 2 normal vector we can get the dihedral angle dihedral = Angle.angle_twoVectors(normalVector1, normalVector2) #to get n and p we will change the plane of j-ring and we will use pitagoras theorem traslated_centroid = centroid2 * 1 #*1 is to get a copy of coords and not a copy of the pointer to the coords traslated_centroid[2] = centroid1[2] n = distance.euclidean(centroid1, traslated_centroid) p = math.sqrt((centroid2[2] - traslated_centroid[2])**2) orientation = "undefined" #now we will define the spatial position if (dihedral >= 0 and dihedral < 30) or (dihedral >= 150 and dihedral < 180): orientation = "Parallel orientation" if (dihedral >= 30 and dihedral < 150): if p < 3.5: orientation = "T-orientation with the edge to face" elif p >= 3.5 and n < 3: orientation = "T-orientation with the face to the edge" else: #p>=3.5 and n >=3 orientation = "L-orientation" toReturn.append( str(nodes[node1]) + "\t" + str(nodes[node2]) + "\t" + str(edge_name) + "\t" + str(dist) + "\t" + str(orientation) + "\n") return toReturn
def parallelPiPi(pdbFrameName): edges = open( outputFolder + "/RIP-MD_Results/Edges/" + pdbFrameName[0] + ".edges", "a") edges.write( "Pi-Pi\nSource Node\tTarget Node\tEdge Name\tDistance (center of rings)\tOrientation\n" ) u = MDAnalysis.Universe(pdbFrameName[1]) ############################################## PIsystems = None try: PIsystems = u.select_atoms( "resname PHE TRP TYR HIS HSD HSE HSP").residues except: PIsystems = u.selectAtoms( "resname PHE TRP TYR HIS HSD HSE HSP").residues for i in range(len(PIsystems)): j = i + 1 while j < len(PIsystems): #///////////////////////////////////////////////////////////////////////////////////////////////////////////// piCoords1 = np.zeros(3) piCoords2 = np.zeros(3) centroid1 = np.zeros(3) centroid2 = np.zeros(3) normalVector1 = np.zeros(3) normalVector2 = np.zeros(3) #geting coords for the first ring if PIsystems[i].resname == "PHE" or PIsystems[i].resname == "TYR": try: piCoords1 = [ PIsystems[i].atoms.CG.position, PIsystems[i].atoms.CD1.position, PIsystems[i].atoms.CD2.position, PIsystems[i].atoms.CE1.position, PIsystems[i].atoms.CE2.position, PIsystems[i].atoms.CZ.position ] #computing normal vector vector1 = piCoords1[0] - piCoords1[5] vector2 = piCoords1[1] - piCoords1[4] vector3 = piCoords1[2] - piCoords1[3] prod1 = np.cross(vector1, vector2) prod2 = np.cross(vector1, vector3) prod3 = np.cross(vector2, vector3) normalVector1 = (prod1 + prod2 + prod3) / 3 except: pass elif PIsystems[i].resname == "TRP": try: piCoords1 = [ PIsystems[i].atoms.CG.position, PIsystems[i].atoms.CD1.position, PIsystems[i].atoms.CD2.position, PIsystems[i].atoms.NE1.position, PIsystems[i].atoms.CE2.position, PIsystems[i].atoms.CE3.position, PIsystems[i].atoms.CZ2.position, PIsystems[i].atoms.CZ3.position, PIsystems[i].atoms.CH2.position ] #computing normal vector vector1 = piCoords1[3] - piCoords1[7] vector2 = piCoords1[0] - piCoords1[8] vector3 = piCoords1[1] - ( (piCoords1[7] + piCoords1[8]) / 2) prod1 = np.cross(vector1, vector2) prod2 = np.cross(vector1, vector3) prod3 = np.cross(vector2, vector3) normalVector1 = (prod1 + prod2 + prod3) / 3 except: pass elif PIsystems[i].resname == "HIS" or PIsystems[ i].resname == "HSD" or PIsystems[ i].resname == "HSE" or PIsystems[i].resname == "HSP": try: piCoords1 = [ PIsystems[i].atoms.CG.position, PIsystems[i].atoms.ND1.position, PIsystems[i].atoms.CE1.position, PIsystems[i].atoms.NE2.position, PIsystems[i].atoms.CD2.position ] #computing normal vector vector1 = piCoords1[1] - piCoords1[3] vector2 = piCoords1[0] - piCoords1[2] vector3 = piCoords1[0] - ( (piCoords1[2] + piCoords1[3]) / 2) prod1 = np.cross(vector1, vector2) prod2 = np.cross(vector1, vector3) prod3 = np.cross(vector2, vector3) normalVector1 = (prod1 + prod2 + prod3) / 3 except: pass #only if the first ring is complete we will compute this with the second one if str(piCoords1) != str(np.zeros(3)): for coord in piCoords1: if str(centroid1) == str(np.zeros(3)): centroid1 = coord else: centroid1 += coord centroid1 = centroid1 / len(piCoords1) #geting coords for the second ring if PIsystems[j].resname == "PHE" or PIsystems[ j].resname == "TYR": try: piCoords2 = [ PIsystems[j].atoms.CG.position, PIsystems[j].atoms.CD1.position, PIsystems[j].atoms.CD2.position, PIsystems[j].atoms.CE1.position, PIsystems[j].atoms.CE2.position, PIsystems[j].atoms.CZ.position ] #computing normal vector vector1 = piCoords2[0] - piCoords2[5] vector2 = piCoords2[1] - piCoords2[4] vector3 = piCoords2[2] - piCoords2[3] prod1 = np.cross(vector1, vector2) prod2 = np.cross(vector1, vector3) prod3 = np.cross(vector2, vector3) normalVector2 = (prod1 + prod2 + prod3) / 3 except: pass elif PIsystems[j].resname == "TRP": try: piCoords2 = [ PIsystems[j].atoms.CG.position, PIsystems[j].atoms.CD1.position, PIsystems[j].atoms.CD2.position, PIsystems[j].atoms.NE1.position, PIsystems[j].atoms.CE2.position, PIsystems[j].atoms.CE3.position, PIsystems[j].atoms.CZ2.position, PIsystems[j].atoms.CZ3.position, PIsystems[j].atoms.CH2.position ] #computing normal vector vector1 = piCoords2[3] - piCoords2[7] vector2 = piCoords2[0] - piCoords2[8] vector3 = piCoords2[1] - ( (piCoords2[7] + piCoords2[8]) / 2) prod1 = np.cross(vector1, vector2) prod2 = np.cross(vector1, vector3) prod3 = np.cross(vector2, vector3) normalVector2 = (prod1 + prod2 + prod3) / 3 except: pass elif PIsystems[j].resname == "HIS" or PIsystems[ j].resname == "HSD" or PIsystems[ j].resname == "HSE" or PIsystems[ j].resname == "HSP": try: piCoords2 = [ PIsystems[j].atoms.CG.position, PIsystems[j].atoms.ND1.position, PIsystems[j].atoms.CE1.position, PIsystems[j].atoms.NE2.position, PIsystems[j].atoms.CD2.position ] #computing normal vector vector1 = piCoords2[1] - piCoords2[3] vector2 = piCoords2[0] - piCoords2[2] vector3 = piCoords2[0] - ( (piCoords2[2] + piCoords2[3]) / 2) prod1 = np.cross(vector1, vector2) prod2 = np.cross(vector1, vector3) prod3 = np.cross(vector2, vector3) normalVector2 = (prod1 + prod2 + prod3) / 3 except: pass #computing centroid for the second ring if str(piCoords2) != str(np.zeros(3)): for coord in piCoords2: if str(centroid2) == str(np.zeros(3)): centroid2 = coord else: centroid2 += coord centroid2 /= len(piCoords2) #computing distance to know if it can be an interaction dist = distance.euclidean(centroid1, centroid2) if dist <= Dist: node1 = PIsystems[i].resname + ":" + PIsystems[ i].segment.segid + ":" + str(PIsystems[i].resid) node2 = PIsystems[j].resname + ":" + PIsystems[ j].segment.segid + ":" + str(PIsystems[j].resid) if nodes.has_key(node1) and nodes.has_key(node2): edge_name = str(node1) + "-(pi-pi)-" + str(node2) #now we define the dihedral angle and two distances defined as n and p #n represents the distance in A between the origin of the orthogonal system (the ring centroid) and the projection of the mass center of the coupled ring j on the Z-axis of the so defined orthogonal system #p is the distance in A between the origin of the orthogonal system and the projection of the mass center of the ring j on the XY plane. #calculating angle between 2 normal vector we can get the dihedral angle dihedral = Angle.angle_twoVectors( normalVector1, normalVector2) #to get n and p we will change the plane of j-ring and we will use pitagoras theorem traslated_centroid = centroid2 * 1 #*1 is to get a copy of coords and not a copy of the pointer to the coords traslated_centroid[2] = centroid1[2] n = distance.euclidean(centroid1, traslated_centroid) p = math.sqrt( (centroid2[2] - traslated_centroid[2])**2) orientation = "undefined" #now we will define the spatial position if (dihedral >= 0 and dihedral < 30) or (dihedral >= 150 and dihedral < 180): orientation = "Parallel orientation" if (dihedral >= 30 and dihedral < 150): if p < 3.5: orientation = "T-orientation with the edge to face" elif p >= 3.5 and n < 3: orientation = "T-orientation with the face to the edge" else: #p>=3.5 and n >=3 orientation = "L-orientation" edges.write( str(nodes[node1]) + "\t" + str(nodes[node2]) + "\t" + str(edge_name) + "\t" + str(round(dist, 3)) + "\t" + str(orientation) + "\n") #///////////////////////////////////////////////////////////////////////////////////////////////////////////// j += 1 ############################################### edges.write("\n") edges.close() return
def find_best_discord_hotsax(series, win_size, a_size, paa_size, znorm_threshold, globalRegistry, sax_series=None, sax=False): # noqa: C901 """Find the best discord with hotsax.""" """[1.0] get the sax data first""" if sax: sax_none = dict() for s in set(sax_series): sax_none[s] = [i for i in range(len(sax_series)) if sax_series[i] == s] else: sax_none = sax_via_window(series, win_size, a_size, paa_size, "none", 0.01) """[2.0] build the 'magic' array""" magic_array = list() for k, v in sax_none.items(): magic_array.append((k, len(v))) """[2.1] sort it desc by the key""" m_arr = sorted(magic_array, key=lambda tup: tup[1]) """[3.0] define the key vars""" bestSoFarPosition = -1 bestSoFarDistance = 0. distanceCalls = 0 visit_array = np.zeros(len(series), dtype=np.int) """[4.0] and we are off iterating over the magic array entries""" for entry in m_arr: """[5.0] some moar of teh vars""" curr_word = entry[0] occurrences = sax_none[curr_word] """[6.0] jumping around by the same word occurrences makes it easier to nail down the possibly small distance value -- so we can be efficient and all that...""" for curr_pos in occurrences: if curr_pos in globalRegistry: continue """[7.0] we don't want an overlapping subsequence""" mark_start = curr_pos - win_size mark_end = curr_pos + win_size visit_set = set(range(mark_start, mark_end)) """[8.0] here is our subsequence in question""" cur_seq = znorm(series[curr_pos:(curr_pos + win_size)], znorm_threshold) """[9.0] let's see what is NN distance""" nn_dist = np.inf do_random_search = 1 """[10.0] ordered by occurrences search first""" for next_pos in occurrences: """[11.0] skip bad pos""" if next_pos in visit_set: continue else: visit_set.add(next_pos) """[12.0] distance we compute""" dist = euclidean(cur_seq, znorm(series[next_pos:( next_pos+win_size)], znorm_threshold)) distanceCalls += 1 """[13.0] keep the books up-to-date""" if dist < nn_dist: nn_dist = dist if dist < bestSoFarDistance: do_random_search = 0 break """[13.0] if not broken above, we shall proceed with random search""" if do_random_search: """[14.0] build that random visit order array""" curr_idx = 0 for i in range(0, (len(series) - win_size)): if not(i in visit_set): visit_array[curr_idx] = i curr_idx += 1 it_order = np.random.permutation(visit_array[0:curr_idx]) curr_idx -= 1 """[15.0] and go random""" while curr_idx >= 0: rand_pos = it_order[curr_idx] curr_idx -= 1 dist = euclidean(cur_seq, znorm(series[rand_pos:( rand_pos + win_size)], znorm_threshold)) distanceCalls += 1 """[16.0] keep the books up-to-date again""" if dist < nn_dist: nn_dist = dist if dist < bestSoFarDistance: nn_dist = dist break """[17.0] and BIGGER books""" if (nn_dist > bestSoFarDistance) and (nn_dist < np.inf): bestSoFarDistance = nn_dist bestSoFarPosition = curr_pos return (bestSoFarPosition, bestSoFarDistance)
def eye_aspect_ratio(eye): a = distance.euclidean(eye[1], eye[5]) b = distance.euclidean(eye[2], eye[4]) c = distance.euclidean(eye[0], eye[3]) EAR = (a + b) / (2 * c) return EAR
X_test, y_test = digits_data.load_testing() # converting list to nparray X_train, y_train = np.array(X_train), np.array(y_train) X_test, y_test = np.array(X_test), np.array(y_test) # k: value in kNN k = int(sys.argv[1]) correct_pred = 0 for i in xrange(0, 10000): query = X_test[i] distance = [] for j in xrange(0, 60000): # euclidean_distance dist = euclidean(X_train[j], query) distance.append(dist) # finding the nearest neighbor # sort the distance matrix distance = np.array(distance) indices = np.argsort(distance) topk = indices[:k] pred_labels = y_train[topk] found = np.where(pred_labels == y_test) if len(found): correct_pred = correct_pred + 1 print "Accuracy after " + str(i + 1) + " examples: " + str( (correct_pred / (i + 1)) * 100) + "%" accuracy = correct_pred / 100
def parallelCationPi(pdbFrameName): edges=open(outputFolder+"/RIP-MD_Results/Edges/"+pdbFrameName[0]+".edges","a") edges.write("Cation-Pi\nSource Node\tTarget Node\tEdge Name\tDistance (cation to center of ring)\tOrientation\n") u=MDAnalysis.Universe(pdbFrameName[1]) #selecting residues that act as Cations Cations=None try: Cations=u.select_atoms("resname ARG LYS HSP").residues except: Cations=u.selectAtoms("resname ARG LYS HSP").residues #selecting HIS (resname) with HD1 and HE2 atoms try: for HIS in u.select_atoms("resname HIS").residues: flag=0 try: #we look for the positions of HD1 and HE2, specifics atoms for a protonated HIS, #so if this HIS have these atoms we will append the residue to the cation list aux=HIS.HD1.position flag+=1 except: pass try: aux=HIS.HE2.position flag+=1 except: pass if flag==2: Cations.append(HIS) except: for HIS in u.selectAtoms("resname HIS").residues: flag=0 try: #we look for the positions of HD1 and HE2, specifics atoms for a protonated HIS, #so if this HIS have these atoms we will append the residue to the cation list aux=HIS.HD1.position flag+=1 except: pass try: aux=HIS.HE2.position flag+=1 except: pass if flag==2: Cations.append(HIS) #selecting residues that act as a pi system PIsystems=None try: PIsystems=u.select_atoms("resname PHE TRP TYR HIS HSD HSE HSP").residues except: PIsystems=u.selectAtoms("resname PHE TRP TYR HIS HSD HSE HSP").residues for i in range(len(Cations)): for j in range(len(PIsystems)): ########################################### #extracting data for the aromatic residue ########################################### aromaticCoords=None if PIsystems[j].resname=="PHE" or PIsystems[j].resname=="TYR": try: aromaticCoords=[PIsystems[j].CG.position,PIsystems[j].CD1.position,PIsystems[j].CD2.position,PIsystems[j].CE1.position,PIsystems[j].CE2.position,PIsystems[j].CZ.position] except: pass elif PIsystems[j].resname=="TRP": try: aromaticCoords=[PIsystems[j].CG.position,PIsystems[j].CD1.position,PIsystems[j].CD2.position,PIsystems[j].NE1.position,PIsystems[j].CE2.position,PIsystems[j].CE3.position,PIsystems[j].CZ2.position,PIsystems[j].CZ3.position,PIsystems[j].CH2.position] except: pass elif PIsystems[j].resname=="HIS" or PIsystems[j].resname=="HSD" or PIsystems[j].resname=="HSE" or PIsystems[j].resname=="HSP": try: aromaticCoords=[PIsystems[j].CG.position,PIsystems[j].ND1.position,PIsystems[j].CE1.position,PIsystems[j].NE2.position,PIsystems[j].CD2.position] except: pass if aromaticCoords!=None: #getting the centroid aux=np.zeros(3) for coord in aromaticCoords: # if aux==None: # try: # print type(coord) #aux=coord #print aux #else: #print coord aux+=coord centroid=aux/len(aromaticCoords) ################################### #extracting charge information ################################### pointOfCharge=np.zeros(3) if Cations[i].resname=="ARG": try: pointOfCharge=Cations[i].NH1.position except: pass elif Cations[i].resname=="LYS": try: pointOfCharge=Cations[i].NZ.position except: pass elif Cations[i].resname=="HSP" or Cations[i].resname=="HIS": try: pointOfCharge=Cations[i].NE2.postition except: pass if str(pointOfCharge)!=str(np.zeros(3)): ############################################################ #now we will compute normal vector for the aromatic residues ############################################################ normalVector=np.zeros(3) try: if PIsystems[j].resname=="PHE" or PIsystems[j].resname=="TYR": v1=PIsystems[j].atoms.CG.position-PIsystems[j].atoms.CZ.position v2=PIsystems[j].atoms.CD1.position-PIsystems[j].atoms.CE2.position v3=PIsystems[j].atoms.CD2.position-PIsystems[j].atoms.CE1.position prod1=np.cross(v1,v2) prod2=np.cross(v1,v3) prod3=np.cross(v2,v3) normalVector=(prod1+prod2+prod3)/3 if PIsystems[j].resname=="TRP": v1=PIsystems[j].atoms.NE1.position-PIsystems[j].atoms.CZ3.position v2=PIsystems[j].atoms.CG.position-PIsystems[j].atoms.CH2.position v3=PIsystems[j].atoms.CD1.position-((PIsystems[j].atoms.CZ3.position+PIsystems[j].atoms.CH2.position)/2.) prod1=np.cross(v1,v2) prod2=np.cross(v1,v3) prod3=np.cross(v2,v3) normalVector=(prod1+prod2+prod3)/3 if PIsystems[j].resname=="HIS" or PIsystems[j].resname=="HSD" or PIsystems[j].resname=="HSE" or PIsystems[j].resname=="HSP": v1=PIsystems[j].atoms.ND1.position-PIsystems[j].atoms.NE2.position v2=PIsystems[j].atoms.CD2.position-PIsystems[j].atoms.CE1.position v3=PIsystems[j].atoms.CG.position-((PIsystems[j].atoms.CE1.position+PIsystems[j].atoms.NE2.position)/2.) prod1=np.cross(v1,v2) prod2=np.cross(v1,v3) prod3=np.cross(v2,v3) normalVector=(prod1+prod2+prod3)/3 except: pass if str(normalVector)!=str(np.zeros(3)): #computing distance between the charge and the dist=distance.euclidean(pointOfCharge,centroid) if dist<=Distance: #if distance between cation and center of the ring is less that cutoff angle=Angle.angle(pointOfCharge,centroid, normalVector)#calculate the angle between 2 vectors, the vector between centroid of the ring and cation and the normal vector if (angle>=a1 and angle<=a2) or (angle<=a3 and angle>=a4): node1=None node2=None try: node1=Cations[i].resname+":"+Cations[i].segment.segid+":"+str(Cations[i].resid) node2=PIsystems[j].resname+":"+PIsystems[j].segment.segid+":"+str(PIsystems[j].resid) except: pass if nodes.has_key(node1) and nodes.has_key(node2): edge_name=node1+"-(cation-pi)-"+node2 last_less_dist=1000 #a high value to be reemplaced at first loop closer_atom=None #we will loop over aromatic atoms positions to see what atom is the closer one, with this we will compute the dihedral angle for pos in aromaticCoords: aux=distance.euclidean(pointOfCharge,pos) if aux<last_less_dist: last_less_dist=aux closer_atom=pos # dihedral angle calculated between CA of the cation, the mass center of cation, closer atom and mass center of ring dihedral=None try: dihedral=Angle.dihedral(Cations[i].CA.position,pointOfCharge, closer_atom, centroid) except: pass if dihedral!=None: kind="" if (dihedral<a5 and dihedral>=a6) or (dihedral<=a7 and dihedral>a8): kind="planar" elif (dihedral<=a9 and dihedral>=a10) or (dihedral>=a11 and dihedral<=a12): kind="oblique" elif (dihedral>a13 and dihedral<a14): kind="orthogonal" edges.write(str(nodes[node1])+"\t"+str(nodes[node2])+"\t"+str(edge_name)+"\t"+str(round(dist,3))+"\t"+str(kind)+"\n") edges.write("\n") edges.close() return
def mouth_aspect_ratio(mouth): a = distance.euclidean(mouth[5], mouth[8]) b = distance.euclidean(mouth[1], mouth[10]) c = distance.euclidean(mouth[0], mouth[6]) MAR = (a + b) / (2 * c) return MAR