agitter commited on
Commit
a90e462
·
verified ·
1 Parent(s): 96ebc35

Upload model

Browse files
Files changed (2) hide show
  1. huggingface_wrapper.py +331 -329
  2. model.safetensors +1 -1
huggingface_wrapper.py CHANGED
@@ -1283,83 +1283,212 @@ def main():
1283
 
1284
  if __name__ == "__main__":
1285
  main()
1286
- """ Encodes data in different formats """
1287
 
1288
 
1289
- class Encoding(Enum):
1290
- INT_SEQS = auto()
1291
- ONE_HOT = auto()
 
 
 
1292
 
1293
 
1294
- class DataEncoder:
1295
- chars = [
1296
- "*",
1297
- "A",
1298
- "C",
1299
- "D",
1300
- "E",
1301
- "F",
1302
- "G",
1303
- "H",
1304
- "I",
1305
- "K",
1306
- "L",
1307
- "M",
1308
- "N",
1309
- "P",
1310
- "Q",
1311
- "R",
1312
- "S",
1313
- "T",
1314
- "V",
1315
- "W",
1316
- "Y",
1317
- ]
1318
- num_chars = len(chars)
1319
- mapping = {c: i for i, c in enumerate(chars)}
1320
 
1321
- def __init__(self, encoding: Encoding = Encoding.INT_SEQS):
1322
- self.encoding = encoding
1323
 
1324
- def _encode_from_int_seqs(self, seq_ints):
1325
- if self.encoding == Encoding.INT_SEQS:
1326
- return seq_ints
1327
- elif self.encoding == Encoding.ONE_HOT:
1328
- one_hot = np.eye(self.num_chars)[seq_ints]
1329
- return one_hot.astype(np.float32)
1330
 
1331
- def encode_sequences(self, char_seqs):
1332
- seq_ints = []
1333
- for char_seq in char_seqs:
1334
- int_seq = [self.mapping[c] for c in char_seq]
1335
- seq_ints.append(int_seq)
1336
- seq_ints = np.array(seq_ints).astype(int)
1337
- return self._encode_from_int_seqs(seq_ints)
1338
 
1339
- def encode_variants(self, wt, variants):
1340
- # convert wild type seq to integer encoding
1341
- wt_int = np.zeros(len(wt), dtype=np.uint8)
1342
- for i, c in enumerate(wt):
1343
- wt_int[i] = self.mapping[c]
1344
 
1345
- # tile the wild-type seq
1346
- seq_ints = np.tile(wt_int, (len(variants), 1))
 
1347
 
1348
- for i, variant in enumerate(variants):
1349
- # special handling if we want to encode the wild-type seq (it's already correct!)
1350
- if variant == "_wt":
1351
- continue
1352
 
1353
- # variants are a list of mutations [mutation1, mutation2, ....]
1354
- variant = variant.split(",")
1355
- for mutation in variant:
1356
- # mutations are in the form <original char><position><replacement char>
1357
- position = int(mutation[1:-1])
1358
- replacement = self.mapping[mutation[-1]]
1359
- seq_ints[i, position] = replacement
1360
 
1361
- seq_ints = seq_ints.astype(int)
1362
- return self._encode_from_int_seqs(seq_ints)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1363
 
1364
 
