Spaces:
Sleeping
Sleeping
File size: 17,095 Bytes
82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d 82f0f49 88ce25d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 |
from __future__ import annotations
import time
import json
import gradio as gr
from gradio_molecule3d import Molecule3D
import torch
from pinder.core import get_pinder_location
get_pinder_location()
from pytorch_lightning import LightningModule
import torch
import lightning.pytorch as pl
import torch.nn.functional as F
import torch.nn as nn
import torchmetrics
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import MessagePassing
from torch_geometric.nn import global_mean_pool
from torch.nn import Sequential, Linear, BatchNorm1d, ReLU
from torch_scatter import scatter
from torch.nn import Module
import pinder.core as pinder
pinder.__version__
from torch_geometric.loader import DataLoader
from pinder.core.loader.dataset import get_geo_loader
from pinder.core import download_dataset
from pinder.core import get_index
from pinder.core import get_metadata
from pathlib import Path
import pandas as pd
from pinder.core import PinderSystem
import torch
from pinder.core.loader.dataset import PPIDataset
from pinder.core.loader.geodata import NodeRepresentation
import pickle
from pinder.core import get_index, PinderSystem
from torch_geometric.data import HeteroData
import os
from enum import Enum
import numpy as np
import torch
import lightning.pytorch as pl
from numpy.typing import NDArray
from torch_geometric.data import HeteroData
from pinder.core.index.system import PinderSystem
from pinder.core.loader.structure import Structure
from pinder.core.utils import constants as pc
from pinder.core.utils.log import setup_logger
from pinder.core.index.system import _align_monomers_with_mask
from pinder.core.loader.structure import Structure
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import MessagePassing
from torch_geometric.nn import global_mean_pool
from torch.nn import Sequential, Linear, BatchNorm1d, ReLU
from torch_scatter import scatter
from torch.nn import Module
import time
from torch_geometric.nn import global_max_pool
import copy
import inspect
import warnings
from typing import Optional, Tuple, Union
import torch
from torch import Tensor
from torch_geometric.data import Data, Dataset, HeteroData
from torch_geometric.data.feature_store import FeatureStore
from torch_geometric.data.graph_store import GraphStore
from torch_geometric.loader import (
LinkLoader,
LinkNeighborLoader,
NeighborLoader,
NodeLoader,
)
from torch_geometric.loader.dataloader import DataLoader
from torch_geometric.loader.utils import get_edge_label_index, get_input_nodes
from torch_geometric.sampler import BaseSampler, NeighborSampler
from torch_geometric.typing import InputEdges, InputNodes
try:
from lightning.pytorch import LightningDataModule as PLLightningDataModule
no_pytorch_lightning = False
except (ImportError, ModuleNotFoundError):
PLLightningDataModule = object
no_pytorch_lightning = True
from lightning.pytorch.callbacks import ModelCheckpoint
from lightning.pytorch.loggers.tensorboard import TensorBoardLogger
from lightning.pytorch.callbacks.early_stopping import EarlyStopping
from torch_geometric.data.lightning.datamodule import LightningDataset
from pytorch_lightning.loggers.wandb import WandbLogger
def get_system(system_id: str) -> PinderSystem:
return PinderSystem(system_id)
from Bio import PDB
from Bio.PDB.PDBIO import PDBIO
# To create dataset, we have used only PINDER datyaset with following steps as follows:
log = setup_logger(__name__)
try:
from torch_cluster import knn_graph
torch_cluster_installed = True
except ImportError as e:
log.warning(
"torch-cluster is not installed!"
"Please install the appropriate library for your pytorch installation."
"See https://github.com/rusty1s/pytorch_cluster/issues/185 for background."
)
torch_cluster_installed = False
def structure2tensor(
atom_coordinates: NDArray[np.double] | None = None,
atom_types: NDArray[np.str_] | None = None,
element_types: NDArray[np.str_] | None = None,
residue_coordinates: NDArray[np.double] | None = None,
residue_ids: NDArray[np.int_] | None = None,
residue_types: NDArray[np.str_] | None = None,
chain_ids: NDArray[np.str_] | None = None,
dtype: torch.dtype = torch.float32,
) -> dict[str, torch.Tensor]:
property_dict = {}
if atom_types is not None:
unknown_name_idx = max(pc.ALL_ATOM_POSNS.values()) + 1
types_array_at = np.zeros((len(atom_types), 1))
for i, name in enumerate(atom_types):
types_array_at[i] = pc.ALL_ATOM_POSNS.get(name, unknown_name_idx)
property_dict["atom_types"] = torch.tensor(types_array_at).type(dtype)
if element_types is not None:
types_array_ele = np.zeros((len(element_types), 1))
for i, name in enumerate(element_types):
types_array_ele[i] = pc.ELE2NUM.get(name, pc.ELE2NUM["other"])
property_dict["element_types"] = torch.tensor(types_array_ele).type(dtype)
if residue_types is not None:
unknown_name_idx = max(pc.AA_TO_INDEX.values()) + 1
types_array_res = np.zeros((len(residue_types), 1))
for i, name in enumerate(residue_types):
types_array_res[i] = pc.AA_TO_INDEX.get(name, unknown_name_idx)
property_dict["residue_types"] = torch.tensor(types_array_res).type(dtype)
if atom_coordinates is not None:
property_dict["atom_coordinates"] = torch.tensor(atom_coordinates, dtype=dtype)
if residue_coordinates is not None:
property_dict["residue_coordinates"] = torch.tensor(
residue_coordinates, dtype=dtype
)
if residue_ids is not None:
property_dict["residue_ids"] = torch.tensor(residue_ids, dtype=dtype)
if chain_ids is not None:
property_dict["chain_ids"] = torch.zeros(len(chain_ids), dtype=dtype)
property_dict["chain_ids"][chain_ids == "L"] = 1
return property_dict
class NodeRepresentation(Enum):
Surface = "surface"
Atom = "atom"
Residue = "residue"
class PairedPDB(HeteroData): # type: ignore
@classmethod
def from_tuple_system(
cls,
tupal: tuple = (Structure , Structure , Structure),
add_edges: bool = True,
k: int = 10,
) -> PairedPDB:
return cls.from_structure_pair(
holo=tupal[0],
apo=tupal[1],
add_edges=add_edges,
k=k,
)
@classmethod
def from_structure_pair(
cls,
holo: Structure,
apo: Structure,
add_edges: bool = True,
k: int = 10,
) -> PairedPDB:
graph = cls()
holo_calpha = holo.filter("atom_name", mask=["CA"])
apo_calpha = apo.filter("atom_name", mask=["CA"])
r_h = (holo.dataframe['chain_id'] == 'R').sum()
r_a = (apo.dataframe['chain_id'] == 'R').sum()
holo_r_props = structure2tensor(
atom_coordinates=holo.coords[:r_h],
atom_types=holo.atom_array.atom_name[:r_h],
element_types=holo.atom_array.element[:r_h],
residue_coordinates=holo_calpha.coords[:r_h],
residue_types=holo_calpha.atom_array.res_name[:r_h],
residue_ids=holo_calpha.atom_array.res_id[:r_h],
)
holo_l_props = structure2tensor(
atom_coordinates=holo.coords[r_h:],
atom_types=holo.atom_array.atom_name[r_h:],
element_types=holo.atom_array.element[r_h:],
residue_coordinates=holo_calpha.coords[r_h:],
residue_types=holo_calpha.atom_array.res_name[r_h:],
residue_ids=holo_calpha.atom_array.res_id[r_h:],
)
apo_r_props = structure2tensor(
atom_coordinates=apo.coords[:r_a],
atom_types=apo.atom_array.atom_name[:r_a],
element_types=apo.atom_array.element[:r_a],
residue_coordinates=apo_calpha.coords[:r_a],
residue_types=apo_calpha.atom_array.res_name[:r_a],
residue_ids=apo_calpha.atom_array.res_id[:r_a],
)
apo_l_props = structure2tensor(
atom_coordinates=apo.coords[r_a:],
atom_types=apo.atom_array.atom_name[r_a:],
element_types=apo.atom_array.element[r_a:],
residue_coordinates=apo_calpha.coords[r_a:],
residue_types=apo_calpha.atom_array.res_name[r_a:],
residue_ids=apo_calpha.atom_array.res_id[r_a:],
)
graph["ligand"].x = apo_l_props["atom_types"]
graph["ligand"].pos = apo_l_props["atom_coordinates"]
graph["receptor"].x = apo_r_props["atom_types"]
graph["receptor"].pos = apo_r_props["atom_coordinates"]
graph["ligand"].y = holo_l_props["atom_coordinates"]
# graph["ligand"].pos = holo_l_props["atom_coordinates"]
graph["receptor"].y = holo_r_props["atom_coordinates"]
# graph["receptor"].pos = holo_r_props["atom_coordinates"]
if add_edges and torch_cluster_installed:
graph["ligand"].edge_index = knn_graph(
graph["ligand"].pos, k=k
)
graph["receptor"].edge_index = knn_graph(
graph["receptor"].pos, k=k
)
# graph["ligand"].edge_index = knn_graph(
# graph["ligand"].pos, k=k
# )
# graph["receptor"].edge_index = knn_graph(
# graph["receptor"].pos, k=k
# )
return graph
index = get_index()
train = index[index.split == "train"].copy()
val = index[index.split == "val"].copy()
test = index[index.split == "test"].copy()
train_filtered = train[(train['apo_R'] == True) & (train['apo_L'] == True)].copy()
val_filtered = val[(val['apo_R'] == True) & (val['apo_L'] == True)].copy()
test_filtered = test[(test['apo_R'] == True) & (test['apo_L'] == True)].copy()
train_apo = [get_system(train_filtered.id.iloc[i]).create_masked_bound_unbound_complexes(
monomer_types=["apo"], renumber_residues=True
) for i in range(0, 10000)]
train_new_apo11 = [get_system(train_filtered.id.iloc[i]).create_masked_bound_unbound_complexes(
monomer_types=["apo"], renumber_residues=True
) for i in range(10000,10908)]
train_new_apo12 = [get_system(train_filtered.id.iloc[i]).create_masked_bound_unbound_complexes(
# monomer_types=["apo"], renumber_residues=True
) for i in range(10908,11816)]
val_new_apo1 = [get_system(val_filtered.id.iloc[i]).create_masked_bound_unbound_complexes(
monomer_types=["apo"], renumber_residues=True
) for i in range(0,342)]
test_new_apo1 = [get_system(test_filtered.id.iloc[i]).create_masked_bound_unbound_complexes(
monomer_types=["apo"], renumber_residues=True
) for i in range(0,342)]
val_apo = val_new_apo1 + train_new_apo11
test_apo = test_new_apo1 + train_new_apo12
import pickle
# with open("train_apo.pkl", "wb") as file:
# pickle.dump(train_apo, file)
# with open("val_apo.pkl", "wb") as file:
# pickle.dump(val_apo, file)
# with open("test_apo.pkl", "wb") as file:
# pickle.dump(test_apo, file)
# with open("train_apo.pkl", "rb") as file:
# train_apo = pickle.load(file)
# with open("val_apo.pkl", "rb") as file:
# val_apo = pickle.load(file)
# with open("test_apo.pkl", "rb") as file:
# test_apo = pickle.load(file)
# # %%
train_geo = [PairedPDB.from_tuple_system(train_apo[i]) for i in range(0,len(train_apo))]
val_geo = [PairedPDB.from_tuple_system(val_apo[i]) for i in range(0,len(val_apo))]
test_geo = [PairedPDB.from_tuple_system(test_apo[i]) for i in range(0,len(test_apo))]
# # %%
# Train= []
# for i in range(0,len(train_geo)):
# data = HeteroData()
# data["ligand"].x = train_geo[i]["ligand"].x
# data['ligand'].y = train_geo[i]["ligand"].y
# data["ligand"].pos = train_geo[i]["ligand"].pos
# data["ligand","ligand"].edge_index = train_geo[i]["ligand"]
# data["receptor"].x = train_geo[i]["receptor"].x
# data['receptor'].y = train_geo[i]["receptor"].y
# data["receptor"].pos = train_geo[i]["receptor"].pos
# data["receptor","receptor"].edge_index = train_geo[i]["receptor"]
# #torch.save(data, f"./data/processed/train_sample_{i}.pt")
# Train.append(data)
from torch_geometric.data import HeteroData
import torch_sparse
from torch_geometric.edge_index import to_sparse_tensor
import torch
# Example of converting edge indices to SparseTensor and storing them in HeteroData
Train1 = []
for i in range(len(train_geo)):
data = HeteroData()
# Define ligand node features
data["ligand"].x = train_geo[i]["ligand"].x
data["ligand"].y = train_geo[i]["ligand"].y
data["ligand"].pos = train_geo[i]["ligand"].pos
# Convert ligand edge index to SparseTensor
ligand_edge_index = train_geo[i]["ligand"]["edge_index"]
data["ligand", "ligand"].edge_index = to_sparse_tensor(ligand_edge_index, sparse_sizes=(train_geo[i]["ligand"].num_nodes,)*2)
# Define receptor node features
data["receptor"].x = train_geo[i]["receptor"].x
data["receptor"].y = train_geo[i]["receptor"].y
data["receptor"].pos = train_geo[i]["receptor"].pos
# Convert receptor edge index to SparseTensor
receptor_edge_index = train_geo[i]["receptor"]["edge_index"]
data["receptor", "receptor"].edge_index = to_sparse_tensor(receptor_edge_index, sparse_sizes=(train_geo[i]["receptor"].num_nodes,)*2)
Train1.append(data)
# # %%
# Val= []
# for i in range(0,len(val_geo)):
# data = HeteroData()
# data["ligand"].x = val_geo[i]["ligand"].x
# data['ligand'].y = val_geo[i]["ligand"].y
# data["ligand"].pos = val_geo[i]["ligand"].pos
# data["ligand","ligand"].edge_index = val_geo[i]["ligand"]
# data["receptor"].x = val_geo[i]["receptor"].x
# data['receptor'].y = val_geo[i]["receptor"].y
# data["receptor"].pos = val_geo[i]["receptor"].pos
# data["receptor","receptor"].edge_index = val_geo[i]["receptor"]
# #torch.save(data, f"./data/processed/val_sample_{i}.pt")
# Val.append(data)
Val1 = []
for i in range(len(val_geo)):
data = HeteroData()
# Define ligand node features
data["ligand"].x = val_geo[i]["ligand"].x
data["ligand"].y = val_geo[i]["ligand"].y
data["ligand"].pos = val_geo[i]["ligand"].pos
# Convert ligand edge index to SparseTensor
ligand_edge_index = val_geo[i]["ligand"]["edge_index"]
data["ligand", "ligand"].edge_index = to_sparse_tensor(ligand_edge_index, sparse_sizes=(val_geo[i]["ligand"].num_nodes,)*2)
# Define receptor node features
data["receptor"].x = val_geo[i]["receptor"].x
data["receptor"].y = val_geo[i]["receptor"].y
data["receptor"].pos = val_geo[i]["receptor"].pos
# Convert receptor edge index to SparseTensor
receptor_edge_index = val_geo[i]["receptor"]["edge_index"]
data["receptor", "receptor"].edge_index = to_sparse_tensor(receptor_edge_index, sparse_sizes=(val_geo[i]["receptor"].num_nodes,)*2)
Val1.append(data)
# # %%
# Test= []
# for i in range(0,len(test_geo)):
# data = HeteroData()
# data["ligand"].x = test_geo[i]["ligand"].x
# data['ligand'].y = test_geo[i]["ligand"].y
# data["ligand"].pos = test_geo[i]["ligand"].pos
# data["ligand","ligand"].edge_index = test_geo[i]["ligand"]
# data["receptor"].x = test_geo[i]["receptor"].x
# data['receptor'].y = test_geo[i]["receptor"].y
# data["receptor"].pos = test_geo[i]["receptor"].pos
# data["receptor","receptor"].edge_index = test_geo[i]["receptor"]
# #torch.save(data, f"./data/processed/test_sample_{i}.pt")
# Test.append(data)
Test1 = []
for i in range(len(test_geo)):
data = HeteroData()
# Define ligand node features
data["ligand"].x = test_geo[i]["ligand"].x
data["ligand"].y = test_geo[i]["ligand"].y
data["ligand"].pos = test_geo[i]["ligand"].pos
# Convert ligand edge index to SparseTensor
ligand_edge_index = test_geo[i]["ligand"]["edge_index"]
data["ligand", "ligand"].edge_index = to_sparse_tensor(ligand_edge_index, sparse_sizes=(test_geo[i]["ligand"].num_nodes,)*2)
# Define receptor node features
data["receptor"].x = test_geo[i]["receptor"].x
data["receptor"].y = test_geo[i]["receptor"].y
data["receptor"].pos = test_geo[i]["receptor"].pos
# Convert receptor edge index to SparseTensor
receptor_edge_index = test_geo[i]["receptor"]["edge_index"]
data["receptor", "receptor"].edge_index = to_sparse_tensor(receptor_edge_index, sparse_sizes=(test_geo[i]["receptor"].num_nodes,)*2)
Test1.append(data)
# with open("Train.pkl", "wb") as file:
# pickle.dump(Train, file)
# with open("Val.pkl", "wb") as file:
# pickle.dump(Val, file)
# with open("Test.pkl", "wb") as file:
# pickle.dump(Test, file)
# with open("Train1.pkl", "rb") as file:
# Train= pickle.load(file)
# with open("Val.pkl", "rb") as file:
# Val = pickle.load(file)
# with open("Test.pkl", "rb") as file:
# Test = pickle.load(file) |