AmelieSchreiber commited on
Commit
dff8ab6
1 Parent(s): a92b07f

Upload cluster_landscapes_v3.py

Browse files
Files changed (1) hide show
  1. cluster_landscapes_v3.py +134 -0
cluster_landscapes_v3.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ from transformers import EsmModel, AutoTokenizer
4
+ import torch
5
+ from scipy.spatial.distance import pdist, squareform
6
+ from gudhi import RipsComplex
7
+ from gudhi.representations.vector_methods import Landscape
8
+ from sklearn.cluster import DBSCAN
9
+ # import matplotlib.pyplot as plt
10
+ from tqdm import tqdm
11
+
12
+ # Define a helper function for hidden states
13
+ def get_hidden_states(sequence, tokenizer, model, layer):
14
+ model.config.output_hidden_states = True
15
+ encoded_input = tokenizer([sequence], return_tensors='pt', padding=True, truncation=True, max_length=1024)
16
+ with torch.no_grad():
17
+ model_output = model(**encoded_input)
18
+ hidden_states = model_output.hidden_states
19
+ specific_hidden_states = hidden_states[layer][0]
20
+ return specific_hidden_states.numpy()
21
+
22
+ # Define a helper function for Euclidean distance matrix
23
+ def compute_euclidean_distance_matrix(hidden_states):
24
+ euclidean_distances = pdist(hidden_states, metric='euclidean')
25
+ euclidean_distance_matrix = squareform(euclidean_distances)
26
+ return euclidean_distance_matrix
27
+
28
+ # Define a helper function for persistent homology
29
+ def compute_persistent_homology(distance_matrix, max_dimension=0):
30
+ max_edge_length = np.max(distance_matrix)
31
+ rips_complex = RipsComplex(distance_matrix=distance_matrix, max_edge_length=max_edge_length)
32
+ st = rips_complex.create_simplex_tree(max_dimension=max_dimension)
33
+ st.persistence()
34
+ persistence_pairs = np.array([[p[1][0], p[1][1]] for p in st.persistence() if p[0] == 0 and p[1][1] < np.inf]) # Filter out infinite death times
35
+ return st, persistence_pairs
36
+
37
+ # Define a helper function for persistent homology
38
+ def compute_persistent_homology2(distance_matrix, max_dimension=0):
39
+ max_edge_length = np.max(distance_matrix)
40
+ rips_complex = RipsComplex(distance_matrix=distance_matrix, max_edge_length=max_edge_length)
41
+ st = rips_complex.create_simplex_tree(max_dimension=max_dimension)
42
+ st.persistence()
43
+ return st, st.persistence()
44
+
45
+ # Define a helper function for Landscape transformations with tqdm
46
+ #def compute_landscapes(persistence_diagrams, num_landscapes=5, resolution=10000):
47
+ # landscape_transformer = Landscape(num_landscapes=num_landscapes, resolution=resolution)
48
+ # landscapes = landscape_transformer.fit_transform([d for d in persistence_diagrams if len(d) > 0]) # Filter out empty diagrams
49
+ # return landscapes
50
+
51
+ def compute_landscapes(persistence_diagrams, num_landscapes=5, resolution=10000):
52
+ landscape_transformer = Landscape(num_landscapes=num_landscapes, resolution=resolution)
53
+ landscapes = []
54
+
55
+ for diagram in tqdm(persistence_diagrams, desc="Computing Landscapes"):
56
+ if len(diagram) > 0:
57
+ landscape = landscape_transformer.fit_transform([diagram])[0]
58
+ landscapes.append(landscape)
59
+
60
+ return landscapes
61
+
62
+ # Load the tokenizer and model
63
+ tokenizer = AutoTokenizer.from_pretrained("facebook/esm2_t33_650M_UR50D")
64
+ model = EsmModel.from_pretrained("facebook/esm2_t33_650M_UR50D")
65
+
66
+ # Define layer to be used
67
+ layer = model.config.num_hidden_layers - 1
68
+
69
+ # Load the TSV file
70
+ file_path = 'clustering_and_evoprotgrad/filtered_protein_interaction_pairs.tsv'
71
+ protein_pairs_df = pd.read_csv(file_path, sep='\t')
72
+
73
+ # Only process the first 1000 proteins
74
+ protein_pairs_df = protein_pairs_df.head(30000)
75
+
76
+ # Extract concatenated sequences
77
+ concatenated_sequences = protein_pairs_df['Protein1'] + protein_pairs_df['Protein2']
78
+
79
+ # Initialize list to store persistent diagrams
80
+ persistent_diagrams = []
81
+
82
+ # Loop over concatenated sequences to compute their persistent diagrams
83
+ for sequence in tqdm(concatenated_sequences, desc="Computing Persistence Diagrams"):
84
+ hidden_states_matrix = get_hidden_states(sequence, tokenizer, model, layer)
85
+ distance_matrix = compute_euclidean_distance_matrix(hidden_states_matrix)
86
+ _, persistence_diagram = compute_persistent_homology(distance_matrix)
87
+ persistent_diagrams.append(persistence_diagram)
88
+
89
+ # Compute landscapes
90
+ landscapes = compute_landscapes(persistent_diagrams)
91
+
92
+ # Compute the L2 distances between landscapes
93
+ with tqdm(total=len(landscapes)*(len(landscapes)-1)//2, desc="Computing Pairwise L2 Distances") as pbar:
94
+ l2_distances = np.zeros((len(landscapes), len(landscapes)))
95
+ for i in range(len(landscapes)):
96
+ for j in range(i+1, len(landscapes)):
97
+ l2_distances[i, j] = l2_distances[j, i] = np.linalg.norm(landscapes[i] - landscapes[j])
98
+ pbar.update(1)
99
+
100
+ # Compute the second-level persistent homology using the L2 distance matrix
101
+ with tqdm(total=1, desc="Computing Second-Level Persistent Homology") as pbar:
102
+ st_2, persistence_2 = compute_persistent_homology2(l2_distances)
103
+ pbar.update(1)
104
+
105
+ # Function to calculate the epsilon for DBSCAN
106
+ def calculate_epsilon(persistence_diagrams, threshold_percentage, max_eps=np.inf):
107
+ lifetimes = [p[1][1] - p[1][0] for p in persistence_diagrams if p[0] == 0]
108
+ lifetimes.sort()
109
+ threshold_index = int(threshold_percentage * len(lifetimes))
110
+ epsilon = lifetimes[threshold_index]
111
+ # Ensure epsilon is within a reasonable range
112
+ epsilon = min(epsilon, max_eps)
113
+ return epsilon
114
+
115
+ # Calculate epsilon with a maximum threshold
116
+ threshold_percentage = 0.35 # 50%
117
+ max_epsilon = 5000.0 # Example maximum threshold
118
+ epsilon = calculate_epsilon(persistence_2, threshold_percentage, max_eps=max_epsilon)
119
+
120
+ # Perform DBSCAN clustering
121
+ with tqdm(total=1, desc="Performing DBSCAN Clustering") as pbar:
122
+ dbscan = DBSCAN(metric="precomputed", eps=epsilon, min_samples=1)
123
+ dbscan.fit(l2_distances) # Use L2 distances here
124
+ labels = dbscan.labels_
125
+ pbar.update(1)
126
+
127
+ # Add the cluster labels to the DataFrame
128
+ protein_pairs_df['Cluster'] = labels
129
+
130
+ # Save the DataFrame with cluster information
131
+ output_file_path = 'clustering_and_evoprotgrad/clustered_protein_pair_landscapes_l2_dist_100K.tsv'
132
+ protein_pairs_df.to_csv(output_file_path, sep='\t', index=False)
133
+
134
+ print(f"Clustered data saved to: {output_file_path}")