1365
  UUID_URL_MAP = {
@@ -2087,300 +2216,173 @@ class RelativeTransformerEncoderLayer(nn.Module):
2087
  # Legacy string support for activation function.
2088
  if isinstance(activation, str):
2089
  self.activation = get_activation_fn(activation)
2090
- else:
2091
- self.activation = activation
2092
-
2093
- def forward(self, src: Tensor, pdb_fn=None) -> Tensor:
2094
- x = src
2095
- if self.norm_first:
2096
- x = x + self._sa_block(self.norm1(x), pdb_fn=pdb_fn)
2097
- x = x + self._ff_block(self.norm2(x))
2098
- else:
2099
- x = self.norm1(x + self._sa_block(x))
2100
- x = self.norm2(x + self._ff_block(x))
2101
-
2102
- return x
2103
-
2104
- # self-attention block
2105
- def _sa_block(self, x: Tensor, pdb_fn=None) -> Tensor:
2106
- x = self.self_attn(x, x, x, pdb_fn=pdb_fn)
2107
- if isinstance(x, dict):
2108
- # handle the case where we are returning attention weights
2109
- x = x["attn_output"]
2110
- return self.dropout1(x)
2111
-
2112
- # feed forward block
2113
- def _ff_block(self, x: Tensor) -> Tensor:
2114
- x = self.linear2(self.dropout(self.activation(self.linear1(x))))
2115
- return self.dropout2(x)
2116
-
2117
-
2118
- class RelativeTransformerEncoder(nn.Module):
2119
- def __init__(self, encoder_layer, num_layers, norm=None, reset_params=True):
2120
- super(RelativeTransformerEncoder, self).__init__()
2121
- # using get_clones means all layers have the same initialization
2122
- # this is also a problem in PyTorch's TransformerEncoder implementation, which this is based on
2123
- # todo: PyTorch is changing its transformer API... check up on and see if there is a better way
2124
- self.layers = _get_clones(encoder_layer, num_layers)
2125
- self.num_layers = num_layers
2126
- self.norm = norm
2127
-
2128
- # important because get_clones means all layers have same initialization
2129
- # should recursively reset parameters for all submodules
2130
- if reset_params:
2131
- self.apply(reset_parameters_helper)
2132
-
2133
- def forward(self, src: Tensor, pdb_fn=None) -> Tensor:
2134
- output = src
2135
-
2136
- for mod in self.layers:
2137
- output = mod(output, pdb_fn=pdb_fn)
2138
-
2139
- if self.norm is not None:
2140
- output = self.norm(output)
2141
-
2142
- return output
2143
-
2144
-
2145
- def _get_clones(module, num_clones):
2146
- return nn.ModuleList([copy.deepcopy(module) for _ in range(num_clones)])
2147
-
2148
-
2149
- def _inv_dict(d):
2150
- """helper function for contact map-based position embeddings"""
2151
- inv = dict()
2152
- for k, v in d.items():
2153
- # collect dict keys into lists based on value
2154
- inv.setdefault(v, list()).append(k)
2155
- for k, v in inv.items():
2156
- # put in sorted order
2157
- inv[k] = sorted(v)
2158
- return inv
2159
-
2160
-
2161
- def _combine_d(d, threshold, combined_key):
2162
- """helper function for contact map-based position embeddings
2163
- d is a dictionary with ints as keys and lists as values.
2164
- for all keys >= threshold, this function combines the values of those keys into a single list
2165
- """
2166
- out_d = {}
2167
- for k, v in d.items():
2168
- if k < threshold:
2169
- out_d[k] = v
2170
- elif k >= threshold:
2171
- if combined_key not in out_d:
2172
- out_d[combined_key] = v
2173
- else:
2174
- out_d[combined_key] += v
2175
- if combined_key in out_d:
2176
- out_d[combined_key] = sorted(out_d[combined_key])
2177
- return out_d
2178
-
2179
-
2180
- class GraphType(Enum):
2181
- LINEAR = auto()
2182
- COMPLETE = auto()
2183
- DISCONNECTED = auto()
2184
- DIST_THRESH = auto()
2185
- DIST_THRESH_SHUFFLED = auto()
2186
-
2187
-
2188
- def save_graph(g, fn):
2189
- """Saves graph to file"""
2190
- nx.write_gexf(g, fn)
2191
-
2192
-
2193
- def load_graph(fn):
2194
- """Loads graph from file"""
2195
- g = nx.read_gexf(fn, node_type=int)
2196
- return g
2197
-
2198
-
2199
- def shuffle_nodes(g, seed=7):
2200
- """Shuffles the nodes of the given graph and returns a copy of the shuffled graph"""
2201
- # get the list of nodes in this graph
2202
- nodes = g.nodes()
2203
-
2204
- # create a permuted list of nodes
2205
- np.random.seed(seed)
2206
- nodes_shuffled = np.random.permutation(nodes)
2207
-
2208
- # create a dictionary mapping from old node label to new node label
2209
- mapping = {n: ns for n, ns in zip(nodes, nodes_shuffled)}
2210
-
2211
- g_shuffled = nx.relabel_nodes(g, mapping, copy=True)
2212
-
2213
- return g_shuffled
2214
-
2215
-
2216
- def linear_graph(num_residues):
2217
- """Creates a linear graph where each node is connected to its sequence neighbor in order"""
2218
- g = nx.Graph()
2219
- g.add_nodes_from(np.arange(0, num_residues))
2220
- for i in range(num_residues - 1):
2221
- g.add_edge(i, i + 1)
2222
- return g
2223
-
2224
-
2225
- def complete_graph(num_residues):
2226
- """Creates a graph where each node is connected to all other nodes"""
2227
- g = nx.complete_graph(num_residues)
2228
- return g
2229
-
2230
-
2231
- def disconnected_graph(num_residues):
2232
- g = nx.Graph()
2233
- g.add_nodes_from(np.arange(0, num_residues))
2234
- return g
2235
 
 
 
 
 
 
 
 
 
2236
 
2237
- def dist_thresh_graph(dist_mtx, threshold):
2238
- """Creates undirected graph based on a distance threshold"""
2239
- g = nx.Graph()
2240
- g.add_nodes_from(np.arange(0, dist_mtx.shape[0]))
2241
 
2242
- # loop through each residue
2243
- for rn1 in range(len(dist_mtx)):
2244
- # find all residues that are within threshold distance of current
2245
- rns_within_threshold = np.where(dist_mtx[rn1] < threshold)[0]
 
 
 
2246
 
2247
- # add edges from current residue to those that are within threshold
2248
- for rn2 in rns_within_threshold:
2249
- # don't add self edges
2250
- if rn1 != rn2:
2251
- g.add_edge(rn1, rn2)
2252
- return g
2253
 
2254
 
2255
- def ordered_adjacency_matrix(g):
2256
- """returns the adjacency matrix ordered by node label in increasing order as a numpy array"""
2257
- node_order = sorted(g.nodes())
2258
- adj_mtx = nx.to_numpy_matrix(g, nodelist=node_order)
2259
- return np.asarray(adj_mtx).astype(np.float32)
 
 
 
 
2260
 
 
 
 
 
2261
 
2262
- def cbeta_distance_matrix(pdb_fn, start=0, end=None):
2263
- # note that start and end are not going by residue number
2264
- # they are going by whatever the listing in the pdb file is
2265
 
2266
- # read the pdb file into a biopandas object
2267
- ppdb = PandasPdb().read_pdb(pdb_fn)
2268
 
2269
- # group by residue number
2270
- # important to specify sort=True so that group keys (residue number) are in order
2271
- # the reason is we loop through group keys below, and assume that residues are in order
2272
- # the pandas function has sort=True by default, but we specify it anyway because it is important
2273
- grouped = ppdb.df["ATOM"].groupby("residue_number", sort=True)
2274
 
2275
- # a list of coords for the cbeta or calpha of each residue
2276
- coords = []
2277
 
2278
- # loop through each residue and find the coordinates of cbeta
2279
- for i, (residue_number, values) in enumerate(grouped):
2280
 
2281
- # skip residues not in the range
2282
- end_index = len(grouped) if end is None else end
2283
- if i not in range(start, end_index):
2284
- continue
2285
 
2286
- residue_group = grouped.get_group(residue_number)
2287
 
2288
- atom_names = residue_group["atom_name"]
2289
- if "CB" in atom_names.values:
2290
- # print("Using CB...")
2291
- atom_name = "CB"
2292
- elif "CA" in atom_names.values:
2293
- # print("Using CA...")
2294
- atom_name = "CA"
2295
- else:
2296
- raise ValueError(
2297
- "Couldn't find CB or CA for residue {}".format(residue_number)
2298
- )
2299
 
2300
- # get the coordinates of cbeta (or calpha)
2301
- coords.append(
2302
- residue_group[residue_group["atom_name"] == atom_name][
2303
- ["x_coord", "y_coord", "z_coord"]
2304
- ].values[0]
2305
- )
2306
 
2307
- # stack the coords into a numpy array where each row has the x,y,z coords for a different residue
2308
- coords = np.stack(coords)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2309
 
2310
- # compute pairwise euclidean distance between all cbetas
2311
- dist_mtx = cdist(coords, coords, metric="euclidean")
2312
 
2313
- return dist_mtx
2314
 
2315
 
2316
- def get_neighbors(g, nodes):
2317
- """returns a list (set) of neighbors of all given nodes"""
2318
- neighbors = set()
2319
- for n in nodes:
2320
- neighbors.update(g.neighbors(n))
2321
- return sorted(list(neighbors))
2322
 
2323
 
2324
- def gen_graph(
2325
- graph_type,
2326
- res_dist_mtx,
2327
- dist_thresh=7,
2328
- shuffle_seed=7,
2329
- graph_save_dir=None,
2330
- save=False,
2331
- ):
2332
- """generate the specified structure graph using the specified residue distance matrix"""
2333
- if graph_type is GraphType.LINEAR:
2334
- g = linear_graph(len(res_dist_mtx))
2335
- save_fn = None if not save else os.path.join(graph_save_dir, "linear.graph")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2336
 
2337
- elif graph_type is GraphType.COMPLETE:
2338
- g = complete_graph(len(res_dist_mtx))
2339
- save_fn = None if not save else os.path.join(graph_save_dir, "complete.graph")
2340
 
2341
- elif graph_type is GraphType.DISCONNECTED:
2342
- g = disconnected_graph(len(res_dist_mtx))
2343
- save_fn = (
2344
- None if not save else os.path.join(graph_save_dir, "disconnected.graph")
2345
- )
 
2346
 
2347
- elif graph_type is GraphType.DIST_THRESH:
2348
- g = dist_thresh_graph(res_dist_mtx, dist_thresh)
2349
- save_fn = (
2350
- None
2351
- if not save
2352
- else os.path.join(
2353
- graph_save_dir, "dist_thresh_{}.graph".format(dist_thresh)
2354
- )
2355
- )
2356
 
2357
- elif graph_type is GraphType.DIST_THRESH_SHUFFLED:
2358
- g = dist_thresh_graph(res_dist_mtx, dist_thresh)
2359
- g = shuffle_nodes(g, seed=shuffle_seed)
2360
- save_fn = (
2361
- None
2362
- if not save
2363
- else os.path.join(
2364
- graph_save_dir,
2365
- "dist_thresh_{}_shuffled_r{}.graph".format(dist_thresh, shuffle_seed),
2366
- )
2367
- )
2368
 
2369
- else:
2370
- raise ValueError("Graph type {} is not implemented".format(graph_type))
2371
 
2372
- if save:
2373
- if isfile(save_fn):
2374
- print(
2375
- "err: graph already exists: {}. to overwrite, delete the existing file first".format(
2376
- save_fn
2377
- )
2378
- )
2379
- else:
2380
- os.makedirs(graph_save_dir, exist_ok=True)
2381
- save_graph(g, save_fn)
2382
 
2383
- return g
 
 
 
 
 
 
 
 
 
2384
 
2385
 
2386
  # Huggingface code
 
1283
 
1284
  if __name__ == "__main__":
1285
  main()
 
1286
 
1287
 
1288
+ class GraphType(Enum):
1289
+ LINEAR = auto()
1290
+ COMPLETE = auto()
1291
+ DISCONNECTED = auto()
1292
+ DIST_THRESH = auto()
1293
+ DIST_THRESH_SHUFFLED = auto()
1294
 
1295
 
1296
+ def save_graph(g, fn):
1297
+ """Saves graph to file"""
1298
+ nx.write_gexf(g, fn)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1299
 
 
 
1300
 
1301
+ def load_graph(fn):
1302
+ """Loads graph from file"""
1303
+ g = nx.read_gexf(fn, node_type=int)
1304
+ return g
 
 
1305
 
 
 
 
 
 
 
 
1306
 
1307
+ def shuffle_nodes(g, seed=7):
1308
+ """Shuffles the nodes of the given graph and returns a copy of the shuffled graph"""
1309
+ # get the list of nodes in this graph
1310
+ nodes = g.nodes()
 
1311
 
1312
+ # create a permuted list of nodes
1313
+ np.random.seed(seed)
1314
+ nodes_shuffled = np.random.permutation(nodes)
1315
 
1316
+ # create a dictionary mapping from old node label to new node label
1317
+ mapping = {n: ns for n, ns in zip(nodes, nodes_shuffled)}
 
 
1318
 
1319
+ g_shuffled = nx.relabel_nodes(g, mapping, copy=True)
 
 
 
 
 
 
1320
 
1321
+ return g_shuffled
1322
+
1323
+
1324
+ def linear_graph(num_residues):
1325
+ """Creates a linear graph where each node is connected to its sequence neighbor in order"""
1326
+ g = nx.Graph()
1327
+ g.add_nodes_from(np.arange(0, num_residues))
1328
+ for i in range(num_residues - 1):
1329
+ g.add_edge(i, i + 1)
1330
+ return g
1331
+
1332
+
1333
+ def complete_graph(num_residues):
1334
+ """Creates a graph where each node is connected to all other nodes"""
1335
+ g = nx.complete_graph(num_residues)
1336
+ return g
1337
+
1338
+
1339
+ def disconnected_graph(num_residues):
1340
+ g = nx.Graph()
1341
+ g.add_nodes_from(np.arange(0, num_residues))
1342
+ return g
1343
+
1344
+
1345
+ def dist_thresh_graph(dist_mtx, threshold):
1346
+ """Creates undirected graph based on a distance threshold"""
1347
+ g = nx.Graph()
1348
+ g.add_nodes_from(np.arange(0, dist_mtx.shape[0]))
1349
+
1350
+ # loop through each residue
1351
+ for rn1 in range(len(dist_mtx)):
1352
+ # find all residues that are within threshold distance of current
1353
+ rns_within_threshold = np.where(dist_mtx[rn1] < threshold)[0]
1354
+
1355
+ # add edges from current residue to those that are within threshold
1356
+ for rn2 in rns_within_threshold:
1357
+ # don't add self edges
1358
+ if rn1 != rn2:
1359
+ g.add_edge(rn1, rn2)
1360
+ return g
1361
+
1362
+
1363
+ def ordered_adjacency_matrix(g):
1364
+ """returns the adjacency matrix ordered by node label in increasing order as a numpy array"""
1365
+ node_order = sorted(g.nodes())
1366
+ adj_mtx = nx.to_numpy_matrix(g, nodelist=node_order)
1367
+ return np.asarray(adj_mtx).astype(np.float32)
1368
+
1369
+
1370
+ def cbeta_distance_matrix(pdb_fn, start=0, end=None):
1371
+ # note that start and end are not going by residue number
1372
+ # they are going by whatever the listing in the pdb file is
1373
+
1374
+ # read the pdb file into a biopandas object
1375
+ ppdb = PandasPdb().read_pdb(pdb_fn)
1376
+
1377
+ # group by residue number
1378
+ # important to specify sort=True so that group keys (residue number) are in order
1379
+ # the reason is we loop through group keys below, and assume that residues are in order
1380
+ # the pandas function has sort=True by default, but we specify it anyway because it is important
1381
+ grouped = ppdb.df["ATOM"].groupby("residue_number", sort=True)
1382
+
1383
+ # a list of coords for the cbeta or calpha of each residue
1384
+ coords = []
1385
+
1386
+ # loop through each residue and find the coordinates of cbeta
1387
+ for i, (residue_number, values) in enumerate(grouped):
1388
+
1389
+ # skip residues not in the range
1390
+ end_index = len(grouped) if end is None else end
1391
+ if i not in range(start, end_index):
1392
+ continue
1393
+
1394
+ residue_group = grouped.get_group(residue_number)
1395
+
1396
+ atom_names = residue_group["atom_name"]
1397
+ if "CB" in atom_names.values:
1398
+ # print("Using CB...")
1399
+ atom_name = "CB"
1400
+ elif "CA" in atom_names.values:
1401
+ # print("Using CA...")
1402
+ atom_name = "CA"
1403
+ else:
1404
+ raise ValueError(
1405
+ "Couldn't find CB or CA for residue {}".format(residue_number)
1406
+ )
1407
+
1408
+ # get the coordinates of cbeta (or calpha)
1409
+ coords.append(
1410
+ residue_group[residue_group["atom_name"] == atom_name][
1411
+ ["x_coord", "y_coord", "z_coord"]
1412
+ ].values[0]
1413
+ )
1414
+
1415
+ # stack the coords into a numpy array where each row has the x,y,z coords for a different residue
1416
+ coords = np.stack(coords)
1417
+
1418
+ # compute pairwise euclidean distance between all cbetas
1419
+ dist_mtx = cdist(coords, coords, metric="euclidean")
1420
+
1421
+ return dist_mtx
1422
+
1423
+
1424
+ def get_neighbors(g, nodes):
1425
+ """returns a list (set) of neighbors of all given nodes"""
1426
+ neighbors = set()
1427
+ for n in nodes:
1428
+ neighbors.update(g.neighbors(n))
1429
+ return sorted(list(neighbors))
1430
+
1431
+
1432
+ def gen_graph(
1433
+ graph_type,
1434
+ res_dist_mtx,
1435
+ dist_thresh=7,
1436
+ shuffle_seed=7,
1437
+ graph_save_dir=None,
1438
+ save=False,
1439
+ ):
1440
+ """generate the specified structure graph using the specified residue distance matrix"""
1441
+ if graph_type is GraphType.LINEAR:
1442
+ g = linear_graph(len(res_dist_mtx))
1443
+ save_fn = None if not save else os.path.join(graph_save_dir, "linear.graph")
1444
+
1445
+ elif graph_type is GraphType.COMPLETE:
1446
+ g = complete_graph(len(res_dist_mtx))
1447
+ save_fn = None if not save else os.path.join(graph_save_dir, "complete.graph")
1448
+
1449
+ elif graph_type is GraphType.DISCONNECTED:
1450
+ g = disconnected_graph(len(res_dist_mtx))
1451
+ save_fn = (
1452
+ None if not save else os.path.join(graph_save_dir, "disconnected.graph")
1453
+ )
1454
+
1455
+ elif graph_type is GraphType.DIST_THRESH:
1456
+ g = dist_thresh_graph(res_dist_mtx, dist_thresh)
1457
+ save_fn = (
1458
+ None
1459
+ if not save
1460
+ else os.path.join(
1461
+ graph_save_dir, "dist_thresh_{}.graph".format(dist_thresh)
1462
+ )
1463
+ )
1464
+
1465
+ elif graph_type is GraphType.DIST_THRESH_SHUFFLED:
1466
+ g = dist_thresh_graph(res_dist_mtx, dist_thresh)
1467
+ g = shuffle_nodes(g, seed=shuffle_seed)
1468
+ save_fn = (
1469
+ None
1470
+ if not save
1471
+ else os.path.join(
1472
+ graph_save_dir,
1473
+ "dist_thresh_{}_shuffled_r{}.graph".format(dist_thresh, shuffle_seed),
1474
+ )
1475
+ )
1476
+
1477
+ else:
1478
+ raise ValueError("Graph type {} is not implemented".format(graph_type))
1479
+
1480
+ if save:
1481
+ if isfile(save_fn):
1482
+ print(
1483
+ "err: graph already exists: {}. to overwrite, delete the existing file first".format(
1484
+ save_fn
1485
+ )
1486
+ )
1487
+ else:
1488
+ os.makedirs(graph_save_dir, exist_ok=True)
1489
+ save_graph(g, save_fn)
1490
+
1491
+ return g
1492
 
1493
 
1494
  UUID_URL_MAP = {
 
2216
  # Legacy string support for activation function.
2217
  if isinstance(activation, str):
2218
  self.activation = get_activation_fn(activation)
2219
+ else:
2220
+ self.activation = activation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2221
 
2222
+ def forward(self, src: Tensor, pdb_fn=None) -> Tensor:
2223
+ x = src
2224
+ if self.norm_first:
2225
+ x = x + self._sa_block(self.norm1(x), pdb_fn=pdb_fn)
2226
+ x = x + self._ff_block(self.norm2(x))
2227
+ else:
2228
+ x = self.norm1(x + self._sa_block(x))
2229
+ x = self.norm2(x + self._ff_block(x))
2230
 
2231
+ return x
 
 
 
2232
 
2233
+ # self-attention block
2234
+ def _sa_block(self, x: Tensor, pdb_fn=None) -> Tensor:
2235
+ x = self.self_attn(x, x, x, pdb_fn=pdb_fn)
2236
+ if isinstance(x, dict):
2237
+ # handle the case where we are returning attention weights
2238
+ x = x["attn_output"]
2239
+ return self.dropout1(x)
2240
 
2241
+ # feed forward block
2242
+ def _ff_block(self, x: Tensor) -> Tensor:
2243
+ x = self.linear2(self.dropout(self.activation(self.linear1(x))))
2244
+ return self.dropout2(x)
 
 
2245
 
2246
 
2247
+ class RelativeTransformerEncoder(nn.Module):
2248
+ def __init__(self, encoder_layer, num_layers, norm=None, reset_params=True):
2249
+ super(RelativeTransformerEncoder, self).__init__()
2250
+ # using get_clones means all layers have the same initialization
2251
+ # this is also a problem in PyTorch's TransformerEncoder implementation, which this is based on
2252
+ # todo: PyTorch is changing its transformer API... check up on and see if there is a better way
2253
+ self.layers = _get_clones(encoder_layer, num_layers)
2254
+ self.num_layers = num_layers
2255
+ self.norm = norm
2256
 
2257
+ # important because get_clones means all layers have same initialization
2258
+ # should recursively reset parameters for all submodules
2259
+ if reset_params:
2260
+ self.apply(reset_parameters_helper)
2261
 
2262
+ def forward(self, src: Tensor, pdb_fn=None) -> Tensor:
2263
+ output = src
 
2264
 
2265
+ for mod in self.layers:
2266
+ output = mod(output, pdb_fn=pdb_fn)
2267
 
2268
+ if self.norm is not None:
2269
+ output = self.norm(output)
 
 
 
2270
 
2271
+ return output
 
2272
 
 
 
2273
 
2274
+ def _get_clones(module, num_clones):
2275
+ return nn.ModuleList([copy.deepcopy(module) for _ in range(num_clones)])
 
 
2276
 
 
2277
 
2278
+ def _inv_dict(d):
2279
+ """helper function for contact map-based position embeddings"""
2280
+ inv = dict()
2281
+ for k, v in d.items():
2282
+ # collect dict keys into lists based on value
2283
+ inv.setdefault(v, list()).append(k)
2284
+ for k, v in inv.items():
2285
+ # put in sorted order
2286
+ inv[k] = sorted(v)
2287
+ return inv
 
2288
 
 
 
 
 
 
 
2289
 
2290
+ def _combine_d(d, threshold, combined_key):
2291
+ """helper function for contact map-based position embeddings
2292
+ d is a dictionary with ints as keys and lists as values.
2293
+ for all keys >= threshold, this function combines the values of those keys into a single list
2294
+ """
2295
+ out_d = {}
2296
+ for k, v in d.items():
2297
+ if k < threshold:
2298
+ out_d[k] = v
2299
+ elif k >= threshold:
2300
+ if combined_key not in out_d:
2301
+ out_d[combined_key] = v
2302
+ else:
2303
+ out_d[combined_key] += v
2304
+ if combined_key in out_d:
2305
+ out_d[combined_key] = sorted(out_d[combined_key])
2306
+ return out_d
2307
 
 
 
2308
 
2309
+ """ Encodes data in different formats """
2310
 
2311
 
2312
+ class Encoding(Enum):
2313
+ INT_SEQS = auto()
2314
+ ONE_HOT = auto()
 
 
 
2315
 
2316
 
2317
+ class DataEncoder:
2318
+ chars = [
2319
+ "*",
2320
+ "A",
2321
+ "C",
2322
+ "D",
2323
+ "E",
2324
+ "F",
2325
+ "G",
2326
+ "H",
2327
+ "I",
2328
+ "K",
2329
+ "L",
2330
+ "M",
2331
+ "N",
2332
+ "P",
2333
+ "Q",
2334
+ "R",
2335
+ "S",
2336
+ "T",
2337
+ "V",
2338
+ "W",
2339
+ "Y",
2340
+ ]
2341
+ num_chars = len(chars)
2342
+ mapping = {c: i for i, c in enumerate(chars)}
2343
 
2344
+ def __init__(self, encoding: Encoding = Encoding.INT_SEQS):
2345
+ self.encoding = encoding
 
2346
 
2347
+ def _encode_from_int_seqs(self, seq_ints):
2348
+ if self.encoding == Encoding.INT_SEQS:
2349
+ return seq_ints
2350
+ elif self.encoding == Encoding.ONE_HOT:
2351
+ one_hot = np.eye(self.num_chars)[seq_ints]
2352
+ return one_hot.astype(np.float32)
2353
 
2354
+ def encode_sequences(self, char_seqs):
2355
+ seq_ints = []
2356
+ for char_seq in char_seqs:
2357
+ int_seq = [self.mapping[c] for c in char_seq]
2358
+ seq_ints.append(int_seq)
2359
+ seq_ints = np.array(seq_ints).astype(int)
2360
+ return self._encode_from_int_seqs(seq_ints)
 
 
2361
 
2362
+ def encode_variants(self, wt, variants):
2363
+ # convert wild type seq to integer encoding
2364
+ wt_int = np.zeros(len(wt), dtype=np.uint8)
2365
+ for i, c in enumerate(wt):
2366
+ wt_int[i] = self.mapping[c]
 
 
 
 
 
 
2367
 
2368
+ # tile the wild-type seq
2369
+ seq_ints = np.tile(wt_int, (len(variants), 1))
2370
 
2371
+ for i, variant in enumerate(variants):
2372
+ # special handling if we want to encode the wild-type seq (it's already correct!)
2373
+ if variant == "_wt":
2374
+ continue
 
 
 
 
 
 
2375
 
2376
+ # variants are a list of mutations [mutation1, mutation2, ....]
2377
+ variant = variant.split(",")
2378
+ for mutation in variant:
2379
+ # mutations are in the form <original char><position><replacement char>
2380
+ position = int(mutation[1:-1])
2381
+ replacement = self.mapping[mutation[-1]]
2382
+ seq_ints[i, position] = replacement
2383
+
2384
+ seq_ints = seq_ints.astype(int)
2385
+ return self._encode_from_int_seqs(seq_ints)
2386
 
2387
 
2388
  # Huggingface code
model.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:263d66cb1e88609b76d7d9aee2a3553bfb39acf6c8186dc724483cb9f9c95024
3
  size 176
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b1dc31b99435c6bdcde45fbe524dc7321e6c0ea13206d0025535cde41cfcaa47
3
  size 176