Spaces:
Build error
Build error
Commit ·
fba25b8
0
Parent(s):
Duplicate from simonduerr/diffdock
Browse filesCo-authored-by: Simon Duerr <simonduerr@users.noreply.huggingface.co>
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributesAdded+23
- .gitignoreAdded+164
- LICENSEAdded+21
- README.mdAdded+158
- app.pyAdded+610
- baselines/baseline_evaluation.pyAdded+219
- baselines/baseline_gnina.pyAdded+175
- baselines/baseline_run_tankbind_parallel.shAdded+5
- baselines/baseline_tankbind_evaluation.pyAdded+239
- baselines/baseline_tankbind_runtime.pyAdded+342
- confidence/confidence_train.pyAdded+319
- confidence/dataset.pyAdded+272
- data/protein_ligand_example_csv.csvAdded+2
- data/splits/timesplit_no_lig_overlap_trainAdded+16379
- data/splits/timesplit_no_lig_overlap_valAdded+968
- data/splits/timesplit_testAdded+363
- data/splits/timesplit_test_no_rec_overlapAdded+144
- datasets/__init__.pyAdded
- datasets/conformer_matching.pyAdded+196
- datasets/esm_embedding_preparation.pyAdded+88
- datasets/esm_embeddings_to_pt.pyAdded+17
- datasets/pdbbind.pyAdded+705
- datasets/pdbbind_lm_embedding_preparation.pyAdded+94
- datasets/process_mols.pyAdded+550
- environment.ymlAdded+102
- esm/LICENSEAdded+21
- esm/esm/__init__.pyAdded+12
- esm/esm/axial_attention.pyAdded+239
- esm/esm/constants.pyAdded+10
- esm/esm/data.pyAdded+493
- esm/esm/inverse_folding/__init__.pyAdded+8
- esm/esm/inverse_folding/features.pyAdded+352
- esm/esm/inverse_folding/gvp_encoder.pyAdded+56
- esm/esm/inverse_folding/gvp_modules.pyAdded+473
- esm/esm/inverse_folding/gvp_transformer.pyAdded+137
- esm/esm/inverse_folding/gvp_transformer_encoder.pyAdded+184
- esm/esm/inverse_folding/gvp_utils.pyAdded+68
- esm/esm/inverse_folding/multichain_util.pyAdded+151
- esm/esm/inverse_folding/transformer_decoder.pyAdded+228
- esm/esm/inverse_folding/transformer_layer.pyAdded+304
- esm/esm/inverse_folding/util.pyAdded+320
- esm/esm/model/esm1.pyAdded+200
- esm/esm/model/esm2.pyAdded+147
- esm/esm/model/msa_transformer.pyAdded+238
- esm/esm/modules.pyAdded+418
- esm/esm/multihead_attention.pyAdded+508
- esm/esm/pretrained.pyAdded+397
- esm/esm/rotary_embedding.pyAdded+69
- esm/esm/version.pyAdded+6
- esm/scripts/extract.pyAdded+142
1234567891011121314151617181920212223*.ipynb linguist-vendored=false*.ipynb linguist-detectable=false/jupyter_notebooks linguist-vendored=falsejupyter_notebooks/** linguist-vendoredjupyter_notebooks/** linguist-vendored=falsejupyter_notebooks/* linguist-vendoredjupyter_notebooks/* linguist-vendored=falsedata/esm2_output_back/1a46_protein_processed.pdb_chain_1.pt filter=lfs diff=lfs merge=lfs -textdata/esm2_output/1a46_protein_processed0t6cxvmshf54nq5e.pdb_chain_0.pt filter=lfs diff=lfs merge=lfs -textdata/esm2_output/1a46_protein_processedhoiape3r6cbddini.pdb_chain_0.pt filter=lfs diff=lfs merge=lfs -textdata/esm2_output/1a46_protein_processedhoiape3r6cbddini.pdb_chain_1.pt filter=lfs diff=lfs merge=lfs -textdata/esm2_output/1a46_protein_processeds5c7cs3aj6rvbhy_.pdb_chain_0.pt filter=lfs diff=lfs merge=lfs -textdata/esm2_output/1a46_protein_processedtyfuvx9z8y4_86ft.pdb_chain_0.pt filter=lfs diff=lfs merge=lfs -textdata/esm2_output_back/1a46_protein_processed.pdb_chain_0.pt filter=lfs diff=lfs merge=lfs -textdata/esm2_output/1a46_protein_processed.pdb_chain_0.pt filter=lfs diff=lfs merge=lfs -textdata/esm2_output_back/1cbr_protein.pdb_chain_1.pt filter=lfs diff=lfs merge=lfs -textworkdir/paper_confidence_model/best_model_epoch75.pt filter=lfs diff=lfs merge=lfs -textdata/esm2_output/1a46_protein_processeds5c7cs3aj6rvbhy_.pdb_chain_1.pt filter=lfs diff=lfs merge=lfs -textdata/esm2_output_back/1cbr_protein.pdb_chain_0.pt filter=lfs diff=lfs merge=lfs -textdata/esm2_output/1a46_protein_processed0t6cxvmshf54nq5e.pdb_chain_1.pt filter=lfs diff=lfs merge=lfs -textdata/esm2_output/1a46_protein_processed.pdb_chain_1.pt filter=lfs diff=lfs merge=lfs -textdata/esm2_output/1a46_protein_processedtyfuvx9z8y4_86ft.pdb_chain_1.pt filter=lfs diff=lfs merge=lfs -textworkdir/paper_score_model/best_ema_inference_epoch_model.pt filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164homeworkinference_out_dir_not_specified.plotly_cache.DS_storerenew.shtmux_renew.shimages# Byte-compiled / optimized / DLL files__pycache__/*.py[cod]*$py.class
# C extensions*.so.so3_*
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover.hypothesis/.pytest_cache/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuildertarget/
# Jupyter Notebook.ipynb_checkpoints
# pyenv.python-version
# celery beat schedule filecelerybeat-schedule
# SageMath parsed files*.sage.py
# Environments.env.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder project settings.spyderproject.spyproject
# Rope project settings.ropeproject
# mkdocs documentation/site
# mypy.mypy_cache/local_config_inference2.yml.vscode/
*.zip
.idea/
#################### Project specific.p.npy.score.npy# this ignores everything in data except for the file!/data/data/*!/data/splits!/data/protein_ligand_example_csv.csv!/data/testset_csv.csv!/data/INDEX_general_PL_data.2020test_run
cachewandblogs
# temporary files.openbabel_cachetemp/bsub*stderr*stdout*!/workdir/workdir/*!/workdir/paper_confidence_model!/workdir/paper_score_modelruns2results# this excludes everything in the runs directory except for that specific run!/runs/runs/*!/runs/rigid_redocking!/runs/flexible_self_dockinglocal_config.ymllocal_config_inference.ymllocal_config_confidence.ymltemp1.pytemp5.pytemp3.pytemp4.pytemp5.pytemp6.pytemp7.py123456789101112131415161718192021MIT License
Copyright (c) 2022 Gabriele Corso, Hannes Stärk, Bowen Jing
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158---title: Diffdockemoji: 🐠colorFrom: indigocolorTo: pinksdk: gradiosdk_version: 3.4.1app_file: app.pypinned: falselicense: mitduplicated_from: simonduerr/diffdock---
# DiffDock: Diffusion Steps, Twists, and Turns for Molecular Docking
### [Paper on arXiv](https://arxiv.org/abs/2210.01776)
Implementation of DiffDock, state-of-the-art method for molecular docking, by Gabriele Corso*, Hannes Stark*, Bowen Jing*, Regina Barzilay and Tommi Jaakkola.This repository contains all code, instructions and model weights necessary to run the method or to retrain a model. If you have any question, feel free to open an issue or reach out to us: [gcorso@mit.edu](gcorso@mit.edu), [hstark@mit.edu](hstark@mit.edu), [bjing@mit.edu](bjing@mit.edu).

The repository also contains all the scripts to run the baselines and generate the figures.Additionally, there are visualization videos in `visualizations`.
# Dataset
The files in `data` contain the names for the time-based data split.
If you want to train one of our models with the data then: 1. download it from [zenodo](https://zenodo.org/record/6034088) 2. unzip the directory and place it into `data` such that you have the path `data/PDBBind_processed`
## Setup Environment
We will set up the environment using [Anaconda](https://docs.anaconda.com/anaconda/install/index.html). Clone thecurrent repo
git clone https://github.com/gcorso/DiffDock.git
Create a new environment with all required packages using `environment.yml`. While in the project directory run:
conda env create
Activate the environment
conda activate diffdock
If you want to install the packages yourself in case something does not work, these are the required ones: pytorch pyg pyyaml scipy networkx biopython rdkit-pypi e3nn spyrmsd pandas biopandas
# Running DiffDock on your own complexesWe support multiple input formats depending on whether you only want to make predictions for a single complex or for many at once.\The protein inputs need to be .pdb files. The ligand input can either be a SMILES string or a filetype that RDKit can read like `.sdf` or `.mol2`.
For a single complex: specify the protein with, e.g., `--protein_path protein.pdb` and the ligand with `--ligand_path ligand.sdf` or `--ligand_smiles COc(cc1)ccc1C#N`
For many complexes: create a csv file with paths to proteins and ligand files or SMILES. The first column of the .csv has to be called `protein_path` and the second one `ligand`.An example .csv is at `data/protein_ligand_example_csv.csv` and you would use it with `--protein_ligand_csv protein_ligand_example_csv.csv`.
### Generate the ESM2 embeddings for the proteinsWe will soon also provide weights of a trained model without ESM2 embeddings such that this step is not necessary. Luckily, it is rather easy. First prepare a fasta for ESM2 (for a single protein use `--protein_path protein.pdb` instead):
python datasets/esm_embedding_preparation.py --protein_ligand_csv data/protein_ligand_example_csv.csv --out_file data/prepared_for_esm.fasta Generate the embeddings with ESM2 (assuming that you are in the DiffDock directory):
git clone https://github.com/facebookresearch/esm cd esm pip install -e . cd .. HOME=esm/model_weights python esm/scripts/extract.py esm2_t33_650M_UR50D data/prepared_for_esm.fasta data/esm2_output --repr_layers 33 --include per_tok And done, that is it!
### Run inference
python -m inference --protein_ligand_csv data/protein_ligand_example_csv.csv --out_dir results/user_predictions_small --inference_steps 20 --samples_per_complex 40 --batch_size 10
# Running DiffDock to reproduce paper numbersDownload the data and place it as described in the "Dataset" section above.
### Generate the ESM2 embeddings for the proteinsFirst run:
python datasets/pdbbind_lm_embedding_preparation.py
Use the generated file `data/pdbbind_sequences.fasta` to generate the ESM2 language model embeddings using the library https://github.com/facebookresearch/esm by installing their repository and executing the following in their repository:
python scripts/extract.py esm2_t33_650M_UR50D pdbbind_sequences.fasta embeddings_output --repr_layers 33 --include per_tok
This generates the `embeddings_output` directory which you have to copy into the `data` folder of our repository to have `data/embeddings_output`.Then run the command:
python datasets/esm_embeddings_to_pt.py
### Using the provided model weights for evaluationTo predict binding structures using the provided model weights run:
python -m evaluate --model_dir workdir/paper_score_model --ckpt best_ema_inference_epoch_model.pt --confidence_ckpt best_model_epoch75.pt --confidence_model_dir workdir/paper_confidence_model --run_name DiffDockInference --inference_steps 20 --split_path data/splits/timesplit_test --samples_per_complex 40 --batch_size 10
To additionally save the .sdf files of the generated molecules, add the flag `--save_visualisation`
### Training a model yourself and using those weightsTrain the large score model:
python -m train --run_name big_score_model --test_sigma_intervals --esm_embeddings_path data/esm2_3billion_embeddings.pt --log_dir workdir --lr 1e-3 --tr_sigma_min 0.1 --tr_sigma_max 19 --rot_sigma_min 0.03 --rot_sigma_max 1.55 --batch_size 16 --ns 48 --nv 10 --num_conv_layers 6 --dynamic_max_cross --scheduler plateau --scale_by_sigma --dropout 0.1 --sampling_alpha 1 --sampling_beta 1 --remove_hs --c_alpha_max_neighbors 24 --receptor_radius 15 --num_dataloader_workers 1 --cudnn_benchmark --rot_alpha 1 --rot_beta 1 --tor_alpha 1 --tor_beta 1 --val_inference_freq 5 --num_inference_complexes 500 --use_ema --distance_embed_dim 64 --cross_distance_embed_dim 64 --sigma_embed_dim 64 --scheduler_patience 30 --n_epochs 850
The model weights are saved in the `workdir` directory.
Train a small score model with higher maximum translation sigma that will be used to generate the samples for training the confidence model:
python -m train --run_name small_score_model --test_sigma_intervals --esm_embeddings_path data/esm2_3billion_embeddings.pt --log_dir workdir --lr 1e-3 --tr_sigma_min 0.1 --tr_sigma_max 34 --rot_sigma_min 0.03 --rot_sigma_max 1.55 --batch_size 16 --ns 24 --nv 6 --num_conv_layers 5 --dynamic_max_cross --scheduler plateau --scale_by_sigma --dropout 0.1 --sampling_alpha 1 --sampling_beta 1 --remove_hs --c_alpha_max_neighbors 24 --receptor_radius 15 --num_dataloader_workers 1 --cudnn_benchmark --rot_alpha 1 --rot_beta 1 --tor_alpha 1 --tor_beta 1 --val_inference_freq 5 --num_inference_complexes 500 --use_ema --scheduler_patience 30 --n_epochs 300
In practice, you could also likely achieve the same or better results by using the first score model for creating the samples to train the confidence model, but this is what we did in the paper. The score model used to generate the samples to train the confidence model does not have to be the same as the score model that is used with that confidence model during inference.
Train the confidence model by running the following:
python -m confidence.confidence_train --original_model_dir workdir/small_score_model --run_name confidence_model --inference_steps 20 --samples_per_complex 7 --inf_sched_alpha 1 --inf_sched_beta 1 --batch_size 16 --n_epochs 100 --lr 3e-4 --scheduler_patience 50 --tr_sigma_min 0.1 --tr_sigma_max 34 --rot_sigma_min 0.03 --rot_sigma_max 1.55 --ns 24 --nv 6 --num_conv_layers 5 --dynamic_max_cross --scale_by_sigma --dropout 0.1 --all_atoms --remove_hs --c_alpha_max_neighbors 24 --receptor_radius 15 --esm_embeddings_path data/esm2_3billion_embeddings.pt --main_metric loss --main_metric_goal min --best_model_save_frequency 5 --rmsd_classification_cutoff 2 --cache_creation_id 1 --cache_ids_to_combine 1 2 3 4
first with `--cache_creation_id 1` then `--cache_creation_id 2` etc. up to 4
Now everything is trained and you can run inference with:
python -m evaluate --model_dir workdir/big_score_model --ckpt best_ema_inference_epoch_model.pt --confidence_ckpt best_model_epoch75.pt --confidence_model_dir workdir/confidence_model --run_name DiffDockInference --inference_steps 20 --split_path data/splits/timesplit_test --samples_per_complex 40 --batch_size 10
## Citation @article{corso2022diffdock, title={DiffDock: Diffusion Steps, Twists, and Turns for Molecular Docking}, author = {Corso, Gabriele and Stärk, Hannes and Jing, Bowen and Barzilay, Regina and Jaakkola, Tommi}, journal={arXiv preprint arXiv:2210.01776}, year={2022} }
## LicenseMIT
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610import gradio as grimport os
import copyimport osimport torch
import subprocess
import timefrom argparse import ArgumentParser, Namespace, FileTypefrom rdkit.Chem import RemoveHsfrom functools import partialimport numpy as npimport pandas as pdfrom rdkit import RDLoggerfrom rdkit.Chem import MolFromSmiles, AddHsfrom torch_geometric.loader import DataLoaderimport yamlimport sysimport csv
csv.field_size_limit(sys.maxsize)
print(torch.__version__)os.makedirs("data/esm2_output", exist_ok=True)os.makedirs("results", exist_ok=True)from datasets.process_mols import ( read_molecule, generate_conformer, write_mol_with_coords,)from datasets.pdbbind import PDBBindfrom utils.diffusion_utils import t_to_sigma as t_to_sigma_compl, get_t_schedulefrom utils.sampling import randomize_position, samplingfrom utils.utils import get_modelfrom utils.visualise import PDBFilefrom tqdm import tqdmfrom datasets.esm_embedding_preparation import esm_embedding_prepimport subprocess
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
with open(f"workdir/paper_score_model/model_parameters.yml") as f: score_model_args = Namespace(**yaml.full_load(f))
with open(f"workdir/paper_confidence_model/model_parameters.yml") as f: confidence_args = Namespace(**yaml.full_load(f))
import shutil
t_to_sigma = partial(t_to_sigma_compl, args=score_model_args)
model = get_model(score_model_args, device, t_to_sigma=t_to_sigma, no_parallel=True)state_dict = torch.load( f"workdir/paper_score_model/best_ema_inference_epoch_model.pt", map_location=torch.device("cpu"),)model.load_state_dict(state_dict, strict=True)model = model.to(device)model.eval()
confidence_model = get_model( confidence_args, device, t_to_sigma=t_to_sigma, no_parallel=True, confidence_mode=True,)state_dict = torch.load( f"workdir/paper_confidence_model/best_model_epoch75.pt", map_location=torch.device("cpu"),)confidence_model.load_state_dict(state_dict, strict=True)confidence_model = confidence_model.to(device)confidence_model.eval()
def get_pdb(pdb_code="", filepath=""): try: return filepath.name except AttributeError as e: if pdb_code is None or pdb_code == "": return None else: os.system(f"wget -qnc https://files.rcsb.org/view/{pdb_code}.pdb") return f"{pdb_code}.pdb"
def get_ligand(smiles="", filepath=""): if smiles is None or smiles == "": try: return filepath.name except AttributeError as e: return None else: return smiles
def read_mol(molpath): with open(molpath, "r") as fp: lines = fp.readlines() mol = "" for l in lines: mol += l return mol
def molecule(input_pdb, ligand_pdb, original_ligand):
structure = read_mol(input_pdb) mol = read_mol(ligand_pdb)
try: ligand = read_mol(original_ligand.name) _, ext = os.path.splitext(original_ligand.name) lig_str_1 = """let original_ligand = `""" + ligand + """`""" lig_str_2 = f""" viewer.addModel( original_ligand, "{ext[1:]}" ); viewer.getModel(2).setStyle({{stick:{{colorscheme:"greenCarbon"}}}});""" except AttributeError as e: ligand = None lig_str_1 = "" lig_str_2 = ""
x = ( """<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <style> body{ font-family:sans-serif } .mol-container { width: 600px; height: 600px; position: relative; mx-auto:0 } .mol-container select{ background-image:None; } .green{ width:20px; height:20px; background-color:#33ff45; display:inline-block; } .magenta{ width:20px; height:20px; background-color:magenta; display:inline-block; } </style><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="https://3Dmol.csb.pitt.edu/build/3Dmol-min.js"></script> </head> <body> <button id="startanimation">Replay diffusion process</button> <button id="togglesurface">Toggle surface representation</button> <div> <span class="green"></span> Uploaded ligand position <span class="magenta"></span> Predicted ligand position </div> <div id="container" class="mol-container"></div> <script> let ligand = `""" + mol + """` let structure = `""" + structure + """` """ + lig_str_1 + """ let viewer = null; let surface = false; let surf = null; $(document).ready(function () { let element = $("#container"); let config = { backgroundColor: "white" }; viewer = $3Dmol.createViewer(element, config); viewer.addModel( structure, "pdb" ); viewer.setStyle({}, {cartoon: {color: "gray"}}); viewer.zoomTo(); viewer.zoom(0.7); viewer.addModelsAsFrames(ligand, "pdb"); viewer.animate({loop: "forward",reps: 1}); viewer.getModel(1).setStyle({stick:{colorscheme:"magentaCarbon"}}); """ + lig_str_2 + """ viewer.render(); })
$("#startanimation").click(function() { viewer.animate({loop: "forward",reps: 1}); }); $("#togglesurface").click(function() { if (surface != true) { surf = viewer.addSurface($3Dmol.SurfaceType.VDW, { "opacity": 0.9, "color": "white" }, { model: 0 }); surface = true; } else { viewer.removeAllSurfaces() surface = false; } }); </script> </body></html>""" )
return f"""<iframe style="width: 100%; height: 700px" name="result" allow="midi; geolocation; microphone; camera; display-capture; encrypted-media;" sandbox="allow-modals allow-forms allow-scripts allow-same-origin allow-popups allow-top-navigation-by-user-activation allow-downloads" allowfullscreen="" allowpaymentrequest="" frameborder="0" srcdoc='{x}'></iframe>"""
import sys
def esm(protein_path, out_file): print("running esm") esm_embedding_prep(out_file, protein_path) # create args object with defaults os.environ["HOME"] = "esm/model_weights" subprocess.call( f"python esm/scripts/extract.py esm2_t33_650M_UR50D {out_file} data/esm2_output --repr_layers 33 --include per_tok", shell=True, env=os.environ, )
def update(inp, file, ligand_inp, ligand_file, n_it, n_samples, actual_steps, no_final_step_noise): pdb_path = get_pdb(inp, file) ligand_path = get_ligand(ligand_inp, ligand_file)
esm( pdb_path, f"data/{os.path.basename(pdb_path)}_prepared_for_esm.fasta", ) tr_schedule = get_t_schedule(inference_steps=n_it) rot_schedule = tr_schedule tor_schedule = tr_schedule print("common t schedule", tr_schedule) ( failures, skipped, confidences_list, names_list, run_times, min_self_distances_list, ) = ( 0, 0, [], [], [], [], ) N = n_samples # number of samples to generate protein_path_list = [pdb_path] ligand_descriptions = [ligand_path] no_random = False ode = False no_final_step_noise = no_final_step_noise out_dir = "results/" test_dataset = PDBBind( transform=None, root="", protein_path_list=protein_path_list, ligand_descriptions=ligand_descriptions, receptor_radius=score_model_args.receptor_radius, cache_path="data/cache", remove_hs=score_model_args.remove_hs, max_lig_size=None, c_alpha_max_neighbors=score_model_args.c_alpha_max_neighbors, matching=False, keep_original=False, popsize=score_model_args.matching_popsize, maxiter=score_model_args.matching_maxiter, all_atoms=score_model_args.all_atoms, atom_radius=score_model_args.atom_radius, atom_max_neighbors=score_model_args.atom_max_neighbors, esm_embeddings_path="data/esm2_output", require_ligand=True, num_workers=1, keep_local_structures=False, ) test_loader = DataLoader(dataset=test_dataset, batch_size=1, shuffle=False) confidence_test_dataset = PDBBind( transform=None, root="", protein_path_list=protein_path_list, ligand_descriptions=ligand_descriptions, receptor_radius=confidence_args.receptor_radius, cache_path="data/cache", remove_hs=confidence_args.remove_hs, max_lig_size=None, c_alpha_max_neighbors=confidence_args.c_alpha_max_neighbors, matching=False, keep_original=False, popsize=confidence_args.matching_popsize, maxiter=confidence_args.matching_maxiter, all_atoms=confidence_args.all_atoms, atom_radius=confidence_args.atom_radius, atom_max_neighbors=confidence_args.atom_max_neighbors, esm_embeddings_path="data/esm2_output", require_ligand=True, num_workers=1, ) confidence_complex_dict = {d.name: d for d in confidence_test_dataset} for idx, orig_complex_graph in tqdm(enumerate(test_loader)): if ( confidence_model is not None and not ( confidence_args.use_original_model_cache or confidence_args.transfer_weights ) and orig_complex_graph.name[0] not in confidence_complex_dict.keys() ): skipped += 1 print( f"HAPPENING | The confidence dataset did not contain {orig_complex_graph.name[0]}. We are skipping this complex." ) continue try: data_list = [copy.deepcopy(orig_complex_graph) for _ in range(N)] randomize_position( data_list, score_model_args.no_torsion, no_random, score_model_args.tr_sigma_max, ) pdb = None lig = orig_complex_graph.mol[0] visualization_list = [] for graph in data_list: pdb = PDBFile(lig) pdb.add(lig, 0, 0) pdb.add( ( orig_complex_graph["ligand"].pos + orig_complex_graph.original_center ) .detach() .cpu(), 1, 0, ) pdb.add( (graph["ligand"].pos + graph.original_center).detach().cpu(), part=1, order=1, ) visualization_list.append(pdb)
start_time = time.time() if confidence_model is not None and not ( confidence_args.use_original_model_cache or confidence_args.transfer_weights ): confidence_data_list = [ copy.deepcopy(confidence_complex_dict[orig_complex_graph.name[0]]) for _ in range(N) ] else: confidence_data_list = None
data_list, confidence = sampling( data_list=data_list, model=model, inference_steps=actual_steps, tr_schedule=tr_schedule, rot_schedule=rot_schedule, tor_schedule=tor_schedule, device=device, t_to_sigma=t_to_sigma, model_args=score_model_args, no_random=no_random, ode=ode, visualization_list=visualization_list, confidence_model=confidence_model, confidence_data_list=confidence_data_list, confidence_model_args=confidence_args, batch_size=1, no_final_step_noise=no_final_step_noise, ) ligand_pos = np.asarray( [ complex_graph["ligand"].pos.cpu().numpy() + orig_complex_graph.original_center.cpu().numpy() for complex_graph in data_list ] ) run_times.append(time.time() - start_time)
if confidence is not None and isinstance( confidence_args.rmsd_classification_cutoff, list ): confidence = confidence[:, 0] if confidence is not None: confidence = confidence.cpu().numpy() re_order = np.argsort(confidence)[::-1] confidence = confidence[re_order] confidences_list.append(confidence) ligand_pos = ligand_pos[re_order] write_dir = ( f'{out_dir}/index{idx}_{data_list[0]["name"][0].replace("/","-")}' ) os.makedirs(write_dir, exist_ok=True) confidences = [] for rank, pos in enumerate(ligand_pos): mol_pred = copy.deepcopy(lig) if score_model_args.remove_hs: mol_pred = RemoveHs(mol_pred) if rank == 0: write_mol_with_coords( mol_pred, pos, os.path.join(write_dir, f"rank{rank+1}.sdf") ) confidences.append(confidence[rank]) write_mol_with_coords( mol_pred, pos, os.path.join( write_dir, f"rank{rank+1}_confidence{confidence[rank]:.2f}.sdf" ), ) self_distances = np.linalg.norm( ligand_pos[:, :, None, :] - ligand_pos[:, None, :, :], axis=-1 ) self_distances = np.where( np.eye(self_distances.shape[2]), np.inf, self_distances ) min_self_distances_list.append(np.min(self_distances, axis=(1, 2)))
filenames = [] if confidence is not None: for rank, batch_idx in enumerate(re_order): visualization_list[batch_idx].write( os.path.join(write_dir, f"rank{rank+1}_reverseprocess.pdb") ) filenames.append( os.path.join(write_dir, f"rank{rank+1}_reverseprocess.pdb") ) else: for rank, batch_idx in enumerate(ligand_pos): visualization_list[batch_idx].write( os.path.join(write_dir, f"rank{rank+1}_reverseprocess.pdb") ) filenames.append( os.path.join(write_dir, f"rank{rank+1}_reverseprocess.pdb") ) names_list.append(orig_complex_graph.name[0]) except Exception as e: print("Failed on", orig_complex_graph["name"], e) failures += 1 return None # zip outputs zippath = shutil.make_archive( os.path.join("results", os.path.basename(pdb_path)), "zip", write_dir ) print("Zipped outputs to", zippath) labels = [ f"rank {i+1}, confidence {confidences[i]:.2f}" for i in range(len(filenames)) ]
torch.cuda.empty_cache() return ( molecule(pdb_path, filenames[0], ligand_file), gr.Dropdown.update(choices=labels, value=labels[0]), filenames, pdb_path, zippath, )
def updateView(out, filenames, pdb, ligand_file): print("updating view") i = out # int(out.replace("rank", "")) print(i) i = int(i.split(",")[0].replace("rank", "")) - 1 return molecule(pdb, filenames[i], ligand_file)
demo = gr.Blocks()
with demo: gr.Markdown("# DiffDock") gr.Markdown( ">**DiffDock: Diffusion Steps, Twists, and Turns for Molecular Docking**, Corso, Gabriele and Stärk, Hannes and Jing, Bowen and Barzilay, Regina and Jaakkola, Tommi, arXiv:2210.01776 [GitHub](https://github.com/gcorso/diffdock)" ) gr.Markdown("") with gr.Box(): with gr.Row(): with gr.Column(): gr.Markdown("## Protein") inp = gr.Textbox( placeholder="PDB Code or upload file below", label="Input structure" ) file = gr.File(file_count="single", label="Input PDB") with gr.Column(): gr.Markdown("## Ligand") ligand_inp = gr.Textbox( placeholder="Provide SMILES input or upload mol2/sdf file below", label="SMILES string", ) ligand_file = gr.File(file_count="single", label="Input Ligand") n_it = gr.Slider(value=20, minimum=10, maximum=40, label="Number of inference steps", step=1 ) actual_steps = gr.Slider(value=18, minimum=10, maximum=40, label="Number of actual inference steps", step=1 ) n_samples = gr.Slider(value=40, minimum=10, maximum=40, label="Number of samples", step=1 ) no_final_step_noise = gr.Checkbox(value=True,label="No final step noise" )
btn = gr.Button("Run predictions")
gr.Markdown("## Output") pdb = gr.Variable() filenames = gr.Variable() out = gr.Dropdown(interactive=True, label="Ranked samples") mol = gr.HTML() output_file = gr.File(file_count="single", label="Output files") gr.Examples( [ [ "6w70", "examples/6w70.pdb", "COc1ccc(cc1)n2c3c(c(n2)C(=O)N)CCN(C3=O)c4ccc(cc4)N5CCCCC5=O", "examples/6w70_ligand.sdf", 20, 10, 18, True ], [ "6moa", "examples/6moa_protein_processed.pdb", "", "examples/6moa_ligand.sdf", 20, 10, 18, True ], [ "", "examples/6o5u_protein_processed.pdb", "", "examples/6o5u_ligand.sdf", 20, 10, 18, True ], [ "", "examples/6o5u_protein_processed.pdb", "[NH3+]C[C@H]1O[C@H](O[C@@H]2[C@@H]([NH3+])C[C@H]([C@@H]([C@H]2O)O[C@H]2O[C@H](CO)[C@H]([C@@H]([C@H]2O)[NH3+])O)[NH3+])[C@@H]([C@H]([C@@H]1O)O)O", "examples/6o5u_ligand.sdf", 20, 10, 18, True ], [ "", "examples/6o5u_protein_processed.pdb", "", "examples/6o5u_ligand.sdf", 20, 10, 18, True ], [ "", "examples/6ahs_protein_processed.pdb", "", "examples/6ahs_ligand.sdf", 20, 10, 18, True ], ], [inp, file, ligand_inp, ligand_file, n_it, n_samples, actual_steps, no_final_step_noise], [mol, out, filenames, pdb, output_file], # fn=update, # cache_examples=True, ) btn.click( fn=update, inputs=[inp, file, ligand_inp, ligand_file, n_it, n_samples, actual_steps, no_final_step_noise], outputs=[mol, out, filenames, pdb, output_file], ) out.change(fn=updateView, inputs=[out, filenames, pdb, ligand_file], outputs=mol)demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219# small script to extract the ligand and save it in a separate file because GNINA will use the ligand position as initial poseimport os
import plotly.express as pximport timefrom argparse import FileType, ArgumentParser
import numpy as npimport pandas as pdimport wandbfrom biopandas.pdb import PandasPdbfrom rdkit import Chem
from tqdm import tqdm
from datasets.pdbbind import read_molfrom datasets.process_mols import read_moleculefrom utils.utils import read_strings_from_txt, get_symmetry_rmsd
parser = ArgumentParser()parser.add_argument('--config', type=FileType(mode='r'), default=None)parser.add_argument('--run_name', type=str, default='gnina_results', help='')parser.add_argument('--data_dir', type=str, default='data/PDBBind_processed', help='')parser.add_argument('--results_path', type=str, default='results/user_inference', help='Path to folder with trained model and hyperparameters')parser.add_argument('--file_suffix', type=str, default='_baseline_ligand.pdb', help='Path to folder with trained model and hyperparameters')parser.add_argument('--project', type=str, default='ligbind_inf', help='')parser.add_argument('--wandb', action='store_true', default=False, help='')parser.add_argument('--file_to_exclude', type=str, default=None, help='')parser.add_argument('--all_dirs_in_results', action='store_true', default=True, help='Evaluate all directories in the results path instead of using directly looking for the names')parser.add_argument('--num_predictions', type=int, default=10, help='')parser.add_argument('--no_id_in_filename', action='store_true', default=False, help='')args = parser.parse_args()
print('Reading paths and names.')names = read_strings_from_txt(f'data/splits/timesplit_test')names_no_rec_overlap = read_strings_from_txt(f'data/splits/timesplit_test_no_rec_overlap')results_path_containments = os.listdir(args.results_path)
if args.wandb: wandb.init( entity='coarse-graining-mit', settings=wandb.Settings(start_method="fork"), project=args.project, name=args.run_name, config=args )
all_times = []successful_names_list = []rmsds_list = []centroid_distances_list = []min_cross_distances_list = []min_self_distances_list = []without_rec_overlap_list = []start_time = time.time()for i, name in enumerate(tqdm(names)): mol = read_mol(args.data_dir, name, remove_hs=True) mol = Chem.RemoveAllHs(mol) orig_ligand_pos = np.array(mol.GetConformer().GetPositions())
if args.all_dirs_in_results: directory_with_name = [directory for directory in results_path_containments if name in directory][0] ligand_pos = [] for i in range(args.num_predictions): file_paths = os.listdir(os.path.join(args.results_path, directory_with_name)) file_path = [path for path in file_paths if f'rank{i+1}' in path][0] if args.file_to_exclude is not None and args.file_to_exclude in file_path: continue mol_pred = read_molecule(os.path.join(args.results_path, directory_with_name, file_path),remove_hs=True, sanitize=True) mol_pred = Chem.RemoveAllHs(mol_pred) ligand_pos.append(mol_pred.GetConformer().GetPositions()) ligand_pos = np.asarray(ligand_pos) else: if not os.path.exists(os.path.join(args.results_path, name, f'{"" if args.no_id_in_filename else name}{args.file_suffix}')): raise Exception('path did not exists:', os.path.join(args.results_path, name, f'{"" if args.no_id_in_filename else name}{args.file_suffix}')) mol_pred = read_molecule(os.path.join(args.results_path, name, f'{"" if args.no_id_in_filename else name}{args.file_suffix}'), remove_hs=True, sanitize=True) if mol_pred == None: print("Skipping ", name, ' because RDKIT could not read it.') continue mol_pred = Chem.RemoveAllHs(mol_pred) ligand_pos = np.asarray([np.array(mol_pred.GetConformer(i).GetPositions()) for i in range(args.num_predictions)]) try: rmsd = get_symmetry_rmsd(mol, orig_ligand_pos, [l for l in ligand_pos], mol_pred) except Exception as e: print("Using non corrected RMSD because of the error:", e) rmsd = np.sqrt(((ligand_pos - orig_ligand_pos) ** 2).sum(axis=2).mean(axis=1))
rmsds_list.append(rmsd) centroid_distances_list.append(np.linalg.norm(ligand_pos.mean(axis=1) - orig_ligand_pos[None,:].mean(axis=1), axis=1))
rec_path = os.path.join(args.data_dir, name, f'{name}_protein_processed.pdb') if not os.path.exists(rec_path): rec_path = os.path.join(args.data_dir, name,f'{name}_protein_obabel_reduce.pdb') rec = PandasPdb().read_pdb(rec_path) rec_df = rec.df['ATOM'] receptor_pos = rec_df[['x_coord', 'y_coord', 'z_coord']].to_numpy().squeeze().astype(np.float32) receptor_pos = np.tile(receptor_pos, (args.num_predictions, 1, 1))
cross_distances = np.linalg.norm(receptor_pos[:, :, None, :] - ligand_pos[:, None, :, :], axis=-1) self_distances = np.linalg.norm(ligand_pos[:, :, None, :] - ligand_pos[:, None, :, :], axis=-1) self_distances = np.where(np.eye(self_distances.shape[2]), np.inf, self_distances) min_cross_distances_list.append(np.min(cross_distances, axis=(1,2))) min_self_distances_list.append(np.min(self_distances, axis=(1, 2))) successful_names_list.append(name) without_rec_overlap_list.append(1 if name in names_no_rec_overlap else 0)performance_metrics = {}for overlap in ['', 'no_overlap_']: if 'no_overlap_' == overlap: without_rec_overlap = np.array(without_rec_overlap_list, dtype=bool) rmsds = np.array(rmsds_list)[without_rec_overlap] centroid_distances = np.array(centroid_distances_list)[without_rec_overlap] min_cross_distances = np.array(min_cross_distances_list)[without_rec_overlap] min_self_distances = np.array(min_self_distances_list)[without_rec_overlap] successful_names = np.array(successful_names_list)[without_rec_overlap] else: rmsds = np.array(rmsds_list) centroid_distances = np.array(centroid_distances_list) min_cross_distances = np.array(min_cross_distances_list) min_self_distances = np.array(min_self_distances_list) successful_names = np.array(successful_names_list)
np.save(os.path.join(args.results_path, f'{overlap}rmsds.npy'), rmsds) np.save(os.path.join(args.results_path, f'{overlap}names.npy'), successful_names) np.save(os.path.join(args.results_path, f'{overlap}min_cross_distances.npy'), np.array(min_cross_distances)) np.save(os.path.join(args.results_path, f'{overlap}min_self_distances.npy'), np.array(min_self_distances))
performance_metrics.update({ f'{overlap}steric_clash_fraction': (100 * (min_cross_distances < 0.4).sum() / len(min_cross_distances) / args.num_predictions).__round__(2), f'{overlap}self_intersect_fraction': (100 * (min_self_distances < 0.4).sum() / len(min_self_distances) / args.num_predictions).__round__(2), f'{overlap}mean_rmsd': rmsds[:,0].mean(), f'{overlap}rmsds_below_2': (100 * (rmsds[:,0] < 2).sum() / len(rmsds[:,0])), f'{overlap}rmsds_below_5': (100 * (rmsds[:,0] < 5).sum() / len(rmsds[:,0])), f'{overlap}rmsds_percentile_25': np.percentile(rmsds[:,0], 25).round(2), f'{overlap}rmsds_percentile_50': np.percentile(rmsds[:,0], 50).round(2), f'{overlap}rmsds_percentile_75': np.percentile(rmsds[:,0], 75).round(2),
f'{overlap}mean_centroid': centroid_distances[:,0].mean().__round__(2), f'{overlap}centroid_below_2': (100 * (centroid_distances[:,0] < 2).sum() / len(centroid_distances[:,0])).__round__(2), f'{overlap}centroid_below_5': (100 * (centroid_distances[:,0] < 5).sum() / len(centroid_distances[:,0])).__round__(2), f'{overlap}centroid_percentile_25': np.percentile(centroid_distances[:,0], 25).round(2), f'{overlap}centroid_percentile_50': np.percentile(centroid_distances[:,0], 50).round(2), f'{overlap}centroid_percentile_75': np.percentile(centroid_distances[:,0], 75).round(2), })
top5_rmsds = np.min(rmsds[:, :5], axis=1) top5_centroid_distances = centroid_distances[np.arange(rmsds.shape[0])[:,None],np.argsort(rmsds[:, :5], axis=1)][:,0] top5_min_cross_distances = min_cross_distances[np.arange(rmsds.shape[0])[:,None],np.argsort(rmsds[:, :5], axis=1)][:,0] top5_min_self_distances = min_self_distances[np.arange(rmsds.shape[0])[:,None],np.argsort(rmsds[:, :5], axis=1)][:,0] performance_metrics.update({ f'{overlap}top5_steric_clash_fraction': (100 * (top5_min_cross_distances < 0.4).sum() / len(top5_min_cross_distances)).__round__(2), f'{overlap}top5_self_intersect_fraction': (100 * (top5_min_self_distances < 0.4).sum() / len(top5_min_self_distances)).__round__(2), f'{overlap}top5_rmsds_below_2': (100 * (top5_rmsds < 2).sum() / len(top5_rmsds)).__round__(2), f'{overlap}top5_rmsds_below_5': (100 * (top5_rmsds < 5).sum() / len(top5_rmsds)).__round__(2), f'{overlap}top5_rmsds_percentile_25': np.percentile(top5_rmsds, 25).round(2), f'{overlap}top5_rmsds_percentile_50': np.percentile(top5_rmsds, 50).round(2), f'{overlap}top5_rmsds_percentile_75': np.percentile(top5_rmsds, 75).round(2),
f'{overlap}top5_centroid_below_2': (100 * (top5_centroid_distances < 2).sum() / len(top5_centroid_distances)).__round__(2), f'{overlap}top5_centroid_below_5': (100 * (top5_centroid_distances < 5).sum() / len(top5_centroid_distances)).__round__(2), f'{overlap}top5_centroid_percentile_25': np.percentile(top5_centroid_distances, 25).round(2), f'{overlap}top5_centroid_percentile_50': np.percentile(top5_centroid_distances, 50).round(2), f'{overlap}top5_centroid_percentile_75': np.percentile(top5_centroid_distances, 75).round(2), })
top10_rmsds = np.min(rmsds[:, :10], axis=1) top10_centroid_distances = centroid_distances[np.arange(rmsds.shape[0])[:,None],np.argsort(rmsds[:, :10], axis=1)][:,0] top10_min_cross_distances = min_cross_distances[np.arange(rmsds.shape[0])[:,None],np.argsort(rmsds[:, :10], axis=1)][:,0] top10_min_self_distances = min_self_distances[np.arange(rmsds.shape[0])[:,None],np.argsort(rmsds[:, :10], axis=1)][:,0] performance_metrics.update({ f'{overlap}top10_self_intersect_fraction': (100 * (top10_min_self_distances < 0.4).sum() / len(top10_min_self_distances)).__round__(2), f'{overlap}top10_steric_clash_fraction': ( 100 * (top10_min_cross_distances < 0.4).sum() / len(top10_min_cross_distances)).__round__(2), f'{overlap}top10_rmsds_below_2': (100 * (top10_rmsds < 2).sum() / len(top10_rmsds)).__round__(2), f'{overlap}top10_rmsds_below_5': (100 * (top10_rmsds < 5).sum() / len(top10_rmsds)).__round__(2), f'{overlap}top10_rmsds_percentile_25': np.percentile(top10_rmsds, 25).round(2), f'{overlap}top10_rmsds_percentile_50': np.percentile(top10_rmsds, 50).round(2), f'{overlap}top10_rmsds_percentile_75': np.percentile(top10_rmsds, 75).round(2),
f'{overlap}top10_centroid_below_2': (100 * (top10_centroid_distances < 2).sum() / len(top10_centroid_distances)).__round__(2), f'{overlap}top10_centroid_below_5': (100 * (top10_centroid_distances < 5).sum() / len(top10_centroid_distances)).__round__(2), f'{overlap}top10_centroid_percentile_25': np.percentile(top10_centroid_distances, 25).round(2), f'{overlap}top10_centroid_percentile_50': np.percentile(top10_centroid_distances, 50).round(2), f'{overlap}top10_centroid_percentile_75': np.percentile(top10_centroid_distances, 75).round(2), })for k in performance_metrics: print(k, performance_metrics[k])
if args.wandb: wandb.log(performance_metrics) histogram_metrics_list = [('rmsd', rmsds[:,0]), ('centroid_distance', centroid_distances[:,0]), ('mean_rmsd', rmsds[:,0]), ('mean_centroid_distance', centroid_distances[:,0])] histogram_metrics_list.append(('top5_rmsds', top5_rmsds)) histogram_metrics_list.append(('top5_centroid_distances', top5_centroid_distances)) histogram_metrics_list.append(('top10_rmsds', top10_rmsds)) histogram_metrics_list.append(('top10_centroid_distances', top10_centroid_distances))
os.makedirs(f'.plotly_cache/baseline_cache', exist_ok=True) images = [] for metric_name, metric in histogram_metrics_list: d = {args.results_path: metric} df = pd.DataFrame(data=d) fig = px.ecdf(df, width=900, height=600, range_x=[0, 40]) fig.add_vline(x=2, annotation_text='2 A;', annotation_font_size=20, annotation_position="top right", line_dash='dash', line_color='firebrick', annotation_font_color='firebrick') fig.add_vline(x=5, annotation_text='5 A;', annotation_font_size=20, annotation_position="top right", line_dash='dash', line_color='green', annotation_font_color='green') fig.update_xaxes(title=f'{metric_name} in Angstrom', title_font={"size": 20}, tickfont={"size": 20}) fig.update_yaxes(title=f'Fraction of predictions with lower error', title_font={"size": 20}, tickfont={"size": 20}) fig.update_layout(autosize=False, margin={'l': 0, 'r': 0, 't': 0, 'b': 0}, plot_bgcolor='white', paper_bgcolor='white', legend_title_text='Method', legend_title_font_size=17, legend=dict(yanchor="bottom", y=0.1, xanchor="right", x=0.99, font=dict(size=17), ), ) fig.update_xaxes(showgrid=True, gridcolor='lightgrey') fig.update_yaxes(showgrid=True, gridcolor='lightgrey')
fig.write_image(os.path.join(f'.plotly_cache/baseline_cache', f'{metric_name}.png')) wandb.log({metric_name: wandb.Image(os.path.join(f'.plotly_cache/baseline_cache', f'{metric_name}.png'), caption=f"{metric_name}")}) images.append(wandb.Image(os.path.join(f'.plotly_cache/baseline_cache', f'{metric_name}.png'), caption=f"{metric_name}")) wandb.log({'images': images})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175# small script to extract the ligand and save it in a separate file because GNINA will use the ligand position as# initial poseimport osimport shutilimport subprocessimport sys
import timefrom argparse import ArgumentParser, FileTypefrom datetime import datetime
import numpy as npimport pandas as pdfrom biopandas.pdb import PandasPdbfrom rdkit import Chemfrom rdkit.Chem import AllChem, MolToPDBFilefrom scipy.spatial.distance import cdist
from datasets.pdbbind import read_molfrom utils.utils import read_strings_from_txt
parser = ArgumentParser()parser.add_argument('--data_dir', type=str, default='data/PDBBind_processed', help='')parser.add_argument('--file_suffix', type=str, default='_baseline_ligand', help='Path to folder with trained model and hyperparameters')parser.add_argument('--results_path', type=str, default='results/gnina_predictions', help='')parser.add_argument('--complex_names_path', type=str, default='data/splits/timesplit_test', help='')parser.add_argument('--seed_molecules_path', type=str, default=None, help='Use the molecules at seed molecule path as initialization and only search around them')parser.add_argument('--seed_molecule_filename', type=str, default='equibind_corrected.sdf', help='Use the molecules at seed molecule path as initialization and only search around them')parser.add_argument('--smina', action='store_true', default=False, help='')parser.add_argument('--no_gpu', action='store_true', default=False, help='')parser.add_argument('--exhaustiveness', type=int, default=8, help='')parser.add_argument('--num_cpu', type=int, default=16, help='')parser.add_argument('--pocket_mode', action='store_true', default=False, help='')parser.add_argument('--pocket_cutoff', type=int, default=5, help='')parser.add_argument('--num_modes', type=int, default=10, help='')parser.add_argument('--autobox_add', type=int, default=4, help='')parser.add_argument('--use_p2rank_pocket', action='store_true', default=False, help='')parser.add_argument('--skip_p2rank', action='store_true', default=False, help='')parser.add_argument('--prank_path', type=str, default='/Users/hstark/projects/p2rank_2.3/prank', help='')parser.add_argument('--skip_existing', action='store_true', default=False, help='')
args = parser.parse_args()
class Logger(object): def __init__(self, logpath, syspart=sys.stdout): self.terminal = syspart self.log = open(logpath, "a")
def write(self, message): self.terminal.write(message) self.log.write(message) self.log.flush()
def flush(self): # this flush method is needed for python 3 compatibility. # this handles the flush command by doing nothing. # you might want to specify some extra behavior here. pass
def log(*args): print(f'[{datetime.now()}]', *args)
# parametersnames = read_strings_from_txt(args.complex_names_path)
if os.path.exists(args.results_path) and not args.skip_existing: shutil.rmtree(args.results_path)os.makedirs(args.results_path, exist_ok=True)sys.stdout = Logger(logpath=f'{args.results_path}/gnina.log', syspart=sys.stdout)sys.stderr = Logger(logpath=f'{args.results_path}/error.log', syspart=sys.stderr)
p2rank_cache_path = "results/.p2rank_cache"if args.use_p2rank_pocket and not args.skip_p2rank: os.makedirs(p2rank_cache_path, exist_ok=True) pdb_files_cache = os.path.join(p2rank_cache_path,'pdb_files') os.makedirs(pdb_files_cache, exist_ok=True) with open(f"{p2rank_cache_path}/pdb_list_p2rank.txt", "w") as out: for name in names: shutil.copy(os.path.join(args.data_dir, name, f'{name}_protein_processed.pdb'), f'{pdb_files_cache}/{name}_protein_processed.pdb') out.write(os.path.join('pdb_files', f'{name}_protein_processed.pdb\n')) cmd = f"bash {args.prank_path} predict {p2rank_cache_path}/pdb_list_p2rank.txt -o {p2rank_cache_path}/p2rank_output -threads 4" os.system(cmd)
all_times = []start_time = time.time()for i, name in enumerate(names): os.makedirs(os.path.join(args.results_path, name), exist_ok=True) log('\n') log(f'complex {i} of {len(names)}') # call gnina to find binding pose rec_path = os.path.join(args.data_dir, name, f'{name}_protein_processed.pdb') prediction_output_name = os.path.join(args.results_path, name, f'{name}{args.file_suffix}.pdb') log_path = os.path.join(args.results_path, name, f'{name}{args.file_suffix}.log') if args.seed_molecules_path is not None: seed_mol_path = os.path.join(args.seed_molecules_path, name, f'{args.seed_molecule_filename}') if args.skip_existing and os.path.exists(prediction_output_name): continue
if args.pocket_mode: mol = read_mol(args.data_dir, name, remove_hs=False) rec = PandasPdb().read_pdb(rec_path) rec_df = rec.get(s='c-alpha') rec_pos = rec_df[['x_coord', 'y_coord', 'z_coord']].to_numpy().squeeze().astype(np.float32) lig_pos = mol.GetConformer().GetPositions() d = cdist(rec_pos, lig_pos) label = np.any(d < args.pocket_cutoff, axis=1)
if np.any(label): center_pocket = rec_pos[label].mean(axis=0) else: print("No pocket residue below minimum distance ", args.pocket_cutoff, "taking closest at", np.min(d)) center_pocket = rec_pos[np.argmin(np.min(d, axis=1)[0])] radius_pocket = np.max(np.linalg.norm(lig_pos - center_pocket[None, :], axis=1)) diameter_pocket = radius_pocket * 2 center_x = center_pocket[0] size_x = diameter_pocket + 8 center_y = center_pocket[1] size_y = diameter_pocket + 8 center_z = center_pocket[2] size_z = diameter_pocket + 8
mol_rdkit = read_mol(args.data_dir, name, remove_hs=False) single_time = time.time()
mol_rdkit.RemoveAllConformers() ps = AllChem.ETKDGv2() id = AllChem.EmbedMolecule(mol_rdkit, ps) if id == -1: print('rdkit pos could not be generated without using random pos. using random pos now.') ps.useRandomCoords = True AllChem.EmbedMolecule(mol_rdkit, ps) AllChem.MMFFOptimizeMolecule(mol_rdkit, confId=0) rdkit_mol_path = os.path.join(args.data_dir, name, f'{name}_rdkit_ligand.pdb') MolToPDBFile(mol_rdkit, rdkit_mol_path)
fallback_without_p2rank = False if args.use_p2rank_pocket: df = pd.read_csv(f'{p2rank_cache_path}/p2rank_output/{name}_protein_processed.pdb_predictions.csv') rdkit_lig_pos = mol_rdkit.GetConformer().GetPositions() diameter_pocket = np.max(cdist(rdkit_lig_pos, rdkit_lig_pos)) size_x = diameter_pocket + args.autobox_add * 2 size_y = diameter_pocket + args.autobox_add * 2 size_z = diameter_pocket + args.autobox_add * 2 if df.empty: fallback_without_p2rank = True else: center_x = df.iloc[0][' center_x'] center_y = df.iloc[0][' center_y'] center_z = df.iloc[0][' center_z']
log(f'processing {rec_path}') if not args.pocket_mode and not args.use_p2rank_pocket or fallback_without_p2rank: return_code = subprocess.run( f"gnina --receptor {rec_path} --ligand {rdkit_mol_path} --num_modes {args.num_modes} -o {prediction_output_name} {'--no_gpu' if args.no_gpu else ''} --autobox_ligand {rec_path if args.seed_molecules_path is None else seed_mol_path} --autobox_add {args.autobox_add} --log {log_path} --exhaustiveness {args.exhaustiveness} --cpu {args.num_cpu} {'--cnn_scoring none' if args.smina else ''}", shell=True) else: return_code = subprocess.run( f"gnina --receptor {rec_path} --ligand {rdkit_mol_path} --num_modes {args.num_modes} -o {prediction_output_name} {'--no_gpu' if args.no_gpu else ''} --log {log_path} --exhaustiveness {args.exhaustiveness} --cpu {args.num_cpu} {'--cnn_scoring none' if args.smina else ''} --center_x {center_x} --center_y {center_y} --center_z {center_z} --size_x {size_x} --size_y {size_y} --size_z {size_z}", shell=True) log(return_code) all_times.append(time.time() - single_time)
log("single time: --- %s seconds ---" % (time.time() - single_time)) log("time so far: --- %s seconds ---" % (time.time() - start_time)) log('\n')log(all_times)log("--- %s seconds ---" % (time.time() - start_time))12345for i in $(seq 0 15); do python baseline_tankbind_runtime.py --parallel_id $i --parallel_tot 16 --prank_path /data/rsg/nlp/hstark/TankBind/packages/p2rank_2.3/prank --data_dir /data/rsg/nlp/hstark/ligbind/data/PDBBind_processed --split_path /data/rsg/nlp/hstark/ligbind/data/splits/timesplit_test --results_path /data/rsg/nlp/hstark/ligbind/results/tankbind_16_worker_runtime --device cpu --skip_p2rank --num_workers 1 --skip_multiple_pocket_outputs &donewait
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
import copyimport os
import plotly.express as pximport timefrom argparse import FileType, ArgumentParser
import numpy as npimport pandas as pdimport wandbfrom biopandas.pdb import PandasPdbfrom rdkit import Chemfrom rdkit.Chem import RemoveHs
from tqdm import tqdm
from datasets.pdbbind import read_molfrom datasets.process_mols import read_molecule, read_sdf_or_mol2from utils.utils import read_strings_from_txt, get_symmetry_rmsd, remove_all_hs
parser = ArgumentParser()parser.add_argument('--config', type=FileType(mode='r'), default=None)parser.add_argument('--run_name', type=str, default='tankbind', help='')parser.add_argument('--data_dir', type=str, default='data/PDBBind_processed', help='')parser.add_argument('--renumbered_atoms_dir', type=str, default='../TankBind/examples/tankbind_pdb/renumber_atom_index_same_as_smiles', help='')parser.add_argument('--results_path', type=str, default='results/tankbind_top5', help='Path to folder with trained model and hyperparameters')parser.add_argument('--project', type=str, default='ligbind_inf', help='')parser.add_argument('--wandb', action='store_true', default=True, help='')parser.add_argument('--num_predictions', type=int, default=5, help='')args = parser.parse_args()
names = read_strings_from_txt(f'data/splits/timesplit_test')names_no_rec_overlap = read_strings_from_txt(f'data/splits/timesplit_test_no_rec_overlap')
if args.wandb: wandb.init( entity='coarse-graining-mit', settings=wandb.Settings(start_method="fork"), project=args.project, name=args.run_name, config=args )
all_times = []rmsds_list = []unsym_rmsds_list = []centroid_distances_list = []min_cross_distances_list = []min_self_distances_list = []made_prediction_list = []steric_clash_list = []without_rec_overlap_list = []
start_time = time.time()successful_names_list = []for i, name in enumerate(tqdm(names)): mol, _ = read_sdf_or_mol2(f"{args.renumbered_atoms_dir}/{name}.sdf", None) sm = Chem.MolToSmiles(mol) m_order = list(mol.GetPropsAsDict(includePrivate=True, includeComputed=True)['_smilesAtomOutputOrder']) mol = Chem.RenumberAtoms(mol, m_order) mol = Chem.RemoveHs(mol) orig_ligand_pos = np.array(mol.GetConformer().GetPositions())
assert(os.path.exists(os.path.join(args.results_path, name, f'{name}_tankbind_0.sdf'))) ligand_pos = [] for i in range(args.num_predictions): if not os.path.exists(os.path.join(args.results_path, name, f'{name}_tankbind_{i}.sdf')): break mol_pred, _ = read_sdf_or_mol2(os.path.join(args.results_path, name, f'{name}_tankbind_{i}.sdf'),None) sm = Chem.MolToSmiles(mol_pred) m_order = list(mol_pred.GetPropsAsDict(includePrivate=True, includeComputed=True)['_smilesAtomOutputOrder']) mol_pred = Chem.RenumberAtoms(mol_pred, m_order) mol_pred = RemoveHs(mol_pred) ligand_pos.append(np.array(mol_pred.GetConformer().GetPositions())) ligand_pos = np.asarray(ligand_pos)
try: unsym_rmsd = np.sqrt(((ligand_pos - orig_ligand_pos) ** 2).sum(axis=2).mean(axis=1)) rmsd = np.array(get_symmetry_rmsd(mol, orig_ligand_pos, [l for l in ligand_pos], mol_pred)) except Exception as e: print("Using non corrected RMSD because of the error:", e) rmsd = np.sqrt(((ligand_pos - orig_ligand_pos) ** 2).sum(axis=2).mean(axis=1))
num_pockets = len(ligand_pos) unsym_rmsds_list.append(np.lib.pad(unsym_rmsd, (0,10-len(unsym_rmsd)), 'constant', constant_values=(0)) ) rmsds_list.append(np.lib.pad(rmsd, (0,10-len(rmsd)), 'constant', constant_values=(0)) ) centroid_distance = np.linalg.norm(ligand_pos.mean(axis=1) - orig_ligand_pos[None,:].mean(axis=1), axis=1) centroid_distances_list.append(np.lib.pad(centroid_distance, (0,10-len(rmsd)), 'constant', constant_values=(0)) )
rec_path = os.path.join(args.data_dir, name, f'{name}_protein_processed.pdb') if not os.path.exists(rec_path): rec_path = os.path.join(args.data_dir, name,f'{name}_protein_obabel_reduce.pdb') rec = PandasPdb().read_pdb(rec_path) rec_df = rec.df['ATOM'] receptor_pos = rec_df[['x_coord', 'y_coord', 'z_coord']].to_numpy().squeeze().astype(np.float32) receptor_pos = np.tile(receptor_pos, (10, 1, 1))
ligand_pos_padded = np.lib.pad(ligand_pos, ((0,10-len(ligand_pos)), (0,0), (0,0)), 'constant', constant_values=(np.inf)) ligand_pos_padded_zero = np.lib.pad(ligand_pos, ((0, 10 - len(ligand_pos)), (0, 0), (0, 0)), 'constant',constant_values=0) cross_distances = np.linalg.norm(receptor_pos[:, :, None, :] - ligand_pos_padded[:, None, :, :], axis=-1) self_distances = np.linalg.norm(ligand_pos_padded_zero[:, :, None, :] - ligand_pos_padded_zero[:, None, :, :], axis=-1) self_distances = np.where(np.eye(self_distances.shape[2]), np.inf, self_distances) min_self_distances_list.append(np.min(self_distances, axis=(1, 2))) min_cross_distance = np.min(cross_distances, axis=(1, 2)) individual_made_prediction = np.lib.pad(np.ones(num_pockets), (0,10-len(rmsd)), 'constant', constant_values=(0)) made_prediction_list.append(individual_made_prediction) min_cross_distances_list.append(min_cross_distance) successful_names_list.append(name) without_rec_overlap_list.append(1 if name in names_no_rec_overlap else 0)
performance_metrics = {}for overlap in ['', 'no_overlap_']: if 'no_overlap_' == overlap: without_rec_overlap = np.array(without_rec_overlap_list, dtype=bool) unsym_rmsds = np.array(unsym_rmsds_list)[without_rec_overlap] rmsds = np.array(rmsds_list)[without_rec_overlap] centroid_distances = np.array(centroid_distances_list)[without_rec_overlap] min_cross_distances = np.array(min_cross_distances_list)[without_rec_overlap] min_self_distances = np.array(min_self_distances_list)[without_rec_overlap] made_prediction = np.array(made_prediction_list)[without_rec_overlap] successful_names = np.array(successful_names_list)[without_rec_overlap] else: unsym_rmsds = np.array(unsym_rmsds_list) rmsds = np.array(rmsds_list) centroid_distances = np.array(centroid_distances_list) min_cross_distances = np.array(min_cross_distances_list) min_self_distances = np.array(min_self_distances_list) made_prediction = np.array(made_prediction_list) successful_names = np.array(successful_names_list)
inf_rmsds = copy.deepcopy(rmsds) inf_rmsds[~made_prediction.astype(bool)] = np.inf inf_centroid_distances = copy.deepcopy(centroid_distances) inf_centroid_distances[~made_prediction.astype(bool)] = np.inf
np.save(os.path.join(args.results_path, f'{overlap}rmsds.npy'), rmsds) np.save(os.path.join(args.results_path, f'{overlap}names.npy'), np.array(successful_names)) np.save(os.path.join(args.results_path, f'{overlap}centroid_distances.npy'), centroid_distances) np.save(os.path.join(args.results_path, f'{overlap}min_cross_distances.npy'), min_cross_distances) np.save(os.path.join(args.results_path, f'{overlap}min_self_distances.npy'), min_self_distances)
performance_metrics.update({ f'{overlap}self_intersect_fraction': (100 * (min_self_distances[:, 0] < 0.4).sum() / len(min_self_distances[:, 0])), f'{overlap}steric_clash_fraction': (100 * (min_cross_distances[:,0] < 0.4).sum() / len(min_cross_distances[:,0])), f'{overlap}mean_rmsd': rmsds[:,0].mean(), f'{overlap}unsym_rmsds_below_2': (100 * (unsym_rmsds[:,0] < 2).sum() / len(unsym_rmsds[:,0])), f'{overlap}rmsds_below_2': (100 * (rmsds[:,0] < 2).sum() / len(rmsds[:,0])), f'{overlap}rmsds_below_5': (100 * (rmsds[:,0] < 5).sum() / len(rmsds[:,0])), f'{overlap}rmsds_percentile_25': np.percentile(rmsds[:,0], 25).round(2), f'{overlap}rmsds_percentile_50': np.percentile(rmsds[:,0], 50).round(2), f'{overlap}rmsds_percentile_75': np.percentile(rmsds[:,0], 75).round(2),
f'{overlap}mean_centroid': centroid_distances[:,0].mean().__round__(2), f'{overlap}centroid_below_2': (100 * (centroid_distances[:,0] < 2).sum() / len(centroid_distances[:,0])).__round__(2), f'{overlap}centroid_below_5': (100 * (centroid_distances[:,0] < 5).sum() / len(centroid_distances[:,0])).__round__(2), f'{overlap}centroid_percentile_25': np.percentile(centroid_distances[:,0], 25).round(2), f'{overlap}centroid_percentile_50': np.percentile(centroid_distances[:,0], 50).round(2), f'{overlap}centroid_percentile_75': np.percentile(centroid_distances[:,0], 75).round(2), })
top5_rmsds = np.min(inf_rmsds[:, :5], axis=1) top5_centroid_distances = centroid_distances[np.arange(rmsds.shape[0])[:,None],np.argsort(inf_rmsds[:, :5], axis=1)][:,0] top5_min_cross_distances = min_cross_distances[np.arange(rmsds.shape[0])[:,None],np.argsort(inf_rmsds[:, :5], axis=1)][:,0] top5_min_self_distances = min_self_distances[np.arange(rmsds.shape[0])[:,None],np.argsort(inf_rmsds[:, :5], axis=1)][:,0] performance_metrics.update({ f'{overlap}top5_steric_clash_fraction': (100 * (top5_min_cross_distances < 0.4).sum() / len(top5_min_cross_distances)).__round__(2), f'{overlap}top5_self_intersect_fraction': (100 * (top5_min_self_distances < 0.4).sum() / len(top5_min_self_distances)).__round__(2), f'{overlap}top5_rmsds_below_2': (100 * (top5_rmsds < 2).sum() / len(top5_rmsds)).__round__(2), f'{overlap}top5_rmsds_below_5': (100 * (top5_rmsds < 5).sum() / len(top5_rmsds)).__round__(2), f'{overlap}top5_rmsds_percentile_25': np.percentile(top5_rmsds, 25).round(2), f'{overlap}top5_rmsds_percentile_50': np.percentile(top5_rmsds, 50).round(2), f'{overlap}top5_rmsds_percentile_75': np.percentile(top5_rmsds, 75).round(2),
f'{overlap}top5_centroid_below_2': (100 * (top5_centroid_distances < 2).sum() / len(top5_centroid_distances)).__round__(2), f'{overlap}top5_centroid_below_5': (100 * (top5_centroid_distances < 5).sum() / len(top5_centroid_distances)).__round__(2), f'{overlap}top5_centroid_percentile_25': np.percentile(top5_centroid_distances, 25).round(2), f'{overlap}top5_centroid_percentile_50': np.percentile(top5_centroid_distances, 50).round(2), f'{overlap}top5_centroid_percentile_75': np.percentile(top5_centroid_distances, 75).round(2), })
top10_rmsds = np.min(inf_rmsds[:, :10], axis=1) top10_centroid_distances = centroid_distances[np.arange(rmsds.shape[0])[:,None],np.argsort(inf_rmsds[:, :10], axis=1)][:,0] top10_min_cross_distances = min_cross_distances[np.arange(rmsds.shape[0])[:,None],np.argsort(inf_rmsds[:, :10], axis=1)][:,0] top10_min_self_distances = min_self_distances[np.arange(rmsds.shape[0])[:,None],np.argsort(inf_rmsds[:, :10], axis=1)][:,0] performance_metrics.update({ f'{overlap}top10_steric_clash_fraction': (100 * (top10_min_cross_distances < 0.4).sum() / len(top10_min_cross_distances)).__round__(2), f'{overlap}top10_self_intersect_fraction': (100 * (top10_min_self_distances < 0.4).sum() / len(top10_min_self_distances)).__round__(2), f'{overlap}top10_rmsds_below_2': (100 * (top10_rmsds < 2).sum() / len(top10_rmsds)).__round__(2), f'{overlap}top10_rmsds_below_5': (100 * (top10_rmsds < 5).sum() / len(top10_rmsds)).__round__(2), f'{overlap}top10_rmsds_percentile_25': np.percentile(top10_rmsds, 25).round(2), f'{overlap}top10_rmsds_percentile_50': np.percentile(top10_rmsds, 50).round(2), f'{overlap}top10_rmsds_percentile_75': np.percentile(top10_rmsds, 75).round(2),
f'{overlap}top10_centroid_below_2': (100 * (top10_centroid_distances < 2).sum() / len(top10_centroid_distances)).__round__(2), f'{overlap}top10_centroid_below_5': (100 * (top10_centroid_distances < 5).sum() / len(top10_centroid_distances)).__round__(2), f'{overlap}top10_centroid_percentile_25': np.percentile(top10_centroid_distances, 25).round(2), f'{overlap}top10_centroid_percentile_50': np.percentile(top10_centroid_distances, 50).round(2), f'{overlap}top10_centroid_percentile_75': np.percentile(top10_centroid_distances, 75).round(2), })for k in performance_metrics: print(k, performance_metrics[k])
if args.wandb: wandb.log(performance_metrics) histogram_metrics_list = [('rmsd', rmsds[:,0]), ('centroid_distance', centroid_distances[:,0]), ('mean_rmsd', rmsds[:,0]), ('mean_centroid_distance', centroid_distances[:,0])] histogram_metrics_list.append(('top5_rmsds', top5_rmsds)) histogram_metrics_list.append(('top5_centroid_distances', top5_centroid_distances)) histogram_metrics_list.append(('top10_rmsds', top10_rmsds)) histogram_metrics_list.append(('top10_centroid_distances', top10_centroid_distances))
os.makedirs(f'.plotly_cache/baseline_cache', exist_ok=True) images = [] for metric_name, metric in histogram_metrics_list: d = {args.results_path: metric} df = pd.DataFrame(data=d) fig = px.ecdf(df, width=900, height=600, range_x=[0, 40]) fig.add_vline(x=2, annotation_text='2 A;', annotation_font_size=20, annotation_position="top right", line_dash='dash', line_color='firebrick', annotation_font_color='firebrick') fig.add_vline(x=5, annotation_text='5 A;', annotation_font_size=20, annotation_position="top right", line_dash='dash', line_color='green', annotation_font_color='green') fig.update_xaxes(title=f'{metric_name} in Angstrom', title_font={"size": 20}, tickfont={"size": 20}) fig.update_yaxes(title=f'Fraction of predictions with lower error', title_font={"size": 20}, tickfont={"size": 20}) fig.update_layout(autosize=False, margin={'l': 0, 'r': 0, 't': 0, 'b': 0}, plot_bgcolor='white', paper_bgcolor='white', legend_title_text='Method', legend_title_font_size=17, legend=dict(yanchor="bottom", y=0.1, xanchor="right", x=0.99, font=dict(size=17), ), ) fig.update_xaxes(showgrid=True, gridcolor='lightgrey') fig.update_yaxes(showgrid=True, gridcolor='lightgrey')
fig.write_image(os.path.join(f'.plotly_cache/baseline_cache', f'{metric_name}.png')) wandb.log({metric_name: wandb.Image(os.path.join(f'.plotly_cache/baseline_cache', f'{metric_name}.png'), caption=f"{metric_name}")}) images.append(wandb.Image(os.path.join(f'.plotly_cache/baseline_cache', f'{metric_name}.png'), caption=f"{metric_name}")) wandb.log({'images': images})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342# This file needs to be ran in the TANKBind repository together with baseline_run_tankbind_parallel.sh
import sysimport timefrom multiprocessing import Pool
import copyimport warningsfrom argparse import ArgumentParser
from rdkit.Chem import AllChem, RemoveHs
from feature_utils import save_cleaned_protein, read_molfrom generation_utils import get_LAS_distance_constraint_mask, get_info_pred_distance, write_with_new_coordsimport loggingfrom torch_geometric.loader import DataLoaderfrom tqdm import tqdm # pip install tqdm if fails.from model import get_model# from utils import *import torch
from data import TankBind_prediction
import osimport numpy as npimport pandas as pdimport rdkit.Chem as Chemfrom feature_utils import generate_sdf_from_smiles_using_rdkitfrom feature_utils import get_protein_featurefrom Bio.PDB import PDBParserfrom feature_utils import extract_torchdrug_feature_from_mol
def read_strings_from_txt(path): # every line will be one element of the returned list with open(path) as file: lines = file.readlines() return [line.rstrip() for line in lines]
def read_molecule(molecule_file, sanitize=False, calc_charges=False, remove_hs=False): if molecule_file.endswith('.mol2'): mol = Chem.MolFromMol2File(molecule_file, sanitize=False, removeHs=False) elif molecule_file.endswith('.sdf'): supplier = Chem.SDMolSupplier(molecule_file, sanitize=False, removeHs=False) mol = supplier[0] elif molecule_file.endswith('.pdbqt'): with open(molecule_file) as file: pdbqt_data = file.readlines() pdb_block = '' for line in pdbqt_data: pdb_block += '{}\n'.format(line[:66]) mol = Chem.MolFromPDBBlock(pdb_block, sanitize=False, removeHs=False) elif molecule_file.endswith('.pdb'): mol = Chem.MolFromPDBFile(molecule_file, sanitize=False, removeHs=False) else: return ValueError('Expect the format of the molecule_file to be ' 'one of .mol2, .sdf, .pdbqt and .pdb, got {}'.format(molecule_file)) try: if sanitize or calc_charges: Chem.SanitizeMol(mol)
if calc_charges: # Compute Gasteiger charges on the molecule. try: AllChem.ComputeGasteigerCharges(mol) except: warnings.warn('Unable to compute charges for the molecule.')
if remove_hs: mol = Chem.RemoveHs(mol, sanitize=sanitize) except: return None
return mol
def parallel_save_prediction(arguments): dataset, y_pred_list, chosen,rdkit_mol_path, result_folder, name = arguments for idx, line in chosen.iterrows(): pocket_name = line['pocket_name'] compound_name = line['compound_name'] ligandName = compound_name.split("_")[1] dataset_index = line['dataset_index'] coords = dataset[dataset_index].coords.to('cpu') protein_nodes_xyz = dataset[dataset_index].node_xyz.to('cpu') n_compound = coords.shape[0] n_protein = protein_nodes_xyz.shape[0] y_pred = y_pred_list[dataset_index].reshape(n_protein, n_compound).to('cpu') compound_pair_dis_constraint = torch.cdist(coords, coords) mol = Chem.MolFromMolFile(rdkit_mol_path) LAS_distance_constraint_mask = get_LAS_distance_constraint_mask(mol).bool() pred_dist_info = get_info_pred_distance(coords, y_pred, protein_nodes_xyz, compound_pair_dis_constraint, LAS_distance_constraint_mask=LAS_distance_constraint_mask, n_repeat=1, show_progress=False)
toFile = f'{result_folder}/{name}_tankbind_chosen.sdf' new_coords = pred_dist_info.sort_values("loss")['coords'].iloc[0].astype(np.double) write_with_new_coords(mol, new_coords, toFile)
if __name__ == '__main__': tankbind_src_folder = "../tankbind" sys.path.insert(0, tankbind_src_folder) torch.set_num_threads(16) parser = ArgumentParser() parser.add_argument('--data_dir', type=str, default='/Users/hstark/projects/ligbind/data/PDBBind_processed', help='') parser.add_argument('--split_path', type=str, default='/Users/hstark/projects/ligbind/data/splits/timesplit_test', help='') parser.add_argument('--prank_path', type=str, default='/Users/hstark/projects/p2rank_2.3/prank', help='') parser.add_argument('--results_path', type=str, default='results/tankbind_results', help='') parser.add_argument('--skip_existing', action='store_true', default=False, help='') parser.add_argument('--skip_p2rank', action='store_true', default=False, help='') parser.add_argument('--skip_multiple_pocket_outputs', action='store_true', default=False, help='') parser.add_argument('--device', type=str, default='cpu', help='') parser.add_argument('--num_workers', type=int, default=1, help='') parser.add_argument('--parallel_id', type=int, default=0, help='') parser.add_argument('--parallel_tot', type=int, default=1, help='') args = parser.parse_args()
device = args.device cache_path = "tankbind_cache" os.makedirs(cache_path, exist_ok=True) os.makedirs(args.results_path, exist_ok=True)
logging.basicConfig(level=logging.INFO) model = get_model(0, logging, device) # re-dock model # modelFile = "../saved_models/re_dock.pt" # self-dock model modelFile = f"{tankbind_src_folder}/../saved_models/self_dock.pt"
model.load_state_dict(torch.load(modelFile, map_location=device)) _ = model.eval() batch_size = 5 names = read_strings_from_txt(args.split_path) if args.parallel_tot > 1: size = len(names) // args.parallel_tot + 1 names = names[args.parallel_id*size:(args.parallel_id+1)*size] rmsds = []
forward_pass_time = [] times_preprocess = [] times_inference = [] top_10_generation_time = [] top_1_generation_time = [] start_time = time.time() if not args.skip_p2rank: for name in names: if args.skip_existing and os.path.exists(f'{args.results_path}/{name}/{name}_tankbind_1.sdf'): continue print("Now processing: ", name) protein_path = f'{args.data_dir}/{name}/{name}_protein_processed.pdb' cleaned_protein_path = f"{cache_path}/{name}_protein_tankbind_cleaned.pdb" # if you change this you also need to change below parser = PDBParser(QUIET=True) s = parser.get_structure(name, protein_path) c = s[0] clean_res_list, ligand_list = save_cleaned_protein(c, cleaned_protein_path)
with open(f"{cache_path}/pdb_list_p2rank.txt", "w") as out: for name in names: out.write(f"{name}_protein_tankbind_cleaned.pdb\n") cmd = f"bash {args.prank_path} predict {cache_path}/pdb_list_p2rank.txt -o {cache_path}/p2rank -threads 4" os.system(cmd) times_preprocess.append(time.time() - start_time) p2_rank_time = time.time() - start_time
list_to_parallelize = [] for name in tqdm(names): single_preprocess_time = time.time() if args.skip_existing and os.path.exists(f'{args.results_path}/{name}/{name}_tankbind_1.sdf'): continue print("Now processing: ", name) protein_path = f'{args.data_dir}/{name}/{name}_protein_processed.pdb' ligand_path = f"{args.data_dir}/{name}/{name}_ligand.sdf" cleaned_protein_path = f"{cache_path}/{name}_protein_tankbind_cleaned.pdb" # if you change this you also need to change below rdkit_mol_path = f"{cache_path}/{name}_rdkit_ligand.sdf"
parser = PDBParser(QUIET=True) s = parser.get_structure(name, protein_path) c = s[0] clean_res_list, ligand_list = save_cleaned_protein(c, cleaned_protein_path) lig, _ = read_mol(f"{args.data_dir}/{name}/{name}_ligand.sdf", f"{args.data_dir}/{name}/{name}_ligand.mol2")
lig = RemoveHs(lig) smiles = Chem.MolToSmiles(lig) generate_sdf_from_smiles_using_rdkit(smiles, rdkit_mol_path, shift_dis=0)
parser = PDBParser(QUIET=True) s = parser.get_structure("x", cleaned_protein_path) res_list = list(s.get_residues())
protein_dict = {} protein_dict[name] = get_protein_feature(res_list) compound_dict = {}
mol = Chem.MolFromMolFile(rdkit_mol_path) compound_dict[name + f"_{name}" + "_rdkit"] = extract_torchdrug_feature_from_mol(mol, has_LAS_mask=True)
info = [] for compound_name in list(compound_dict.keys()): # use protein center as the block center. com = ",".join([str(a.round(3)) for a in protein_dict[name][0].mean(axis=0).numpy()]) info.append([name, compound_name, "protein_center", com])
p2rankFile = f"{cache_path}/p2rank/{name}_protein_tankbind_cleaned.pdb_predictions.csv" pocket = pd.read_csv(p2rankFile) pocket.columns = pocket.columns.str.strip() pocket_coms = pocket[['center_x', 'center_y', 'center_z']].values for ith_pocket, com in enumerate(pocket_coms): com = ",".join([str(a.round(3)) for a in com]) info.append([name, compound_name, f"pocket_{ith_pocket + 1}", com]) info = pd.DataFrame(info, columns=['protein_name', 'compound_name', 'pocket_name', 'pocket_com'])
dataset_path = f"{cache_path}/{name}_dataset/" os.system(f"rm -r {dataset_path}") os.system(f"mkdir -p {dataset_path}") dataset = TankBind_prediction(dataset_path, data=info, protein_dict=protein_dict, compound_dict=compound_dict)
# dataset = TankBind_prediction(dataset_path) times_preprocess.append(time.time() - single_preprocess_time) single_forward_pass_time = time.time() data_loader = DataLoader(dataset, batch_size=batch_size, follow_batch=['x', 'y', 'compound_pair'], shuffle=False, num_workers=0) affinity_pred_list = [] y_pred_list = [] for data in tqdm(data_loader): data = data.to(device) y_pred, affinity_pred = model(data) affinity_pred_list.append(affinity_pred.detach().cpu()) for i in range(data.y_batch.max() + 1): y_pred_list.append((y_pred[data['y_batch'] == i]).detach().cpu())
affinity_pred_list = torch.cat(affinity_pred_list) forward_pass_time.append(time.time() - single_forward_pass_time) output_info = copy.deepcopy(dataset.data) output_info['affinity'] = affinity_pred_list output_info['dataset_index'] = range(len(output_info)) output_info_sorted = output_info.sort_values('affinity', ascending=False)
result_folder = f'{args.results_path}/{name}' os.makedirs(result_folder, exist_ok=True) output_info_sorted.to_csv(f"{result_folder}/output_info_sorted_by_affinity.csv")
if not args.skip_multiple_pocket_outputs: for idx, (dataframe_idx, line) in enumerate(copy.deepcopy(output_info_sorted).iterrows()): single_top10_generation_time = time.time() pocket_name = line['pocket_name'] compound_name = line['compound_name'] ligandName = compound_name.split("_")[1] coords = dataset[dataframe_idx].coords.to('cpu') protein_nodes_xyz = dataset[dataframe_idx].node_xyz.to('cpu') n_compound = coords.shape[0] n_protein = protein_nodes_xyz.shape[0] y_pred = y_pred_list[dataframe_idx].reshape(n_protein, n_compound).to('cpu') y = dataset[dataframe_idx].dis_map.reshape(n_protein, n_compound).to('cpu') compound_pair_dis_constraint = torch.cdist(coords, coords) mol = Chem.MolFromMolFile(rdkit_mol_path) LAS_distance_constraint_mask = get_LAS_distance_constraint_mask(mol).bool() pred_dist_info = get_info_pred_distance(coords, y_pred, protein_nodes_xyz, compound_pair_dis_constraint, LAS_distance_constraint_mask=LAS_distance_constraint_mask, n_repeat=1, show_progress=False)
toFile = f'{result_folder}/{name}_tankbind_{idx}.sdf' new_coords = pred_dist_info.sort_values("loss")['coords'].iloc[0].astype(np.double) write_with_new_coords(mol, new_coords, toFile) if idx < 10: top_10_generation_time.append(time.time() - single_top10_generation_time) if idx == 0: top_1_generation_time.append(time.time() - single_top10_generation_time)
output_info_chosen = copy.deepcopy(dataset.data) output_info_chosen['affinity'] = affinity_pred_list output_info_chosen['dataset_index'] = range(len(output_info_chosen)) chosen = output_info_chosen.loc[ output_info_chosen.groupby(['protein_name', 'compound_name'], sort=False)['affinity'].agg( 'idxmax')].reset_index()
list_to_parallelize.append((dataset, y_pred_list, chosen, rdkit_mol_path, result_folder, name))
chosen_generation_start_time = time.time() if args.num_workers > 1: p = Pool(args.num_workers, maxtasksperchild=1) p.__enter__() with tqdm(total=len(list_to_parallelize), desc=f'running optimization {i}/{len(list_to_parallelize)}') as pbar: map_fn = p.imap_unordered if args.num_workers > 1 else map for t in map_fn(parallel_save_prediction, list_to_parallelize): pbar.update() if args.num_workers > 1: p.__exit__(None, None, None) chosen_generation_time = time.time() - chosen_generation_start_time """ lig, _ = read_mol(f"{args.data_dir}/{name}/{name}_ligand.sdf", f"{args.data_dir}/{name}/{name}_ligand.mol2") sm = Chem.MolToSmiles(lig) m_order = list(lig.GetPropsAsDict(includePrivate=True, includeComputed=True)['_smilesAtomOutputOrder']) lig = Chem.RenumberAtoms(lig, m_order) lig = Chem.RemoveAllHs(lig) lig = RemoveHs(lig) true_ligand_pos = np.array(lig.GetConformer().GetPositions()) toFile = f'{result_folder}/{name}_tankbind_chosen.sdf' mol_pred, _ = read_mol(toFile, None) sm = Chem.MolToSmiles(mol_pred) m_order = list(mol_pred.GetPropsAsDict(includePrivate=True, includeComputed=True)['_smilesAtomOutputOrder']) mol_pred = Chem.RenumberAtoms(mol_pred, m_order) mol_pred = RemoveHs(mol_pred) mol_pred_pos = np.array(mol_pred.GetConformer().GetPositions()) rmsds.append(np.sqrt(((true_ligand_pos - mol_pred_pos) ** 2).sum(axis=1).mean(axis=0))) print(np.sqrt(((true_ligand_pos - mol_pred_pos) ** 2).sum(axis=1).mean(axis=0))) """ forward_pass_time = np.array(forward_pass_time).sum() times_preprocess = np.array(times_preprocess).sum() times_inference = np.array(times_inference).sum() top_10_generation_time = np.array(top_10_generation_time).sum() top_1_generation_time = np.array(top_1_generation_time).sum()
rmsds = np.array(rmsds)
print(f'forward_pass_time: {forward_pass_time}') print(f'times_preprocess: {times_preprocess}') print(f'times_inference: {times_inference}') print(f'top_10_generation_time: {top_10_generation_time}') print(f'top_1_generation_time: {top_1_generation_time}') print(f'chosen_generation_time: {chosen_generation_time}') print(f'rmsds_below_2: {(100 * (rmsds < 2).sum() / len(rmsds))}') print(f'p2rank Time: {p2_rank_time}') print( f'total_time: ' f'{forward_pass_time + times_preprocess + times_inference + top_10_generation_time + top_1_generation_time + p2_rank_time}')
with open(os.path.join(args.results_path, 'tankbind_log.log'), 'w') as file: file.write(f'forward_pass_time: {forward_pass_time}') file.write(f'times_preprocess: {times_preprocess}') file.write(f'times_inference: {times_inference}') file.write(f'top_10_generation_time: {top_10_generation_time}') file.write(f'top_1_generation_time: {top_1_generation_time}') file.write(f'rmsds_below_2: {(100 * (rmsds < 2).sum() / len(rmsds))}') file.write(f'p2rank Time: {p2_rank_time}') file.write(f'total_time: {forward_pass_time + times_preprocess + times_inference + top_10_generation_time + top_1_generation_time + p2_rank_time}')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319import gcimport mathimport os
import shutil
from argparse import Namespace, ArgumentParser, FileTypeimport torch.nn.functional as F
import wandbimport torchfrom sklearn.metrics import roc_auc_scorefrom torch_geometric.loader import DataListLoader, DataLoaderfrom tqdm import tqdm
from confidence.dataset import ConfidenceDatasetfrom utils.training import AverageMeter
torch.multiprocessing.set_sharing_strategy('file_system')
import yamlfrom utils.utils import save_yaml_file, get_optimizer_and_scheduler, get_model
parser = ArgumentParser()parser.add_argument('--config', type=FileType(mode='r'), default=None)parser.add_argument('--original_model_dir', type=str, default='workdir', help='Path to folder with trained model and hyperparameters')parser.add_argument('--restart_dir', type=str, default=None, help='')parser.add_argument('--use_original_model_cache', action='store_true', default=False, help='If this is true, the same dataset as in the original model will be used. Otherwise, the dataset parameters are used.')parser.add_argument('--data_dir', type=str, default='data/PDBBind_processed/', help='Folder containing original structures')parser.add_argument('--ckpt', type=str, default='best_model.pt', help='Checkpoint to use inside the folder')parser.add_argument('--model_save_frequency', type=int, default=0, help='Frequency with which to save the last model. If 0, then only the early stopping criterion best model is saved and overwritten.')parser.add_argument('--best_model_save_frequency', type=int, default=0, help='Frequency with which to save the best model. If 0, then only the early stopping criterion best model is saved and overwritten.')parser.add_argument('--run_name', type=str, default='test_confidence', help='')parser.add_argument('--project', type=str, default='diffdock_confidence', help='')parser.add_argument('--split_train', type=str, default='data/splits/timesplit_no_lig_overlap_train', help='Path of file defining the split')parser.add_argument('--split_val', type=str, default='data/splits/timesplit_no_lig_overlap_val', help='Path of file defining the split')parser.add_argument('--split_test', type=str, default='data/splits/timesplit_test', help='Path of file defining the split')
# Inference parameters for creating the positions and rmsds that the confidence predictor will be trained on.parser.add_argument('--cache_path', type=str, default='data/cacheNew', help='Folder from where to load/restore cached dataset')parser.add_argument('--cache_ids_to_combine', nargs='+', type=str, default=None, help='RMSD value below which a prediction is considered a postitive. This can also be multiple cutoffs.')parser.add_argument('--cache_creation_id', type=int, default=None, help='number of times that inference is run on the full dataset before concatenating it and coming up with the full confidence dataset')parser.add_argument('--wandb', action='store_true', default=False, help='')parser.add_argument('--inference_steps', type=int, default=2, help='Number of denoising steps')parser.add_argument('--samples_per_complex', type=int, default=3, help='')parser.add_argument('--balance', action='store_true', default=False, help='If this is true than we do not force the samples seen during training to be the same amount of negatives as positives')parser.add_argument('--rmsd_prediction', action='store_true', default=False, help='')parser.add_argument('--rmsd_classification_cutoff', nargs='+', type=float, default=2, help='RMSD value below which a prediction is considered a postitive. This can also be multiple cutoffs.')
parser.add_argument('--log_dir', type=str, default='workdir', help='')parser.add_argument('--main_metric', type=str, default='accuracy', help='Metric to track for early stopping. Mostly [loss, accuracy, ROC AUC]')parser.add_argument('--main_metric_goal', type=str, default='max', help='Can be [min, max]')parser.add_argument('--transfer_weights', action='store_true', default=False, help='')parser.add_argument('--batch_size', type=int, default=5, help='')parser.add_argument('--lr', type=float, default=1e-3, help='')parser.add_argument('--w_decay', type=float, default=0.0, help='')parser.add_argument('--scheduler', type=str, default='plateau', help='')parser.add_argument('--scheduler_patience', type=int, default=20, help='')parser.add_argument('--n_epochs', type=int, default=5, help='')
# Datasetparser.add_argument('--limit_complexes', type=int, default=0, help='')parser.add_argument('--all_atoms', action='store_true', default=True, help='')parser.add_argument('--multiplicity', type=int, default=1, help='')parser.add_argument('--chain_cutoff', type=float, default=10, help='')parser.add_argument('--receptor_radius', type=float, default=30, help='')parser.add_argument('--c_alpha_max_neighbors', type=int, default=10, help='')parser.add_argument('--atom_radius', type=float, default=5, help='')parser.add_argument('--atom_max_neighbors', type=int, default=8, help='')parser.add_argument('--matching_popsize', type=int, default=20, help='')parser.add_argument('--matching_maxiter', type=int, default=20, help='')parser.add_argument('--max_lig_size', type=int, default=None, help='Maximum number of heavy atoms')parser.add_argument('--remove_hs', action='store_true', default=False, help='remove Hs')parser.add_argument('--num_conformers', type=int, default=1, help='')parser.add_argument('--esm_embeddings_path', type=str, default=None,help='If this is set then the LM embeddings at that path will be used for the receptor features')parser.add_argument('--no_torsion', action='store_true', default=False, help='')
# Modelparser.add_argument('--num_conv_layers', type=int, default=2, help='Number of interaction layers')parser.add_argument('--max_radius', type=float, default=5.0, help='Radius cutoff for geometric graph')parser.add_argument('--scale_by_sigma', action='store_true', default=True, help='Whether to normalise the score')parser.add_argument('--ns', type=int, default=16, help='Number of hidden features per node of order 0')parser.add_argument('--nv', type=int, default=4, help='Number of hidden features per node of order >0')parser.add_argument('--distance_embed_dim', type=int, default=32, help='')parser.add_argument('--cross_distance_embed_dim', type=int, default=32, help='')parser.add_argument('--no_batch_norm', action='store_true', default=False, help='If set, it removes the batch norm')parser.add_argument('--use_second_order_repr', action='store_true', default=False, help='Whether to use only up to first order representations or also second')parser.add_argument('--cross_max_distance', type=float, default=80, help='')parser.add_argument('--dynamic_max_cross', action='store_true', default=False, help='')parser.add_argument('--dropout', type=float, default=0.0, help='MLP dropout')parser.add_argument('--embedding_type', type=str, default="sinusoidal", help='')parser.add_argument('--sigma_embed_dim', type=int, default=32, help='')parser.add_argument('--embedding_scale', type=int, default=10000, help='')parser.add_argument('--confidence_no_batchnorm', action='store_true', default=False, help='')parser.add_argument('--confidence_dropout', type=float, default=0.0, help='MLP dropout in confidence readout')
args = parser.parse_args()if args.config: config_dict = yaml.load(args.config, Loader=yaml.FullLoader) arg_dict = args.__dict__ for key, value in config_dict.items(): if isinstance(value, list): for v in value: arg_dict[key].append(v) else: arg_dict[key] = value args.config = args.config.nameassert(args.main_metric_goal == 'max' or args.main_metric_goal == 'min')
def train_epoch(model, loader, optimizer, rmsd_prediction): model.train() meter = AverageMeter(['confidence_loss'])
for data in tqdm(loader, total=len(loader)): if device.type == 'cuda' and len(data) % torch.cuda.device_count() == 1 or device.type == 'cpu' and data.num_graphs == 1: print("Skipping batch of size 1 since otherwise batchnorm would not work.") optimizer.zero_grad() try: pred = model(data) if rmsd_prediction: labels = torch.cat([graph.rmsd for graph in data]).to(device) if isinstance(data, list) else data.rmsd confidence_loss = F.mse_loss(pred, labels) else: if isinstance(args.rmsd_classification_cutoff, list): labels = torch.cat([graph.y_binned for graph in data]).to(device) if isinstance(data, list) else data.y_binned confidence_loss = F.cross_entropy(pred, labels) else: labels = torch.cat([graph.y for graph in data]).to(device) if isinstance(data, list) else data.y confidence_loss = F.binary_cross_entropy_with_logits(pred, labels) confidence_loss.backward() optimizer.step() meter.add([confidence_loss.cpu().detach()]) except RuntimeError as e: if 'out of memory' in str(e): print('| WARNING: ran out of memory, skipping batch') for p in model.parameters(): if p.grad is not None: del p.grad # free some memory torch.cuda.empty_cache() gc.collect() continue else: raise e
return meter.summary()
def test_epoch(model, loader, rmsd_prediction): model.eval() meter = AverageMeter(['loss'], unpooled_metrics=True) if rmsd_prediction else AverageMeter(['confidence_loss', 'accuracy', 'ROC AUC'], unpooled_metrics=True) all_labels = [] all_affinities = [] for data in tqdm(loader, total=len(loader)): try: with torch.no_grad(): pred = model(data) affinity_loss = torch.tensor(0.0, dtype=torch.float, device=pred[0].device) accuracy = torch.tensor(0.0, dtype=torch.float, device=pred[0].device) if rmsd_prediction: labels = torch.cat([graph.rmsd for graph in data]).to(device) if isinstance(data, list) else data.rmsd confidence_loss = F.mse_loss(pred, labels) meter.add([confidence_loss.cpu().detach()]) else: if isinstance(args.rmsd_classification_cutoff, list): labels = torch.cat([graph.y_binned for graph in data]).to(device) if isinstance(data,list) else data.y_binned confidence_loss = F.cross_entropy(pred, labels) else: labels = torch.cat([graph.y for graph in data]).to(device) if isinstance(data, list) else data.y confidence_loss = F.binary_cross_entropy_with_logits(pred, labels) accuracy = torch.mean((labels == (pred > 0).float()).float()) try: roc_auc = roc_auc_score(labels.detach().cpu().numpy(), pred.detach().cpu().numpy()) except ValueError as e: if 'Only one class present in y_true. ROC AUC score is not defined in that case.' in str(e): roc_auc = 0 else: raise e meter.add([confidence_loss.cpu().detach(), accuracy.cpu().detach(), torch.tensor(roc_auc)]) all_labels.append(labels)
except RuntimeError as e: if 'out of memory' in str(e): print('| WARNING: ran out of memory, skipping batch') for p in model.parameters(): if p.grad is not None: del p.grad # free some memory torch.cuda.empty_cache() continue else: raise e
all_labels = torch.cat(all_labels)
if rmsd_prediction: baseline_metric = ((all_labels - all_labels.mean()).abs()).mean() else: baseline_metric = all_labels.sum() / len(all_labels) results = meter.summary() results.update({'baseline_metric': baseline_metric}) return meter.summary(), baseline_metric
def train(args, model, optimizer, scheduler, train_loader, val_loader, run_dir): best_val_metric = math.inf if args.main_metric_goal == 'min' else 0 best_epoch = 0
print("Starting training...") for epoch in range(args.n_epochs): logs = {} train_metrics = train_epoch(model, train_loader, optimizer, args.rmsd_prediction) print("Epoch {}: Training loss {:.4f}".format(epoch, train_metrics['confidence_loss']))
val_metrics, baseline_metric = test_epoch(model, val_loader, args.rmsd_prediction) if args.rmsd_prediction: print("Epoch {}: Validation loss {:.4f}".format(epoch, val_metrics['confidence_loss'])) else: print("Epoch {}: Validation loss {:.4f} accuracy {:.4f}".format(epoch, val_metrics['confidence_loss'], val_metrics['accuracy']))
if args.wandb: logs.update({'valinf_' + k: v for k, v in val_metrics.items()}, step=epoch + 1) logs.update({'train_' + k: v for k, v in train_metrics.items()}, step=epoch + 1) logs.update({'mean_rmsd' if args.rmsd_prediction else 'fraction_positives': baseline_metric, 'current_lr': optimizer.param_groups[0]['lr']}) wandb.log(logs, step=epoch + 1)
if scheduler: scheduler.step(val_metrics[args.main_metric])
state_dict = model.module.state_dict() if device.type == 'cuda' else model.state_dict()
if args.main_metric_goal == 'min' and val_metrics[args.main_metric] < best_val_metric or \ args.main_metric_goal == 'max' and val_metrics[args.main_metric] > best_val_metric: best_val_metric = val_metrics[args.main_metric] best_epoch = epoch torch.save(state_dict, os.path.join(run_dir, 'best_model.pt')) if args.model_save_frequency > 0 and (epoch + 1) % args.model_save_frequency == 0: torch.save(state_dict, os.path.join(run_dir, f'model_epoch{epoch+1}.pt')) if args.best_model_save_frequency > 0 and (epoch + 1) % args.best_model_save_frequency == 0: shutil.copyfile(os.path.join(run_dir, 'best_model.pt'), os.path.join(run_dir, f'best_model_epoch{epoch+1}.pt'))
torch.save({ 'epoch': epoch, 'model': state_dict, 'optimizer': optimizer.state_dict(), }, os.path.join(run_dir, 'last_model.pt'))
print("Best Validation accuracy {} on Epoch {}".format(best_val_metric, best_epoch))
def construct_loader_confidence(args, device): common_args = {'cache_path': args.cache_path, 'original_model_dir': args.original_model_dir, 'device': device, 'inference_steps': args.inference_steps, 'samples_per_complex': args.samples_per_complex, 'limit_complexes': args.limit_complexes, 'all_atoms': args.all_atoms, 'balance': args.balance, 'rmsd_classification_cutoff': args.rmsd_classification_cutoff, 'use_original_model_cache': args.use_original_model_cache, 'cache_creation_id': args.cache_creation_id, "cache_ids_to_combine": args.cache_ids_to_combine} loader_class = DataListLoader if torch.cuda.is_available() else DataLoader
exception_flag = False try: train_dataset = ConfidenceDataset(split="train", args=args, **common_args) train_loader = loader_class(dataset=train_dataset, batch_size=args.batch_size, shuffle=True) except Exception as e: if 'The generated ligand positions with cache_id do not exist:' in str(e): print("HAPPENING | Encountered the following exception when loading the confidence train dataset:") print(str(e)) print("HAPPENING | We are still continuing because we want to try to generate the validation dataset if it has not been created yet:") exception_flag = True else: raise e
val_dataset = ConfidenceDataset(split="val", args=args, **common_args) val_loader = loader_class(dataset=val_dataset, batch_size=args.batch_size, shuffle=True)
if exception_flag: raise Exception('We encountered the exception during train dataset loading: ', e) return train_loader, val_loader
if __name__ == '__main__': device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') with open(f'{args.original_model_dir}/model_parameters.yml') as f: score_model_args = Namespace(**yaml.full_load(f))
# construct loader train_loader, val_loader = construct_loader_confidence(args, device) model = get_model(score_model_args if args.transfer_weights else args, device, t_to_sigma=None, confidence_mode=True) optimizer, scheduler = get_optimizer_and_scheduler(args, model, scheduler_mode=args.main_metric_goal)
if args.transfer_weights: print("HAPPENING | Transferring weights from original_model_dir to the new model after using original_model_dir's arguments to construct the new model.") checkpoint = torch.load(os.path.join(args.original_model_dir,args.ckpt), map_location=device) model_state_dict = model.state_dict() transfer_weights_dict = {k: v for k, v in checkpoint.items() if k in list(model_state_dict.keys())} model_state_dict.update(transfer_weights_dict) # update the layers with the pretrained weights model.load_state_dict(model_state_dict)
elif args.restart_dir: dict = torch.load(f'{args.restart_dir}/last_model.pt', map_location=torch.device('cpu')) model.module.load_state_dict(dict['model'], strict=True) optimizer.load_state_dict(dict['optimizer']) print("Restarting from epoch", dict['epoch'])
numel = sum([p.numel() for p in model.parameters()]) print('Model with', numel, 'parameters')
if args.wandb: wandb.init( entity='entity', settings=wandb.Settings(start_method="fork"), project=args.project, name=args.run_name, config=args ) wandb.log({'numel': numel})
# record parameters run_dir = os.path.join(args.log_dir, args.run_name) yaml_file_name = os.path.join(run_dir, 'model_parameters.yml') save_yaml_file(yaml_file_name, args.__dict__) args.device = device
train(args, model, optimizer, scheduler, train_loader, val_loader, run_dir)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272import itertoolsimport mathimport osimport pickleimport randomfrom argparse import Namespacefrom functools import partialimport copy
import numpy as npimport pandas as pdimport torchimport yamlfrom torch_geometric.data import Dataset, Datafrom torch_geometric.loader import DataLoaderfrom tqdm import tqdm
from datasets.pdbbind import PDBBindfrom utils.diffusion_utils import get_t_schedulefrom utils.sampling import randomize_position, samplingfrom utils.utils import get_modelfrom utils.diffusion_utils import t_to_sigma as t_to_sigma_compl
class ListDataset(Dataset): def __init__(self, list): super().__init__() self.data_list = list
def len(self) -> int: return len(self.data_list)
def get(self, idx: int) -> Data: return self.data_list[idx]
def get_cache_path(args, split): cache_path = args.cache_path if not args.no_torsion: cache_path += '_torsion' if args.all_atoms: cache_path += '_allatoms' split_path = args.split_train if split == 'train' else args.split_val cache_path = os.path.join(cache_path, f'limit{args.limit_complexes}_INDEX{os.path.splitext(os.path.basename(split_path))[0]}_maxLigSize{args.max_lig_size}_H{int(not args.remove_hs)}_recRad{args.receptor_radius}_recMax{args.c_alpha_max_neighbors}' + ('' if not args.all_atoms else f'_atomRad{args.atom_radius}_atomMax{args.atom_max_neighbors}') + ('' if args.no_torsion or args.num_conformers == 1 else f'_confs{args.num_conformers}') + ('' if args.esm_embeddings_path is None else f'_esmEmbeddings')) return cache_path
def get_args_and_cache_path(original_model_dir, split): with open(f'{original_model_dir}/model_parameters.yml') as f: model_args = Namespace(**yaml.full_load(f)) return model_args, get_cache_path(model_args,split)
class ConfidenceDataset(Dataset): def __init__(self, cache_path, original_model_dir, split, device, limit_complexes, inference_steps, samples_per_complex, all_atoms, args, balance=False, use_original_model_cache=True, rmsd_classification_cutoff=2, cache_ids_to_combine= None, cache_creation_id=None):
super(ConfidenceDataset, self).__init__()
self.device = device self.inference_steps = inference_steps self.limit_complexes = limit_complexes self.all_atoms = all_atoms self.original_model_dir = original_model_dir self.balance = balance self.use_original_model_cache = use_original_model_cache self.rmsd_classification_cutoff = rmsd_classification_cutoff self.cache_ids_to_combine = cache_ids_to_combine self.cache_creation_id = cache_creation_id self.samples_per_complex = samples_per_complex
self.original_model_args, original_model_cache = get_args_and_cache_path(original_model_dir, split) self.complex_graphs_cache = original_model_cache if self.use_original_model_cache else get_cache_path(args, split) print('Using the cached complex graphs of the original model args' if self.use_original_model_cache else 'Not using the cached complex graphs of the original model args. Instead the complex graphs are used that are at the location given by the dataset parameters given to confidence_train.py') print(self.complex_graphs_cache) if not os.path.exists(os.path.join(self.complex_graphs_cache, "heterographs.pkl")): print(f'HAPPENING | Complex graphs path does not exist yet: {os.path.join(self.complex_graphs_cache, "heterographs.pkl")}. For that reason, we are now creating the dataset.') PDBBind(transform=None, root=args.data_dir, limit_complexes=args.limit_complexes, receptor_radius=args.receptor_radius, cache_path=args.cache_path, split_path=args.split_val if split == 'val' else args.split_train, remove_hs=args.remove_hs, max_lig_size=None, c_alpha_max_neighbors=args.c_alpha_max_neighbors, matching=not args.no_torsion, keep_original=True, popsize=args.matching_popsize, maxiter=args.matching_maxiter, all_atoms=args.all_atoms, atom_radius=args.atom_radius, atom_max_neighbors=args.atom_max_neighbors, esm_embeddings_path=args.esm_embeddings_path, require_ligand=True)
print(f'HAPPENING | Loading complex graphs from: {os.path.join(self.complex_graphs_cache, "heterographs.pkl")}') with open(os.path.join(self.complex_graphs_cache, "heterographs.pkl"), 'rb') as f: complex_graphs = pickle.load(f) self.complex_graph_dict = {d.name: d for d in complex_graphs}
self.full_cache_path = os.path.join(cache_path, f'model_{os.path.splitext(os.path.basename(original_model_dir))[0]}' f'_split_{split}_limit_{limit_complexes}')
if (not os.path.exists(os.path.join(self.full_cache_path, "ligand_positions.pkl")) and self.cache_creation_id is None) or \ (not os.path.exists(os.path.join(self.full_cache_path, f"ligand_positions_id{self.cache_creation_id}.pkl")) and self.cache_creation_id is not None): os.makedirs(self.full_cache_path, exist_ok=True) self.preprocessing(original_model_cache)
if self.cache_ids_to_combine is None: print(f'HAPPENING | Loading positions and rmsds from: {os.path.join(self.full_cache_path, "ligand_positions.pkl")}') with open(os.path.join(self.full_cache_path, "ligand_positions.pkl"), 'rb') as f: self.full_ligand_positions, self.rmsds = pickle.load(f) if os.path.exists(os.path.join(self.full_cache_path, "complex_names_in_same_order.pkl")): with open(os.path.join(self.full_cache_path, "complex_names_in_same_order.pkl"), 'rb') as f: generated_rmsd_complex_names = pickle.load(f) else: print('HAPPENING | The path, ', os.path.join(self.full_cache_path, "complex_names_in_same_order.pkl"), ' does not exist. \n => We assume that means that we are using a ligand_positions.pkl where the ' 'code was not saving the complex names for them yet. We now instead use the complex names of ' 'the dataset that the original model used to create the ligand positions and RMSDs.') with open(os.path.join(original_model_cache, "heterographs.pkl"), 'rb') as f: original_model_complex_graphs = pickle.load(f) generated_rmsd_complex_names = [d.name for d in original_model_complex_graphs] assert (len(self.rmsds) == len(generated_rmsd_complex_names)) else: all_rmsds_unsorted, all_full_ligand_positions_unsorted, all_names_unsorted = [], [], [] for idx, cache_id in enumerate(self.cache_ids_to_combine): print(f'HAPPENING | Loading positions and rmsds from cache_id from the path: {os.path.join(self.full_cache_path, "ligand_positions_"+ str(cache_id)+ ".pkl")}') if not os.path.exists(os.path.join(self.full_cache_path, f"ligand_positions_id{cache_id}.pkl")): raise Exception(f'The generated ligand positions with cache_id do not exist: {cache_id}') # be careful with changing this error message since it is sometimes cought in a try catch with open(os.path.join(self.full_cache_path, f"ligand_positions_id{cache_id}.pkl"), 'rb') as f: full_ligand_positions, rmsds = pickle.load(f) with open(os.path.join(self.full_cache_path, f"complex_names_in_same_order_id{cache_id}.pkl"), 'rb') as f: names_unsorted = pickle.load(f) all_names_unsorted.append(names_unsorted) all_rmsds_unsorted.append(rmsds) all_full_ligand_positions_unsorted.append(full_ligand_positions) names_order = list(set(sum(all_names_unsorted, []))) all_rmsds, all_full_ligand_positions, all_names = [], [], [] for idx, (rmsds_unsorted, full_ligand_positions_unsorted, names_unsorted) in enumerate(zip(all_rmsds_unsorted,all_full_ligand_positions_unsorted, all_names_unsorted)): name_to_pos_dict = {name: (rmsd, pos) for name, rmsd, pos in zip(names_unsorted, full_ligand_positions_unsorted, rmsds_unsorted) } intermediate_rmsds = [name_to_pos_dict[name][1] for name in names_order] all_rmsds.append((intermediate_rmsds)) intermediate_pos = [name_to_pos_dict[name][0] for name in names_order] all_full_ligand_positions.append((intermediate_pos)) self.full_ligand_positions, self.rmsds = [], [] for positions_tuple in list(zip(*all_full_ligand_positions)): self.full_ligand_positions.append(np.concatenate(positions_tuple, axis=0)) for positions_tuple in list(zip(*all_rmsds)): self.rmsds.append(np.concatenate(positions_tuple, axis=0)) generated_rmsd_complex_names = names_order print('Number of complex graphs: ', len(self.complex_graph_dict)) print('Number of RMSDs and positions for the complex graphs: ', len(self.full_ligand_positions))
self.all_samples_per_complex = samples_per_complex * (1 if self.cache_ids_to_combine is None else len(self.cache_ids_to_combine))
self.positions_rmsds_dict = {name: (pos, rmsd) for name, pos, rmsd in zip (generated_rmsd_complex_names, self.full_ligand_positions, self.rmsds)} self.dataset_names = list(set(self.positions_rmsds_dict.keys()) & set(self.complex_graph_dict.keys())) if limit_complexes > 0: self.dataset_names = self.dataset_names[:limit_complexes]
def len(self): return len(self.dataset_names)
def get(self, idx): complex_graph = copy.deepcopy(self.complex_graph_dict[self.dataset_names[idx]]) positions, rmsds = self.positions_rmsds_dict[self.dataset_names[idx]]
if self.balance: if isinstance(self.rmsd_classification_cutoff, list): raise ValueError("a list for --rmsd_classification_cutoff can only be used without --balance") label = random.randint(0, 1) success = rmsds < self.rmsd_classification_cutoff n_success = np.count_nonzero(success) if label == 0 and n_success != self.all_samples_per_complex: # sample negative complex sample = random.randint(0, self.all_samples_per_complex - n_success - 1) lig_pos = positions[~success][sample] complex_graph['ligand'].pos = torch.from_numpy(lig_pos) else: # sample positive complex if n_success > 0: # if no successfull sample returns the matched complex sample = random.randint(0, n_success - 1) lig_pos = positions[success][sample] complex_graph['ligand'].pos = torch.from_numpy(lig_pos) complex_graph.y = torch.tensor(label).float() else: sample = random.randint(0, self.all_samples_per_complex - 1) complex_graph['ligand'].pos = torch.from_numpy(positions[sample]) complex_graph.y = torch.tensor(rmsds[sample] < self.rmsd_classification_cutoff).float().unsqueeze(0) if isinstance(self.rmsd_classification_cutoff, list): complex_graph.y_binned = torch.tensor(np.logical_and(rmsds[sample] < self.rmsd_classification_cutoff + [math.inf],rmsds[sample] >= [0] + self.rmsd_classification_cutoff), dtype=torch.float).unsqueeze(0) complex_graph.y = torch.tensor(rmsds[sample] < self.rmsd_classification_cutoff[0]).unsqueeze(0).float() complex_graph.rmsd = torch.tensor(rmsds[sample]).unsqueeze(0).float()
complex_graph['ligand'].node_t = {'tr': 0 * torch.ones(complex_graph['ligand'].num_nodes), 'rot': 0 * torch.ones(complex_graph['ligand'].num_nodes), 'tor': 0 * torch.ones(complex_graph['ligand'].num_nodes)} complex_graph['receptor'].node_t = {'tr': 0 * torch.ones(complex_graph['receptor'].num_nodes), 'rot': 0 * torch.ones(complex_graph['receptor'].num_nodes), 'tor': 0 * torch.ones(complex_graph['receptor'].num_nodes)} if self.all_atoms: complex_graph['atom'].node_t = {'tr': 0 * torch.ones(complex_graph['atom'].num_nodes), 'rot': 0 * torch.ones(complex_graph['atom'].num_nodes), 'tor': 0 * torch.ones(complex_graph['atom'].num_nodes)} complex_graph.complex_t = {'tr': 0 * torch.ones(1), 'rot': 0 * torch.ones(1), 'tor': 0 * torch.ones(1)} return complex_graph
def preprocessing(self, original_model_cache): t_to_sigma = partial(t_to_sigma_compl, args=self.original_model_args)
model = get_model(self.original_model_args, self.device, t_to_sigma=t_to_sigma, no_parallel=True) state_dict = torch.load(f'{self.original_model_dir}/best_model.pt', map_location=torch.device('cpu')) model.load_state_dict(state_dict, strict=True) model = model.to(self.device) model.eval()
tr_schedule = get_t_schedule(inference_steps=self.inference_steps) rot_schedule = tr_schedule tor_schedule = tr_schedule print('common t schedule', tr_schedule)
print('HAPPENING | loading cached complexes of the original model to create the confidence dataset RMSDs and predicted positions. Doing that from: ', os.path.join(self.complex_graphs_cache, "heterographs.pkl")) with open(os.path.join(original_model_cache, "heterographs.pkl"), 'rb') as f: complex_graphs = pickle.load(f) dataset = ListDataset(complex_graphs) loader = DataLoader(dataset=dataset, batch_size=1, shuffle=False)
rmsds, full_ligand_positions, names = [], [], [] for idx, orig_complex_graph in tqdm(enumerate(loader)): data_list = [copy.deepcopy(orig_complex_graph) for _ in range(self.samples_per_complex)] randomize_position(data_list, self.original_model_args.no_torsion, False, self.original_model_args.tr_sigma_max)
predictions_list = None failed_convergence_counter = 0 while predictions_list is None: try: predictions_list, confidences = sampling(data_list=data_list, model=model, inference_steps=self.inference_steps, tr_schedule=tr_schedule, rot_schedule=rot_schedule, tor_schedule=tor_schedule, device=self.device, t_to_sigma=t_to_sigma, model_args=self.original_model_args) except Exception as e: if 'failed to converge' in str(e): failed_convergence_counter += 1 if failed_convergence_counter > 5: print('| WARNING: SVD failed to converge 5 times - skipping the complex') break print('| WARNING: SVD failed to converge - trying again with a new sample') else: raise e if failed_convergence_counter > 5: predictions_list = data_list if self.original_model_args.no_torsion: orig_complex_graph['ligand'].orig_pos = (orig_complex_graph['ligand'].pos.cpu().numpy() + orig_complex_graph.original_center.cpu().numpy())
filterHs = torch.not_equal(predictions_list[0]['ligand'].x[:, 0], 0).cpu().numpy()
if isinstance(orig_complex_graph['ligand'].orig_pos, list): orig_complex_graph['ligand'].orig_pos = orig_complex_graph['ligand'].orig_pos[0]
ligand_pos = np.asarray([complex_graph['ligand'].pos.cpu().numpy()[filterHs] for complex_graph in predictions_list]) orig_ligand_pos = np.expand_dims(orig_complex_graph['ligand'].orig_pos[filterHs] - orig_complex_graph.original_center.cpu().numpy(), axis=0) rmsd = np.sqrt(((ligand_pos - orig_ligand_pos) ** 2).sum(axis=2).mean(axis=1))
rmsds.append(rmsd) full_ligand_positions.append(np.asarray([complex_graph['ligand'].pos.cpu().numpy() for complex_graph in predictions_list])) names.append(orig_complex_graph.name[0]) assert(len(orig_complex_graph.name) == 1) # I just put this assert here because of the above line where I assumed that the list is always only lenght 1. Just in case it isn't maybe check what the names in there are. with open(os.path.join(self.full_cache_path, f"ligand_positions{'' if self.cache_creation_id is None else '_id' + str(self.cache_creation_id)}.pkl"), 'wb') as f: pickle.dump((full_ligand_positions, rmsds), f) with open(os.path.join(self.full_cache_path, f"complex_names_in_same_order{'' if self.cache_creation_id is None else '_id' + str(self.cache_creation_id)}.pkl"), 'wb') as f: pickle.dump((names), f)
12protein_path,ligandexamples/1cbr_protein.pdb,CCCC12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163793dpf2zy16h775c0m4o2c3a2c3b2t1v2q4q874j283efw4mi63k8c3s542fda2q555ylv4ozo3fzn3eoc4tn23hfv5gg45svi2r585d1n4yqv1hs63zxh1ft74hww6b1j3di65jaz5ema6gip5am54bnt1fq63pqz6eil2q114nw74ahr1p1o3le83nzk1eub1eoc3std3qw84za05l8a5teg5u6j3g2n2wp11zyr1xs74m6q2jq94m5h4d633shb3i6m4hw36eq53hqy3zos6h962gv65yjb4lm44lwv3g305f324dkr6b4l4j9a5w864mpn5m511ro65q0m3bea1mu62wtd3sr46dqb5hh55q0e2r034xv94y0a5ota3u5l3m3o4idz2w472g5u6cec5wzs3iu75mky3ibc2qwf3p764np34kb81uyi4tkf2fai2xvd5ar82lzg3e621p6e5wqa1p026gjr1nhu4yyl3jzq4pce4gvu4n7g3s9e3k3b1pmn1ogd2j4i1oss1v0k6cn63k3e2btr1ppk6egw4zx14zfi5yso2rfn5cep2xyu3eou4mme4fnn4og74gkh6d1l6dlj5i941eb24qzw3fu04aif5eec2qlj5cfb5sy31mhw2flu3e6y4wiv5oot4bae6bfd3po62wo91rp71l2s5ab13pce2w6z1iew3e853e125arf4jgv1ikw6goo4zdu3wcb2w1h4x2i6ggv3h0b5nwe1o465f2u2feq2jnw3gpj5uex1ndw1zhk4mcd3r4m4cps3gcp2g9v5try4c2v4og33otq2yns4m0e5tkj2m3z3pa53iww5o0b3m585lz25u6k4yw63ewh3wc71rhk3gi42wd73jq85yr56fnf3hx34mz61ol24aa51rry1ozv5jf64mnq5wa53nlb3f6e2xu53wk74p6w2pmc3byo5ehe6chq6c8x3pp13uev3ad75aqv3qzq2z975d1r5ajy4k672w1e5j3v3upk4gj81td75lz96erw4rhx1hxw6cbf5qal1q8w4mf05t1s1fzk4tju5t2y4el52v871epo2r5p4pis3ehy5erg2r1x2f8i2wi75wre3dek3hp24bcw4uau5ap33udy2ksa5ekg5lh82uw73uvq2glp3m3r6bsx2ddf6eqm3ufl2mwp1h4n5f4r4ybj4kz82z604ogi5ufp4uiw3igv5b561bn32xg91u594m5j5oua5qaa6h7j2o7v5v7t2r022j945o871o3k4mr45am76g351ljt3srv4bi62yoh4zed5tln3rkb5jiq2ll61tkz2vj63qrk3c454pks3nf32oaz3pwk3ryy2y7k6dm85ism5i7u2qtn5cuu5n1y4kot5wa12wyi188l3h2o1sw11zuc2nnq4l8m5j754afe5nwi2n063l4w3ibl4l314ruy4ufm5sxk4hnn5q0x4zij3fdn5fe63nuj5h8x5ets4x5z1w3k3hs93ro03zi81nl45cao4gjd2p3d2z8e3w2p1f282iw61h9l4o781soj3krw5g4n3t4v5drr5o0a4c4i2vwx6miq6guk5c3k5fhn3o755kap4zo52jko3iss4eg64fcd3v7s4bcf2qyn1ikx6f6i5os51om26axb3s3n1fl64luo1qiw5f2w3udj5tbj5k0c5ndf1ek24zb83r9o5qah3avb4c524ybi5mi66fu51yc44ymq1xn33dpo4z7q5ehn5mri2vcw2byp5du81i7z1ec35jmx4yxi3iw73l4v3wcf5igk1sz04x6i1wum1d3d3rv61x7r2c574u826cwh2vrj2xag5nw75qau4ocz3chg5oh11hkm3ayd3mn85ngf4bo61b575wzt4uzd1cyn3eys4umc6guh2e992xb85tus6ap74ajn4od76g2l5v405wjj2bow3kc03zs14igq3b245e8r5a4l4ci13qd02ohv3uw53lp43ftw6c5q4e0x4hbw2yoj4b2i3mkn1i5r5tig5bqs5j2x1oz05a2s3fkv3qnj5w5o2cht5dj55oje5o9y4hxs5t365gmh4eh93kr23rk52b544ufh2zxa4mji4e704huo3zrk3wb52iw84ge46ccs5nwc5lmb4i6h4dhu5y6e5bvn4lxd3b3s5j9f3jzp2no31ouk5epk1fo21g7g4dve6au24wt63w2q5tdr4xx91jg02n275lyn1p1q1hi32wih4hym4ew35ixq1h603ppk4x8s5nzn3ddf1yvm1kv24djq3sym4fz31ze85ia12qcm5m9d2erz4g0l5tqg2i5j3ow61met3r425tdi3i971alw1doj3f5j2r5q6eir2ie45cav1n4m5wj62o7n2r4f5nkn2g6p1bnu4uc53kze5dg61nym6cki4kmz6mjf4ch86hsh1txr4zj86ggn4qzx4qsu5ety1o5a4otf1pgp5wex4p4b4h4m3k544j535dva1e3v4wop1c3i4jls5mxv4qrc3fvn5ivn4xu12o4n1m5b3t1a1mqi5n845ifu5eie5lgr5unf5w5u5tq13dkj5ye81br83tsd6dvn1oxg4kz55v3h5in94avi220l4b7z2xbv3twx5zo82w4i5opc4q8y5acy5ncz3in43arp4rt14mq66ey73uzd2b9a5o4z2ow06f5w1x7q5agv5pzm6afh4z1e5flp5xsr1b4z5f1r1o2g1uwh3bmo1p192ans6fbv4lrr1gi94xuh2weo5xpi4btm5h0e4gye6bgu5wlt5oul1t495k1v5lz41fsw6cvx6c3e6cj55fqc1cze3uwl5l3g5jnc3ps66csr6bw43hau3ud96csp5uyu5lqf4bfz2xp63sjo5os34z8d5un16esy3kjq3sl45mgl5dp53n0h5fao4dmy6dxl4qw03q923rwf2xke4gfo3t033pd83f184utr4cu75n1s3wkb2zdt2yit4cmt5dpa4rt02y5h3cde5lud3vva2wev5mrm4ypf5ea43fr54tkh5tyi1db14hxj3hu15ftg2eh81jiz1gww5nih1rr64fp14y241fki3lea4lch2xk14qjr4os14pft5eb35qad3cpc3c945jhb6b223vfj6hmx1kuk2gh91xh63eyl5hng3nes3i1y2anl4xit3n2e2n0u5hdx4zt64f6v5n7g4mc14yc93q6w2cmb5g4m3pww5d7x4cpr3muf5f955o9o5e2w2chx2pk63bet6cje2rd65khk4eh51i9l1swg4q4o1kf01llb5aep2zp03zze5csp5eyk3u7n4z0e5fh65kj22o4k5llg4b5t3li23of83mvh1jut1auj5awj5x731eol1f904crd1d2e2oht1ua42h9m5byz3rse4mp23hhk5tur2xxr2r3w4u6e4qlt3db82bub1ths3s8o3x1k3eg61jaq3anr3ua82kfg4m3g3d3x5a5v3nuu1jh11iy75dlz4wpf4pvy1sve4qmy1pyg5drq4ivt2gcd1azg3wjw2qiq4leq2qfu1thz1y3a5yjp5cgv1oi93cd53w1f2v125f371e033b674q8x5uk84v253u8k5l8o5hlb4qfn4li71dth4gkm6f3e4rn43vtb5l6i4lrh4jvq5est3gtc2jbu2yfx4yx95bs05ea31vyf5a4e3kku3cyw3tvx5mkj6b4d4bny5j8x5tza1uk15yg21d6v5t4e2j4g5tci1z9y2ca84hyf5mg24bcq1lqf6b3v5htc2qh64pul1gj74mmf3sfg5ap22oi94h813s771awh3s743oyp4u5u6euz6eq34obq4u4x2r234tjw4anq2a4z2mwy4pzh5m7m4mzj1o3l3d622xow5hog3rwq2kmx4fpf5ajx1f5k4de75c7c3q774pnr5tkb5hz82vle5ho75xmx2xpk6mdq3tge5fls3oku5jr23e0q2l982uzj5csz5yr63f7i1ex86ft72bdj5l7g1cnx1mmp5j8m2ay26fnq5eng1pg24a6v3ivv2zq24wag3s7a4is61lhw5tq83v514w9x5lto1o865a694zg74unq2q885c1m6bgy4fil2qi12x7o6exj3nkk1q652xxw3l7d1om94jq71lf24xg43sgx1sdt3ow44kp82cem5nzo3oaw2wwj2v6n4g111lf33ljz1amn6hm43jq91qx12wi54old1g5s3tic3cs84er45kr02pe05abf3v044e6q2yc33bys5jeo4b004bek4fci4qna5eh54r025ef74hu15v5n5ehp5yr43dt14cd06gl83uvl3v0l5ne54nvp4qok4ipj4zyi1o3j1lrt3iog5zwe4hbn2gz25tco3gc54l6t5mnx5m232etr5gwy3b5j1oai2ath2v115wuk2ym64mwu5u694i8w6g864f7l2yi54nan1j372xup2byi4f633m3x2bpm2wb56fel3tdc4z1s4fgy3cyz6bh13m8p2df63jrs2wmv6fau5oah3d503aza1uwt4nct1jqe4nb34y3b1okw1db44n983inh6hzp1hdt6aoy4o3u5es15i9i6ccm5nev5wp54bo75byy3su24hlf4c1g3sww2os94men2wxd4qq45eei4hnf3b263eht3oqf3dd03si44v1f4e6d2c8w1jyi4ob15x4n5alc2pbw5eym4e282xui4qtl5jz93chr2p2a1v1j4o3b5v835v5e3byu7abp5jga3sw25jgb4dtk1q913cqu1nje3vhd4knm4yrt1bgo5ih56afe4res1akt1kyv1sqn4oas5u5l1v793hp55ivc1q843avg3tws1rmz4rse5zae5w2q5glu5b4w5f624y6r4mha5etk5nzm4o2b4cwq2pj83lvw2fw31dwc3zln3ejq2f6y6bic4p0x2cct3dxh2xhx1d3q3qbh5tkt4acd1yt75aki3zy24tw73b3w1nkm5uoo2l754l7u4iut1pbq4dow3hab1owe6ft34y2q2hs16gu64dpi5aac4j2c1s506nao5fox3jvs4ozl1zub5wxp5iuh5oh72c905owl3oof4ona4ydg1h081uk02fxs3f374xtz4mww6gg44zz35cf43blr4twc3zsz4er24uuh1i8j6faw5opv3voz3d1g5q0n3kfc3qqs1oay1uvs5os44abe1r0x4jwr1l6m3nf63qip1nlt3zdg3o843ehn3k165szb2j2u5aiv2weg3dz44jdf1ttm3wyy3ifo5j413fl51q1m2y803fr43o561yrs2gvv3uxk2zq05uac3sfi2wk6184l6gvz6dik3u8w3rxb2qpq3nwe13gs4gpl4rxz4qbm5y9l4nh84rra5ey84j032ou75tt31uwf4dgr5xzr4mw43n5k4umq2l6e6drg6ghp2ksp1sps5hna6gnp3dxk5eom1e342xfi2itp2zlf4iva2y4m4o1b2o9v4i7f4ezw1k4h2xgm4nud3m556ezg4x341czo5fqr5he42h6k3fmr4kzb2g9q3tpx4hpy2bo44nhx4mvh2nq73n5u3rjw3emg2xm91kzn5faq5f1u1c6y4j8g5lvr1xuo2vgo1grp4uxb2rol5cbm6hke5tr61uyc3d6o5awu4wz85egm1duv6b4n1t7j5aqj4jh04q7s5cpr1bqm1g9c4fem4wnk4uv85hgq1ayu6co46ck33uzj2qwe3u2q1nl96bd15yzd4r922i0j4hvh4ool3s0n1ba83b4p2ea45k762xzq4yur1pq62y813f8s2hwh1q4w4h393zmh1ftl4ok52qcn3qtf1g523vw03i4a5x792am22ym75odu3adu6cea3t6y4pgc1k1j3d143el44nyf2y0j2w1c5l7k4n6g5cp53ekr2isc5cbs5hvu4n005mpn5zoo3v431t691oj55lle5wef2ya84ezk2c6o5vrl1b4d5za81i802ccb6ce24cfx3m5e1k226eea3s3m5t4f2xyn6br33krl3upy2rm05q1f4app7gch5hx84ok64zla5g3w1h271fkb1idg5c8n1h463w333rzb4xg62rib2uuo1r1h5agu6dcz1r581nlo3g702ofu4k6z4x135ihc2yiw6bgw6gji1tve1gpn5tq54ujb4l336cqz4avh5uga5tzy5op61m7d4aia2bxt4qgh3uuo5vkm4jr31wdy4o4r2c3j2r9m5ual3vfq4c166h7l3tv62pyn2bj44qvy4abk3m533cwk3d521a4q4rvl1d043thd1ogz3luo2ftd4ran3uph3c8b2xp32vtl1fj42zm33rxl1xmy3uo51q1y2ql91bhf2jg86fuh2q2n4aof3ff31heg4cae6fkq4i9i3ask1dbj4zbf2io63d1y5t2l3kwf1juj3i0r4gui2hy03i7c6g9m3nnx5u482v2v6f5h5mwh5m0d5fue3k5k5edi4d2p2cm78cpa3doy3k991vyg6ckw6bmv5m4q5j4n4tpt2jbv3uqr4di25ue45enj3csl3m354a9t5khx5f0h4wq34ktu2qbr1sbr2f6z6cgt1t4v5nra3fed5l2o3mb74bzn1efi3nrm5kjm2cle1j073h9k4d835n4s5yie5yz75cr74e356di03omm4w9n4z1j6b984x614x6m2pu14q1s3n7a4qbb6fng5ya53qiz5awt3sv83doz6dlx4rkx3h914uma1lvc1uy95gso5gsa5drc4j5e2o224loo5t663rz05unj4g176bhv3cii5qcl4nw64qqi3r0i5uff4lbp4bqy4l515akh2yjb3dx03v493g425xpp2c4g2bz64fny3x004nat6f8g4ppc3lpb3tlh4bcs3nok3lfs3o9h2vf63we42yig2kgi5llc2jgs1fkh5ogb5w8i1a425web2llq5j7b2c6l4u0e2g9r1lt55ai53khj6hh34uac5nob1ynd2on66hd43msj5ut42wkz5jvi3gww4uja1pq34u5v4z836dh81h363vjk1unh3hv72vxj3l381a085lgo1fgi5fqs5a5p5oss4o0z1gvx1xur5vqe2j7w2adm3b1m5zah1iwq4zx83wkd5mtv5myd3t6r2c6n2c6e2gpp3opm5n9r3r0t6gue4b703gnv5nyz1fh75wae2bvs1tow1toj5een5fog6e9a5jek1jet5qck6coj1if85t6g4b852fm05eje1ezf3twd3mo84rvt6bbu4ejl1waw4heu4hgs6b672cmc3arv4r4t1j805ads6abp3el76fex4m5o3qgw5t8o3pcn3nw35w843bqn4pin2w3o5yic4lwh3vo34unr4cp54b736c6o1xz85zo92qn32g1r4xc21oe82z945aic4m121sld2h966cn53bvb5x273usx1ddm3fal2iit3fzt5vgi5jv11py15ktx4b351m0q5kjk2vey6dkg5ei36gbx3e011p034zuq4wbo4rfd3zlo5alb5b5o3liw2mwo4yjl4ab85nau4at41ke01zz22ccs5hz62cll4m2v1q3d3ozt4ge73pkd5t703ts45q0y5q1a3ogm5t185c7d3g2k1ikv2j7b4obp4k6y2fb83vbd5ung4b322qlq3jzs3tiz1v2k6ee23zzf1hpv5xo25e2l1jn45aly2jjr4agm3rwp3r7r3zbf4url2wm06dcy2brg5dlx4g2y5jzs5fd25nqr4jpe3tkm5ti05lxp3avi5zuj3p3h3d9v4gs84cwn5q1i6b7a1gjc4dbn5yp55ukj6arj4iuo4ibk5ali6fgq1b5h2bvx2y363f814e3f3t844na72ow74ob01qb12iku5kh71eve1k2v3npc2w686gqm1b2h4dfl4l193dri5ab94qzs3sqq1d4l4dn09hvp2lko1lev3aau4mib3g2l1lee1o5e4os44b343m564qvw4i4f5wf63u7k4j5d1r4w5iaw3buw1eou3vbq6g5j5t4u3fuh2pj42zn74n4v2obo1tjp6b1w1ru21fh94wcf6hh55orz4xmb4jfv6ekq5q0i3h1z4ycv4ura4prn6ev01v3x2pqz2xjx3k5i5dtq4pn15bue3ik12h5d4jbl2x972q722qpj1acj4k6t6b1e3f3e2yog4kio3qem3ued5mge2bfq3mxs4k1b4p6g3td45mnh5ien3lk82zx61rql3rm45u4c4kb75ap14rj85tkk4j046i8b2nxl3zm44dy63h0z4zyf3e7o5li34qjw4aq43kpu5oq73h2c2qnq5jn95lvx1r102l8r5ega2wi33rxk1upf6chm4w9k1vja4zw75ov85wag1x8j5a6b6br24owv5ev83drs6fdc3tvl5mlo2xaf3h0j4yas1o355dex2x523lgs3fkt3dcr2ax66cnj4y5d4umb3l4y6fkp5aoj1ony6b955ueu5ahj2xel2g1y6iiv3b1t5dht4zup4rlk1axs5fnj1izi4gvm4xmr5yhg3g453tao2q7o1pme4rrs6gl34pct2tsr3qtw4uua5abe3ozp4lc72bu55kya2q6h1n953k843bl13ui22cgv4ez53t3c3puk6css1ghw3ezr5il11a2c5j6l2gss1n1m5f1x5vt44y621bcd1pwu4fht3w9k3qu01zxc2vtj3dnt2pu24hej4x3e5ive2wo84ozn5i2f6dj74a6w4q1x2g631jak5knr5y7z5npb2izx3jpx2x384knr3rwe4aze4nrm6er36d595a2k4cr95i294mbi6ht12d1n1uj53ljt1kyn5osd5whc4qws3uwo3th92r2l5n8v2y544m5n1yy66fui3lvp2gdo3hyf2zva3zmu2pt95nxg4zsm5eif4qsk4djr2ceo4apo5gj91q4x4wz52vx92qzl4keq2b174kzu1bdr4zjr3ftz3cic2c2l4yo81vj51w4p1aaq2q9n2yay4bea1szd5acb5db15ne11vj63n5h3kpv2hvc3arr3v0p2fqw5jf73udq2n145mk32pj64pp54c685q153u8h4erw1sb15iz86iiu3txo4nah4ir64ufy6fer4zba1jij2piy5td24yzc5qap5yhl1h1p5ni74pf34a6b4uy12xwy4el02w712p8h4d7b4yoj2ms44iwz5ctb3t854lpg5bvw3uri3hfb4mr33lq83mlb4qwf4ixv4njd5tzo5qa95ai83o234rn65i225u2j4o724ej81rv14ixh1w823arx3k023uf95wij4oq51z4o2qf63lq54yw23u4h4f204mg55ufi4n8d6mu15zag4az24fbx4emv4bqt3t2q5ajw4q812fqx4kza5k513u4i5ho83lkz4ciz1yy43bmy3vf52w6p6fa24flh4w4s3i283oyl2nn15lrk4e3i4xg94d8n3lik4aj24jt85j7w5std3h2a2pwd6bjo3nik5lxc3qce1vrt4qxo2y1w1wok5lne5am65er13ob11w4l6e2m5wh63kf44lnp3el51w844gm83o6t1q836fut2ycm3cqw5ot35dp81g535va94wx75kww6bu11q6t1uto2bks4fmq5opr3ies6hti5u664qz66b1o4gy55mrb2xml3skk1c2t4in94mss4kju1hti5l6o4wkb4dus2am13t5i1dkd2onc6hvh1ypg6cvf6bkw2jt53fdt4wh75i3m1azx3fck5u6c4ded4k0u5xmu3wk94kz05a7c6g9j3iw64ddk1icj6eyt4z2o4e3h4c702y573dzt5e0g4nrb4qr35ltn3omg6bod4jpa3fzs6f5l5edd2oyl2bmc2xqq3kqy1oiy5y134d1s3ked5djp3bxe4bo03oy34o2a5em65tfx4d9p3tku4p1r5nwz4bs43oys5lgs4nyi3l582vxn1y983ck71nh04an01mcz2h9n3h0s2ycq2x4s4acc5ows3rxa4dhm5lhi5l8c3rxi3r005oq51jev4ztn4yb74a7j4os73e3c4acu5hvt3lf04jfj4p445dxh1d4k5ewk1gx81x6u3g2z1i7c5opb4y856fii6c7q4jkt4lbl1w765dgz3run4qoc456c5twz4a4h6gl96h7z4fxz2hu62ohp4ayt4fgx1x8b2y7x4yb65i8c2aoi3kgt3g2h3gwx5lyr3nk81mrx1pf86dj14jss3tu95cqt1yds3hy95y5u6dko3s0j5hm03s3o5om72j9n4bfd5wzw1d3v4pvv4i0s4pmm6ftp4hct1c5t5i3v5urk5q0f5xv74bj91css4azc1hqf3kej2p8n5tg13cvk6awp1e3g1t4e2nns5al53cr56equ5fl52yex5lsh4fgz3mv03l5d1q6m5khh5c852f3e1npw5w1e4j0a4mvn5ioz4yve5tbm2fx74oex4pjt1nnu3c4h3vp11bky5ajc1jcx8hvp4wvs2vcx5hkh2llo2jkm1q6p5mf65afj4l501o3e6evm1pyw3l3a4mnx4fll6hx53ivc6mx85wf55a1f4c4g1w5w2w264an95n8j3aqt4dho4l7r4aro1stp6g074hze2cbj5wbr5afx3bh34ca86aam1r786aol1gcz3bjc1o2x1b404u455nat4qiy3v303kyq3unn5elf1xoe2oqi5mpz4hxz4rfr3vp36upj5xyy4wci2fwz6buu3ocz3v3v2yq64m8e4r6e5ihh5ngs2v773nzs5tyk4l7g3dne1m5f2xk84urx3ft54br31bgq3fa32y074lpb5k0m4tlr1ocq4j5c4awm1ado2n3k4mf14oho2xv15hh65kmh4lkt3n2v3o7u2ieo1wbo5i254mhz5mmp3qs82ykj5igm4zji3zxz4b711fpp2y766eya5lch5gp73mmr4qc13sbi4bsq5yhe5hj94qw11px41q5l4i9z1pbk1o5b1ryf3oeu3nx74izy5lvf3hll4jbp5icv2yln5om31e2l2oyk2c0o5w5v1b2i3w8o4x606h2z2a3i5jnl6m9d4twp5gmu5wg42mkr5e892j783elc3eb15wlv3udk4p0v5ahu5two2jf41mm63c4c5a2j3ti43pd94rx84yhz2vr06mim2k003fr25q0o5dgw3tiy4jxs5xst5tpx4j1h5xva1o492mlm4alu1tv64g2f2xp41lhg5aoi2bz84kbc1h225tho1wun1d8m3m171slg3pcc1oh42vio3v6r4n7h3fv84f082p335a5d3n1v4j4o5o1d5ewm3ds44b3b1sqi2nmx1gai1fax4deg3suu4rcd6f6s1juf4zx31m485ttf4man5ljt1y0l6hsk1gyy3bi63fue1c874byj4r186bnh3qpn4r4i4e5h4ojq5aqt3fu33oap3d1x4j485uig5vcz5tzd4hva3mvl6b1c4e964d884ufi4uvu3met5aeh6dh54mrh5fqv5t8q6f7c5l173zim3k832p3a4wsj4cd12xk75w6u4zs34u582qn16f5m2c8y3vw61o425uor2ycs2i4z4q1d5m0s3qup1tr75xpn2aa65uv23pgl4mk75uir1p574ezx3shj5csw3ibn4ag86ceh2p984yht3k0k5neb4ysi1bo51a283wha4nq61czc1ckb5j6d3hr14acm6hrq1py53km44c661sr71rnm3krx3d255d6e5w4v1xbc2x8e4cmu4f095afv6bkx3lqj2hug5dnu2woa5xvw3fi34yho1h1s1w3j5y591sdv5tmn5myk5f291efy4ayy4ykk3m6p1utl3zls4ff85f6d4k8s2mpa2gfs1c865e5g3zvy2f3r4e5j3l5r5l012vj84b9w4i7m4qwu3rpr4i7k2c1n4ret1owk4mxc2ohs1akw5tyh5huw5w145lb71f8e4ciy5etm2pwr5o1f4r1e4ncg4abf1my44jib4nxr2jbo1njd1pdq1qj75fi62vtp5dro1o3b4jln2yis1rt24feq3gjs5eef2zx83ujd1fkf5eto1c5p5tys6ayo4eh43djv3mhm2pow1w0y4dbm2ywp5uhi1mj75am31pxp4uff2bq61n1g5nxq966c3vws2of22ydf4nbk1l0a4u435trh1rpa5etv1h612vcb3d1v1xq01b3h3svj5fun4bw11kti4jof4izm4phu3jy94urw5ael4irx3avn5mm95twl4w9l2ad54b4g4a225vfc3l3q6fn94m142gl04c353iob6apr6g3v4cik2xpb3loo3drr3e4a5thi5mgm3mrv2c4v4i8n5obr2qyl6ee42wzx5j8z2itz5t2i4mdn5nw05l9o1c5n3bel1nt14g695ovv1i9n1hlk5hh42hhn5v132ww02rcx5zms2ncz1a864uuq5g2n1o5g2gfj5d3j3dpe5ldp3veu2vaq4ui51hp55g1a3f394owm1dl73ce32qmg4poh5azg6by85l7f4awo6fh74ifi6b7e5i3x5lws5sve3kn03q2h5eoc6b7h5ekn3rqw4erk5fso5e802bpx1yw83sc15o4t5c2o4u0f2w175nxy1oy76dvm3k001py24zx04nkt3s1h2ym56cis3hdm2yj24ef43kvw5cu26c1s4j6i6bij5xgh5u2c3m3e1yid1b6k4gd65lp14ww61zhy3eky2q384jym2ymt3gur3suv1njs4na84msa5nk81o4k3l6h1i5h3t6b5e1s6gzd2eum1z712yc56hai2a144aa44ask4ea13pxz4n4s5wkm4jg03sie3pkc1w1g5y8c2c6m5ou36d505v3y5lzj5tya4c9x3eyu4xtm3agl2brh4mbf5d4a2zz62gbi1t5f5jiy1nw73hl76h7f1zd43suw5fdc3cct4pm02y1x5n9n4gj25d6f4joj5klz4jju2gg75hn94tjy4r916ffn5usf2clk5n702ohu3eka5eq14qlq6eis4acf5t354orx2hmw3fz13qx54zhm3rxo1atl5t1k3np73zt41bdl4u6y2jbk5l135mob2igy5jlz4flj2zu42w705d6y4kip2uw04msg6f8x1r2b4qvm2ydo1w4q5okt5op43al32rvn3dp14luz3o871w2h1fiv1uh16c8p4g8m4hai2evc2q2z4yyt4od05k9w3fyj5vh05ale3th84yhp4pvo4whs1c4v5hed5qbv2oei4y2s1z6q4px62knh5kns1m4h2g963cm74gcj1qft3ztd4yzu1vwl4kiq6ax13zyh2c1q6mx35o9r1q8t4ue12y7z3mdz4gtr6fh64qvq3tti5ap64pkt3tdj3qnd4lvt1xo21pcg5fiv1g3e6gx35dhj5ixt1xhm4po71a5g1haa6egs3iw85qag5o1b5brz3mpt3ral1j145wdj4io32irz3f355jan6mrg2oi31onp4bjx2i0v4hmk5mat4h2m4agl4ayx5iwg2xez5em75kdf3vv64y593ti65gn64u7v3rz75wxo1o2w4r0i1a305nz23rf46ee64oiv1a9u3iop5x4p3gl61hqg2oji4ps32w051tnh3djq2c9b2flb5itd5k001t373g0b6hdo2rfh1b5g4bdi4ikn3inf1rww4g684djw5yum4hxl3dbd4hw75mys3p7i2j7h2vvt3r2y5ng91y2g2vwm3if72hl43ffp4qwg3g6z5dhf4y793m574oyi3s0b1yvx3v7c4md64g9c2w6m5tt73pkb3upi2va62weh4bao5gid2w1g3mxc2fw63diw1ind3i3d5k0i4npv2wf52q7q4wyz5xaf1gj45hf12aw13dbu3o9i4l345j0d5afl2w3i5ew35e0m5jfu4fm71o4h4w9p6eyb4onf4zhl3mj23k222xxy5m5q4aci5kab4dpt4rsk1rsi5c423tb66bmi4myd2i405nhj5moc1tom3ds61lt63eft2w8g4d1y4yrc1tu65hmh5nw21k9r3mxf2q1j1u0h4ye34k605zop6htg2fx94q834y8y4gr03uqf3vha2yaz1k1m4i2w5ovx3db61v2p5njx1wtg3uvn3h892q7y4o2f3fv14eu33pwm4tmp5ulp6di14iks4dhs5hg86b1x5nw83tjd5yve4uwg1jd55km52w4x3umx2ony1bm24pku2pj92m414z8a2yjq6mwe1prl5y1y1c5y5ak61ggn2usn2pv21w251c4u4ba36c2x4ijl3gxy3f3u4io24drm3cjo4dst5c875ni82ll72pem2x7d3zc61m2q4gk23lqi3c1x2az91fv01gz31gfy5mte2nxm4yml4yog2g6q1t793hdk3uij5vl24ufk4aph6d1u4rn21zxv2p4i1w803bl72vh03kqa5vdu4b2d5jgi4u0i3g9n5var4lnf3e9h2fzz3cfv1ws45h212p7z4j8s5fdr5z7b6cj15tts6bmx1g491mqd5ost2qhd6e4a3fur3v1r4wwn4hni6e831gqs3eko1dmp2wnj4i6q4d8s2jb54p584usj6eq63o0j5apj4ty15avf2xef1way1a7c5f2r5k1f2c9d3a9i3deh3q3k4xtw6f0y2r3l4mra5qa44zpg4ijp3wyx1s5z1y2h3qi11c835dts5e1d5j9k5o4f2wxi5f042qmj3kvx4l7j1d5r2vyt4cfv1qcp4hlm5d483snl5uwn4yll2brm4dzw4q7v5teh1c4y5mro4ymg3b1u2z9g2rt53gxz6e0q6f7b4qz55dh53v3q4do53k0h5dt23l543ebh2hd65hbe4wri2qi71jao5ajp6ej33gjq6f8w5y201rwx4ibj5op23c6u2w0s1c7e5yyb3ni53t8w5ntp4dfu1o4e5tqu2xyd4pl05tl92vpo4ov54qps5wdc4awp4a9s3atk4nja4ms03fzr1i9m4b5s2y713f335q0h5x9p4p4j5ajo3c564pnl4fmu3uli5nlk4cs96hkz2vo52fts3sfc3pke4dk51lor2jdn3jya6bqg3p9t3qkk6fnj6fmc5c0k1mmq4fck5npe4j594eol5m574efk3bt91oiq5dwr3wyk4qf94c5w5tuq3oqk4xj05mwg2vwu6dpy4ara3wi65owf3nw54fhh3sna1uye2vcg5j7j4gtt5jc12ph64zpe2hz05l4i1y1m5vo14y2v1ecq6eeo5jrs4l236f344r4q4quo6dq64e3k3zov1cet5e2k5jyy2jld5jna4qls4ksq4py46biy2hqu4yk54i124km05ttu2za34o5g2y1g4cff4ztr4jps4uin2q932x7t2q6c6ayr1pwy5lwe5cxi4n9b1fzo5ukm1ork4mk01jbd1k2i4ifh4yh43fee1flm5tqe1jj94li54jc15i8p1lah1apw3ppm4kn71m5w3vbx4ie23sur1nz74trw4qmu4qnu4os62bge5xvg4o6w1nfu2zjf1fpi5id13ccz2d3u5tyj1fls1ggd5ofx4o124wf43pck4ayv5jt95nb74b845ggk6h5x1r5w4zw65d6j5ep74duh4ps04drk1los3s6t3be94ipi3wf74pow4y465izj1d4j4qg72avm1g851r1i3g1v3l7c5wyr4oti4a4o1fvv3uok5n3v4tim3tv84a4g6c0s4fak1w124jn24oyp4zt75emj2rc82ypo3kmc4hwp3q2j4k5l3hwn5i831j4r4fyh1kfy5g434bnv5fpu1o486ei46ekd2k3w3ksq5wkl4hzz2f8g2uw36mi64u913f7u3zk65n2f2qx03mrt2f0z3qvv1l7x2oc13gbe5he31pun5m4i3pp75o914mjo4fns4xnv3tay3ejs4c1w3njq6guc4dv84el91iep1ta23h0e1bsk4pri3pcb4jg83lbj1i8h4a4x1lhd2wa35tcy3wth4baq1ylv5bve4g345u281qbv5z5f4ot62g975n161m5e3efk4h7q2v5a5vs62cne1pxn1jqy5j6s4abv6d6t1t4s3zsx1p012f4j2gh73f785i383h0w5d3x3zst2lbm6fil2vk26ew72iu03t0l5ai95wbm4ark3hlo1np02w6c6dk15xih5hk21qhc3v5l1vr14no85hmy2jql1a463kf74lv45hbh3wf94ieh2vr35dyw4xuz1mmr5ar04h4b5knj5elv2g794w522rnx4rgd2az83c1k5ick4lv34mwb5a831prm4gg51rlq1rq25fbn4e491f474yfi2v103pa34j1f4jvi4gmy2v3d4cft1epp2hoc4r5g4k0y5zz21d3p4ng96fav5hor3qci4mbp4msu5hg11pyn1hmt2lpr4yha5hoa1sln4h3c4k642w0d4lmu3tf64z2p2hny5ctc6cck5vd13qcf5ia03l7g1eld1xh91h3c4urm4j7i4ly91nu15sz56cdl1uvu2wl44eo45lj22qrl3kc15nqe6gon2xs85gmj5eyd6c424wks3ka24p6e4nnn3zvw4q6r5v8v2jdv4lxm5qcm5e8f5y803ud54n701jwt4cgi2uw84ajw4ivb4m6u2xu16bxy4ud73k5f2arm5jin3fmq2nt71p4r3hxf4zwx4xx34yee6aak2xae5t313bhb5llh5nge4b9h5oxl5ipa1q3w6d566df13ole2v163g2s4led2uz64pnu3nrz1f7b1j4k5ku91a4g4uia5kv82rke4e8z5ykp4z1n5sz14oak3twu2r3p5cf61ym45l4j4exs4qpa2k1q4eny4i0r2xz55fxq3re46cf52cbr5ece5t2t1x8r4n3w1klu5nxx5jcb5klt4usw5ek92mov6bid1mjj1tlo2hb92f944luv5gu43wf85ufo4n5t5hcx5mtw1o385z1c4w4z4v271k213jrx5l961esz2m3m5ivf1o3p6std4auj2lyb2w875j3l2fgu3snd2w5g2wsx4qfl2vuk4a235iu61siv4ht22ltz1o394p0w3p8p5ypy3zvt2c5y1ayv3erk6g4y4ucd3e164i7p5alv1osg6gw15wxg4bvb1nc15ugg5t1w3tvw5hkb2r3n2iog1h1r5eyc1ogx3er35q0p3rlq5itp4nuc4w9j2b8l5khj4mz43zlv3okh2epn1pwq3gsm3hzv6dpx4hvg1s176arm5jq72v885lay5nn44hj23pp01rst3qcq3rx85ewz5mgx4c1t3cso4wq24gxl5isz2xj24y5h3zcw1l8g5vex4tky4elh4ejn4pgh2wuf2xbp6gw43d7g5ksu2qrp4jg64eqf3hbo5yjy2gv74hdf1yi35edr5nmf4w7p4fz61g4j4a2a5kx85a0b4qta4mho4fn51gj83d941kdw6euw6gpb6glb2xaq3vh91aku5j4v2f1g2vfk2r5a1g1e3buf1bzj4abg3cho5t6j4jda5ywy6cdo6fo91g743oxi5t8p3pcu1fyr1fm95ddc5hwu1xud5ai14e9u4uyn5k056fgl5iha4aa21wzy2w853s2v4yuy6dud1xdg3bgs4hiq3rqf1jmg2xeg4g936c7b3zso4xjt4rsc5q0u5iyv1qxy5n201you5c7e4x9v5tjx3rtm4b053tg51b521w1v5lg32bmg5wii5wew5iua2g001nm64wef1i7m4hrc6at01biw4uhg5hvp1ugy3ery5ll45v6y1ru12o4l2evo5lvn2rc92fci6evq3rah3g2v5ny11p103o965vsd4cxx5kcb4g2l5vqi5svl5qax5h6v4aa06g1w3ddu1pzi3sax4nmr4c1f5d261elr3gc73c842y1d3vd42uzo3v8s5mqv4zly4p0a5dlv3qqa4g3g3h9f4wr85win4hzm3rqe4j1c4kii5mw65mwj1xap4zv21ol11a694btt5t4h2oi26bbs6aaj2y4a5i801hte6cfd1o4l5kbe3saz3kqr2b073iue3bxf1is05a4t5ktu4agd3nf82nd05yyz2ay46fhq3f3t1zhl3vbv1g9s5aut4u711q665vb93qtr4nw23qin5mzg1d9i5h083rv73rv86ckx2itk4ij11pxo5nt05x624oc45qao3le95dtr4a6s3bls1em61pus3asx4lng3mvj4q3q3s9t4gfd2r8q5wqc3ri15ih86g6w3cjf6duh3shv4pda3cpb1bp04lmn1zm62kup3ij06cz33v3b3vru3arg2o646ayi4qab4xu25wzu4lh21w6y5eis1czr5jzy4ejf4ufe5wqd5f0f4aw53iqg4p902ank4n1u6eku2h231j5i2y7w5alj5jfr5eak2gfk3be25hln5uc13ax54f3k5qb04llj5ldk4eyr5v3x4fys4crl2zxd2etk3ddp4q0a3el02ica4yv84jin5enc1pb95jur5n1z5ou24y8d4gby5acw4r765hrv2jt64hhz3ocb4qxj5er53hu21v2l3dz54j8b5vqs5khd5fho2f713kdt5gmm3sd55fck3q8h4h366bm64qmz4ks54dew1nf85ap03s736chp4r3b2oag2w065j742a2g4ju73i815aol1af25hda3nu36das1swp5njz1b741sts2co05od13pab5u062gnh3uig2uw52vrx1ele3hp93fqa4mh72xkc2w3l5w735hip4xv21fch2j4k1o332v571kqb1bhx4a4w5bmm3dcw4i9o4ydn5xii5duf5j1r4no11gvu1ycm2l3r4wnp4yzn4p751b1h5hwv1s4d3rlb1c5f4fqo1iau5mim5y935qa63wk54mcb4qms6b5m6fba2q8z3r925mo03wvm4qh86dgz2w662joa6gih5fqt2viw4o762j833cm23ion4y2u3fhb2rip2q946eiz3ieo1uyg1vsn5fnf2vgp2pk52f6t1zfq5ypo2nnv4jvj2cej3hqw2boj2h213bzi5ut62toh5urm5ml82qpu6f5u3t3y2zx55alu2vxa1z4n1c8k4w535cf84hcz1jik4b815y865ul65l2n3dhk5vio2piz3jyj5ly26do41v2s4ezo1iht3hl84q1c3sk22xjj6cdj4w4w1bm75lca3rxf4q7w5ceq5aen3kjf2psj4avt5nxo3qn71d6w5ory3ckr6eyz4lxa2chz6eqw3nzc5umw1ilh1o4j2pks6evp2wks2yc04xy82jg01u335iez2zxb2qnz5wfz3ob01g364at33pd35jjr6eo84omc1k3t2vl84y8x3l4t3s2a6f4x2qrm4u684o3f4rpn2zns4zvi5ul13fwv1exw2vvv2aof5vfd2qcf3bl03gk15i2i5w8v4ptc3piy1nlj4ddy2vwo3kdu6bt05l993rtn2yk16f281zh75uiu4eh75epp1o6h1b055t5g6b1k4k755hva3ips5obg5a3o2q895owc5ggo4xk93cf91czl2ewy3a1e1xlz5k0b2nta4gvc1axr5fou1kkq4u7o5i4o4cwr5fa71i5d5hdu2zg32pmk3mrx3s1g6mvu1wkm6dvl5fe95odx3sbh2jiw2r434ibb4o052v134io84z2h2vmc5ggn2afx1g3c2cn03oki4xty1xgi3mmf5v1d2uxz4wwo4kpz4xbb5up02gzl4r5x3iet1oq56afd1b556chl1xp02q5k5ti75uqx6bm55w941k1o4lm31ek14ayr2xxn5lsc1o0m4ui71ppl6beh3ud74zxx6gzh1uu95jgq2q955l2y3v3l2gmv5bvo3snb5q135upf5tq33gw54wwp5wbo2j7g3rmf1fhd2w2u4flk2r0y2wbb3da63l4z1v2w2azb2bz52oxn3f8w1w7g3moh5m3a5aqq3tz03zyu2pzy5usy4mx04cpq4aq65eld5gmv3qbn6rsa3u5j5h1t1ms01ctr5lub4h5d4n994cc24hzw5lbq3ati3pd21f741qyg5dhg4mwx5ohy4ob22b2v3c0z2gtv4r755w2s3wsy1rs22r6w4agn4gk44qq56bfa1n7t1ocn1gnj4u793hmm2vl11ec15f4u2zsc4u5j4jfk5kew4btw2cbu1vkj4jnc1nli6bw33fyk3cl26f3i1w3l3gv94h4e2ylc2fgi2ha55sz95gjg2q1q4aza5yia2rny1o303m1k6dj51pfu4awf5oqu4k422wcg3oj84ngs4lq91jzs6g9h6g9u3axm4qp74mma1g985wi05iep2opy6eq12pri4y2j4x1s1bux4cjn2vnn5d2a6cms3g724wz42las4his5ohi1apv2v865nap3wdc3d9m4kzl5ixf1fd75f255js33d7h4ceb3dst4yym4x7n4cr51gar4z2b3iph5t373zqe6m9t3m543szm2oxx4mlx3uxg3qri4l0v1a075qay4cwo3r0y1wbs8gpb6bgz1ecv1ha22kfx2be26cjw2p945tq75fsc4btb5yov6eox5am22pvm3gn72ql75j581msm2bjm3rt83ds31m134nxo2vj93fqe2m0v3so94r5b1v2j4bks4tkj1jld2ojf1z5m3m1s4lpf4zls4af35eue2jh62kvm5etl5hn03f6g3fdm2jj32zjw3sfh1ong1noi3cen2p4j4rvr4az52wqp6fnt3ejt5c2h3sow3ml21ld71yz33m2u2wcx1ec23iqj3ccn3r1v5foo3cn02z4w4ks13rtf4bfr2pvk3ppr3r934x9w2z7i4hdb4bti1eef6bln4wyy4bw33mks3iit2axi4urz3q2a2w123aho6e065dy71gi13az84ew23tgs3zc52ggx4ih35u004qkx4oef6gjn1ewj2xii5al21o4p2xck3dcs2g0h5adr1kv16h332wl56h3k1qq95vdr5x4q2xk33p4f5prc4gxs1qm54aw82eep5l153tk25heb5aia4nh95nki3eos4m8y5u495yh85ylu6f8r3nxq2x3t5exl4x0z4rj65ly13zo42nw43upx5btv4n3r5ek03otx4r4c1y3n5cal4dld5z895sys1ybo2cmo1k3q2ima3wv23caj3vv71xug4l2k3aya3gs65alg4b4n3zyr4hxm2ov43n9s4n072jnp3zxr3v7x1aid2zis4u8w6e2o5yqn3oc04b1d3g9e4qw71c1r1zsf2nm13cs72x245d7c1bji4yl34k782f9u4kab3rl74n8r5etu5drs6es02g8n5ol32i6a5gvk2qrk3sx44q4r5nq53ctt5kxc1tyr4j0z5z4h2uzn4oon2ohr4re43prs1f8c4jvb3eig1dbk4p744zg93wtn3l7a4cdr4fli2am92jkp2bts1u9q5ea66db34b6o3nnw3p5k2c4f1rbp2xuc4hvd3ijz5n4t4jr56e9w5f634cjq1b464j4n4kcx2a2x4h3i4k4f6bky2bak5csd4mgc4mwv1mzs4ym24ztm5epn5v7w5hes3n492zlg2kbr5fng2fgv1f4e2gd83g6h5u0f4j445v351c9d6g6y4azi5kpk4ui81no94p3h3gcs5ngu6bl11q6j2zda3b271o2j3u2k6mil1n7i2wec1h6h3owl3g341ec94crf3hha3qiy4dh64pid2y555hhx5etf4xar2pvu5ito1li33dya1xsc3ti31tze6fmf1di92yke5f4p5sz71m2p1uu84y643rt63vs33nfl4bdg5jv03wd14pge5cxz5ak44mdt2j274lte2ayr5m6f5dv42qbu6ciy3ekq3c7q2osc4r6w2ph93qkm3hhu4xqb5jr62uwl5ezz1y3y1i8i3sxf2i7c4m1j6rnt3g5y3hwx2p831mik1mrn1sm33py15fah4pnn3tza3zmp2wxl5qaz4odf1eix5b2d5kdr3hcm2x913frg6gch4qz21hvh1g3m1tnl3s7f6cpa6g0w6ffh3kec1nj56afr5kup6ftn4o972i5f5nzf2f895fsn3nex6b2c4zt53gt93sud5btx4fab3fxb2x4z3l4x5svx5u981oim3lpr4pqa4pnk4ogj5k0s4oba6h7m3aas4zae5u5t4n6h4dsy1ywh4w9o2qbp5d455lhu2bro1uz41ugx6avi2aox5nb64he92oz55n241h8l3pwd1it64rvk6b272qu54x7j5tyo2ym35mjn3h265ufs2wj11rt11kz82zbk4krs5j873u3u3g1d5bms1u9w2z7g4xv14ngm4j8t5d115c113f174alw3q3b3rwd1c703iiw1hww5kv94wey4ok32ctc4bcb6e8m3shy4mnw5ut03lcd5yc32vwz2xbx1o0o2vj16b334hnp1w704bh34gng2q8m4rrr4rqv1hih3u1i5ovr4ach6c0u4qiz4k181e724ocq1b113gds3mwu5ivs3bux3qc45ovc1pu71y3w4v016e7j1uu35dh33tu14q3s4r5a4z163uyr5wir4exg5kby4iur4zv15xsu4gtp2o8h3wqw5th75tv31tfz2v3e5ntw3cyy1ny24q6f2pjt5w7x5jap3b685tyl2a4w2v004nks1ets2fq65hbs4r592ama2web6e4t4xm63bkl6fty5v0n6ge72boh1ikt2r5d5alh5szc1cr64zzy2p1c1phw5w923l9n3k8q3eml3nij5amg3bv22w731h353tne3jyr5l9g2xsb4f702iuz1ml13ewj4mk92lo62jiu4es06dqa3kab5mxk2i0y4zy26cqt2i472i0d2i801nfw5uzk6hd61y6a1vcu1e2k4wz61nc64zyv1wcc4og43il61kzk4frk1nms5kax1fwu5djr3a1c1hdq5ml65l4h4rj32x4t5nk92xj13mfw3gy35nvv4rh54jxv4zs25ivv4axa5lli3q5h4wmu2z504lkf1rjk6g934nni6exs1nki3i7g6ei56erv1z3c3r5n1lol3qk51rhm4jfe1xm44gny3ti14hhy5b5b4fjz3w2o1oxq3wk86bl23oe83f7z4j3i5ogl4my66fob4o1l2uy05dqc1g465orl1uwu185l4z072w8w3l3l3vvy3jwq1o2z5lsy3iok3g6m1sdu4xtp4qt25fdd5ia21ux75jhk4ca43qfz1qvt3t9t4j0y4x493lpf2bpv3jzr1fcz3qps4p7m4hvb3cp95jm42q9y3eid4o4y3cid3nc46b1f3rth3rxe1sl34ap04mu71pvn4jfm1rej3ens3e9b4hby6guf3iiy2z4y4to85t1i5upj3c894dju3pcg6gu22euk3vbw3px83g4k6dh01ukh4rxh2ien2upj5m443gzn3eio2hk53emh1o3f5ipj6dai3su53sh14iic5e0h4fs44m3q4wf22osf2pj32r0z1jrs1i9q2zgx2jfh2ow92aa95vt15l0c4ybk3zmt5kr12r7b2lh82wyn3ckz6lpr1usn3v2n5oq86bhd2pym4xaq3puj4ek91eb15o1a5k5c2rnw5qa82zg14gtm3uec4ncm4alg5hvs1lxh1y6r5aux2qwb2h2d4qir1s891qwf2avv5knt4odn3o1e3lj73eov6cpw1qca1jii3lkh3rul4g4p1qk45nkh1w0z1jlq4ngt4meo4pmt2v2h4lm23bu61bzs2vvc1v0n5a7y3d674u0c4uxj4b784bo22jsd4aa13ga55hka3vtd2gm14x6x6ma22ces4ayq1tpw2uxi3gc45ye72cbv1v0p2uzb5xvq3r7b3umo3b8q2y6c3bc52bes5wa74f6x3uvk1hgt6m8y5twg4avu5vwi1ms65xo73dcq5km92ygf1zsr1f405m2q1bl74k7n4hvs4z2i5voj3ck85d6q3g0e5y0f3dpk1bjv6bw53dow2zif1mzc2nng2xnm3f8e2ndg4lh53e8r2e9o3uih4hlc5moo4epy2i3h6fby6ew63ama4l0t1vj93pup2xct5fh85ivz3pxq1str2xxx2pqj5mra4o281d6n1pr51rpf4tt23bhx2cma3dct4qt06f1j3gvu5yy92x812cv36fa45jo03l0e3p3j1eed5aib3qbc1n7j5fpi6bnl5v8q6gxw1rw85zw64e3d2mji6ayh3lcv1w2k3zns5mty6c3u4ks43ds94hld3elj4j455v412yne5nad5lvq3h0a3d9p4tu43ip51w224kbk5lqq5wyx3ps15ou15j9x2xru3t4p3uzp2o2u3dei3u934z8m3lhs2f813fn04iqt5laz1xot2z521zs01oau5d473o4k6dcg1o4q1csi3tpp5nwd2wca4ie51u1w2w923r4n5aae4gja2pj25f2p5hjq2yme3cbs5u0y5w3i5qaw5d3h3sb05alx5g573uhm6afj5jf54ccd5mhq5etx1clu4k6u6g284zyz1sj04eh32r5b4pyn5eq01cil5le15nyh6bdy2auz5vm02ff13f8f2rka3dda4iu45bs45a0a2qn24fyo1p2a2uze1x384ps82g193nzu3gi65dtt1gaf3nii2xm84att2vex4jx76h344tvj4lh33pvw1ai71kc72rl56c0r4rcp1nhv5mw24mg71drk4mzh1r6g5xpl4o743bu83cgf4nie2a3b1xos2wlz1a375lpj1yvh4xhe2lct3lau3zki1g2l4uiv6b4u3jqf3ixk4pvt5lpl3sdk5km31t7f4z2l4tk12j9a3bbt3tjc2qi44acg5tuz4lbo5uuu5ckr2h2e5qai1qxk2wyf3f0r1rd42ipo1ukt2xx23hvh2bmz1jqd5d244cpy4bdk2xu42evm6alc4r5y4oc53kdm4gk35wvd4pz51x1z2duv6fnx5u4b4dfn4agp1n9a5mny3hqh3o8h4qem3l814c0r1utp5z685tuy5fb73wv33n7r3bze2bvd2fx65vcw4ibf1zom4f6w2fdp1i911d2s3ikd4w9e3fej4ntj4wk72a293f154u6c1ing3wq64ock2yb03wtl5yl22hz42gbf3r8z5cso2j955jxq4ofb2fr35b4l3ovx6cha4qwl1tl93mo23c8e3k5x1uw63fhr1b3f5a8z5bvk4o622hb13qxd3i4y6g9d6gop5ajv1oar5flt2zhd2xey4ikr4ckr4ufg5xvk2vmd5oci1syo4lq31dtq5bpp6fg64cki5wei3fl95cnj4os56awn3atm1ypj1odj5msb4f2w2h5a2w3k5w1v1pi44kx85m251dhj2qki4b721n0t3oag5dyo1ql95u7k5mod5mtx4u6w1yk73d8z2pnc5em85cil3iny5l2t3u6a5fow2owb1k1y5nf93ijg1qan4ad22p094xir4tqn5q113zzh3qel5jha3rxh2ha05xqx3q2g5wl04bic6ccn1mh52ai81xp94ef65jzb2h8h5sxm3dm62ym86fmi5f1h4qyg2qtu3vfb1vwf1ivp3vf75typ5igq4h1j3sug3h852viy6hf52poq5q176afa4mpc6c0t4zsh5dit6aom3h8c2e9v2hfp4u5n5caq4m2w4tv33oy81pot3owk3arn2dri4ymj3qto5ix04jr05i5x1nzl5u4a4eg41wbw3nee5fdp4cqe1hvs2w6q1n8v5ct75dx42fdd4ydf5c2e3qsb5zk35vgy5ot86boe1c292pjl2euf6cnk3as13abu3dpd5aku4k6w4j3l4nau3fpm5w7u3c3q3mg71c123buo3rhx5lyh1b0h4ynd5y0x5enb2a5b5mqe3l5e1tl13way3gs73ex34np95mxq2cnh1swr3t1m4eyj6mj75f013rkz4ln24jia4l4z4qr42er95vnb5xff4prp2jqk1gi82ynr1gfz5nk21rsd5umz3jzf4k696b5o4o4k4jal3nht4j1i5xof4ie74f9w5tvn2qoh2jdy3wym1w315c6o3nim1vso4z2g1o373lbz4bqs3tfv5i8g3utu3msl1bra2k464mg92w764wyp5jcj3b923zha2i4x3wbl5trk2n8t3ge74unn2ria4wgi4bds2y066bhh4raq5i563vv82xk44az03ov14ycw5ei44u1b3bv35etp3kcf6fod3eq91awf1eat4giu3vyd2pvh5aaf2hdr1lgw2lsp4l026b7b3ioe4c1m5kxi5yof4obv3r6t1uj61a094yk61rzx3cy26f8v1xor4la71qwe5mxo2opb3psl1aqi5y5w2j4q5vfn3e374fzg5qim6da41oxr5hgc3at35ieg6cq02ioa3lpg4mzo1w7x2aia5v2l5abg5x5o2xcn5toz5tp04z224wlb4pd53zbx3pb93f5l6bke4p7s6dhc5enh4m3p4jmg1k034pni4asy1a4r4deu4hy94g0p5b5p3wqv2r3m6q735ar51drv4ua84loy5eh84wy33jzh2aov6dj25t271kdk2og810gs4uw14hge5qcn6c4d1bai3i5n6epa3dgq5tzx4h3b5a4q1e5a5n932exg5k4l1qpb1f3e4a0j5ula4cc32oym1dis3ns73uz53ewz5q0r1qbo1nd52qzr4oq36e9l2n0w2hr65vse5jsm1ssq3l4u1y2k2r3k3e3u4ibi3kgu1tni5hfj1dva5mno1qbu3px95xpm5q1b4zjw4gqp3r213lpp4bdt4ks22v583bft1il55yco4p5e3rhk5fq95ko15bwc4q7p1ro73lil4mwq3wf61tft3hpt5t3n4oo92b5j2bet3nuy5nea3kdd5ls66f2n4rac4j473iut4uvv2i4v1a8i5k482hpa1mrs6fv41q8u5aqz4ytc1ibc4eft2v953me94o0b4kn03g2j1ai51n511gnm4zur4zsj3v8w4tzm1swn5ih93gen4r6t2ykb5u7i4e813v013n4b1jmi4dcx3at42c6c4mzl5ybi5tcj2w544o135ufc2xs04flp4yqm3o8p3tpu5yft5mql5w6e2yjx4pqn4m482iiv4ohm4a9c6en43wk43p503bpr5gwz1mai5wys4oel1uy84u014ibc1qti4jpy1q412gvd5aip5i0b4zyt4yxd4qt14w4y1c8l3e5u3kqd4uj23k4q4o425o1h3b0w3t641hty5dgm3bjm1b8o4l3p2b1z4yyi5ceh3l3m3ebl4bo84fvq3fup5ot93eax3vhk3cda5c1y3r2a1obx4tzn1d7i3qd33wka3ovz3ihz5iis5vo65tc03fqk1dm24y636mvx4ucu5oht4jff1n8u4xua2ybp2cgf3d4q4gsy4i322psv2ych5lck1xxe5wrs5trg5dp62lnw5kr24utx1a8t4qw56emu2itt4m7y3kqo5ku34n7u1oit1w1t4j264nrp4yh33nzw5zh23vw92hyy1qj11csr2we36mnf4ijh2jdk4kcg1kmv3buh4ovh1mxu4mg83lka4twy5vsb4ofl6cdm2f3k5aqp4tkg5w4e3zot2yak3qkd2pv15mz85gut3avz2q8g3ilq3zw34ckj1qbr4q083zpu5u8f2ydv3rtp4b952f9b2uz94ehg4xsz1bkj6f221tet3f3w4abd3sjf2byh5jsg4op36fsy3twv5d252vto2oa06csq6dh35jq94xkx4tmf4brx2ghg2gvj4wnm5ayf4osf1u653lzs1i903gdt6eru5ops2mpm4cc73ckp1o4d2vvs6ep44bkz4aom1wc61mpa2pl92p534zyr3gqz4og84mlt1mf41xxh3p3g3g0c5dbm4xhk5lny3g8i5g602zas2z7h3kfa4a9u4gj74nwd4ei45yjf2won2f2c3mg83i062wa43hzm3wkc4j7e3dxm3m9f1gzv4clp5a095tg54wkn1njf3ce01tpz6bh03vfa3su12vtn5yp65twj4i745zk82al53bh94djo4oi65m4u1wva3uvx2aod1pqc4n4t5fdi1lcp4ere1ci71ykp2qju1ftj5hk95y3o5q0v6ayn5os12j9l2qm92x6j5ei25izc3u184zek4s1g2wq41nfy6bnt4jai2jb65ahw4uit3bmn4gzx6gxu4gki3ccb4ezq5v7a6dzq4az34ucr4pnt2wtj5amn4ux63t8v1i333r7n5f005nvy3k414aq33tdh3wdz5nib6b8y1v2h5jpt1xge4umn2xrw2vvn3t072vpp1ghv4ydq2dbl3ho95w882g712lk12pwg4ai51o411tsv5al34fk72o4z4a514gwk3ay03own4e5g1lcj1hk34rhy4yoi3prf5z993slz4tmk1au02qwg1bdq5h8b4emt6bec1g9d1qf22r0u1f2o1b9t2c1p1hn43skg4ee06c2y4pg33uw41wdn3mho4yl16cex3b7r4pop5f023d7b1xbb2zft4i8z4oya3otf2xhm5c201zrz4rqk5k8o1tvo6fnr1dwd4zlo1nyx5aad3kqw3nw75ti66e591ywr2xn54cy11yfz5e3a4a7c5ljq5h9r1gi62b1p1kc53kpw1q5k4aml4ibg6e492w8y3kmm2w6o3hdn6cef1u8t4e8y4gj64hbm4g3f4eok2rox1t482xd62fjn5ndb4j771n433ui75e731h1h4mhs3ohf3kdc4edy2wzs5h9s3cth2j341h624jnm6bil3mhc4zw83g904f7v4eh85wkh4ycm4mk82xj02tpi4clz4ko85qaj5dus4xm72uzl1k1l4g951c3e5g104nnr3e641fq84c714b0c3ft31ybg4y2t5dk44dds3ggw5axi3ueo2r9b3ppj1meu4z7o3n8k2jup3p9j3hxe1e063ika5yyf4kc43su34z7h4x2l5hcv5ir11f9g5law3o991yci3g3d3aje2o5d3b7i6af92gvz4qmt3qj02y9q1nw55wg84bzr1k6t5hd03fui1lek5kql5d211iig5ewh2vhq2gh64x6y4mbl2v545ug93hvk3qts3q434nvq3co94uxh2gj44dwb5q161uyf5jbi2il21yt93t6j2zu55buj2xiy2fs91al84cig3cgy4mdq3st64dzy6fcl1m0o3spf1lkk4uu71zky5d9l1zd35t6f1g2o2i1m3khv3o885fi23idp2pov4x112qe43qtz5alm4pli3fts2x4u4o451tkx2q8h1mue4eop2j7e5akk5wtt3h9o3v4x5b6c5boy5hdz5nkg6ajg4dum3whw6b595aan6fo54pmp5i0l2xk95mon3d4y2xib3c2r5mfr2ra62xl24w5a3zm63zm53zhz3ogq4rrq4wxi4asd5txy5u0w4xta3t2v2q9m5lyw4kon3sv22j7d3hmv6g921z6f5a463gnw5k032bgn3ohi3acw3hng4j061owj4fbe1gbt4fmo4g8v2fzc2vx02o1c5unp4o7c4rxe5t905jyo2wzy1tfq1tqf3s786g0v2ei64r953peq3o9f1mq61k6v6gfs6q6y5m393wz71nwl3ard5e3d2woq4gq63iw52h153avh2azr5vsk6ckr4n844eh24cpw5f914k3r4dgn2yer5ayt4cpz4y295tq63bcn3roc5lwm3gjd3k5v4zip4und6exm5qak4u0n5wo41rrw6b2p5hls3pjc1cin3b2w1kmy4ys74f0c1zgi3vqu3uoh1qr35i8b4l7h2aay4jlm3wnr4en45w0f4lxz4cjr4jj72h5i2avi3ezv4j093hkw3uxm4b5d5vcv2vtt3bl92y1n5nin3uvo5anw5nvw4b9k1j4p4io54dkp2jdt1iem4lm05wyq5nr86f7t5a813lnk2xuf5ort1h1q4twd1e1y5lo54anm1e1v4tki4wv64htx1t134euo6gy14civ3dux5knv5hn76gi65vb53f5p2kfh4b3u5nf55mes4w551sv33p7a6frf6eks5afm5z4o3cow5hu16f9g3ds16a6w2g8r2ze15q185cau1s381zge1me43cj44pr54gzf1q545l9i1z6j2ez53unk3qwc3o864j516fyi3cj22viz5ekm3f9y2uy52brb5g455jgd4j1e4ikt5opu4mwc1t7d2viq3ocp3wuv4yay3d7f2vh64foc2ra05fwg1o3c4bi01kll3qtq3cl03ho23vw76h374rlw6dak3p3t3m116fdp4c735ksx6bcy1okl4gqq3sji2x2i1hkj5hu95vom5fdo1uu75iay5nu56ghh4q063apc1re85uey2ha64aaw1tcx3lpj3w0l3s453n5j1rhj5d0r2qp62vqj2zaz2zir4mq15alt5he53atp5w5j3ekw4xas5mwy4mwy2wzf2z1w1d4t4yk03hnb4h3j6g361rhr2r3f6bcr5owh5idp1odi3vw14n6z3qcx4z894pkb2ewp3d9z4c5d1xoz4meq3so63tiw6h7u3u0d1ur94lar4css2a3c1h3a4aqc5l2s5vi66cmr2wf43chs5uc45tca2x6e4gne5ey94ih51mto4qwi5nai4ym43prz2nnp1vij5bvd5swf3pn32pql3ekv3nq95c7n1els4k5m6bq01o2k2aux4x695mts1e9h4ykj1mkd6i3s1zpb5mo82q924u704wph4xy94ith5aph5cy33fat4ly12vti1f0q4wsy3ej13ine3rux2vvu5a3t4qtd5a5s3t7g1xon4gah5flq2hw23aig4hl55wzr2imd3oxz1ndv5yji2hxm3l594jpx1ws54uix2iv94dwk4qvp2c1b5cw82r6n4cws2d3z2oc94ehz1ett1fdq2avo4r0a1zzz3moe4mmp5muc5zh53zqi6f086elo6dif3mf55qas3fu53rv94jne5urj5oxk4y3y5hki4tyb2glm2xnb3tt06gmq4i5p1f923psd5hcy1q6n4tmn1tmn2gg03zep1c884fea5nwb1ppc5myx4ci31z6d4kww4ixu1leg3a5y4bo35cyi5uzj4mw05j185ml32bmk1e662brc2fwy5oxm1bn14qlv4qip3ms25wxf5yib3ig74pgb4p732y4s5zh44ch25tex3b4f3poa4zyx4m0y2ot15e911yc53iqi2xpc1o2s1pmu4l584mx15am42hs24yne1ctt3l5c2zm11lxf2f1b4zcs4zw52oh05n2z3f192obf6f9t2f016euc5vee4oyo5moq3ft46cbg5wuu5f5b4xs21ype4rwl4hpi4e341yc15jy02fxr5e1m5oq61nhz3pjt5jzi4elf4fxy6dpz5a6a2waj2fqt3mxy1y916biv4j1k3zmi5xjm2fv55db33ryj3b953i5r2ajl6c993bx55ave3muz2ye92rf22j2i5g0q4yuw2r3g4cwf3t3h5ajz2bgr4l9i4igk6cz44qfp5ty84odm3hs84ele5zia2pvj5w5k4m5l3wz84egh5w7j4jfw6eda5tpb5m5d4o713kag4u936eed4zam2jbp4z3v2pu04zzd4f144h4d1pxh2hwp1u9e4wko5kqx1tog4yqu2yi02xf04uof4io74ds15diq3ti54x8u2lp83avm3kqm4zph2wou4jyu3ip85ti34cku3h783vdb3chd4i5h5i2r3tyv4uwk5j6a3lk05k132hj43bfu4ajk3n453te53ujb5v9p2bzz3a6t2y6o3b281hvl5a2i4mx94g8y4dko3kdb1lf94qmp5q103hqr4d2d3w324ksp6f8b3h6z5k0h3h2n5ke05w4w5mxr5igl2h9p4iuu4d8a3dvp1lox3ao44h384bdb4j1p1o4b4mro5eel2ay33e8n6g8m2pyy4m0z2mas4ks34p726ccx3ttn4jsr6aqq6em65o3r4rqz4hkk4qll2q6f5he14fe92wu62pj71bty1ule6dry5ezg5h173s7b4x483atw1kug2hdu3odu3l9m1d1p2ihj5mgk2n1g6hk61mq54kp51yyr5al41pzj6axl2z4b5mym4gv82cni4xub6cjh3ig14m2r1tt15ime5oei6d6u1utj1dfo3ixj5anu2ogz5bwb5vad2x9e6epz4yv22jdh1w134eos4x1f4gao5c8k4k5n3pj15hz51x7a1h9z6gjm3ipe3fuj4m3d5g114asj5xig4ybs5gmi3d043dv12fie4twt3ary4anb6hmg4n9c2lsk2ksb5mwd1gfw5gja3u3z2f7o3mzc5w9g5yz24nmq2y2k5lz54qz71bug4zmf1o8b5jf32qft5jop4jaj3s9i6cvy3oaf4hlw5ta65mae2yg25m2v4zxy1g9r3iqu5i9y3pch5kkt2fqo5mn13e3b4jlj4tq34zga4jlg1pf75ewd4dhf4ywa5fxr4e1k2zmd4jyv1fkg2lwi6iik3zxe6dgx2vx13hav3pkn1trd3u102a0c3ly22xn61irs2ntf3rum6iin5hzx1urw2xb74umr5apr5ngt3q713og74oeg4tte2ow63sff3eu72zju5tx53v8t1nqc3t2c4afh3vhu2d1x2h2h5nvz4qy83w2s4w9h4r6v5esq5v5d3rbu3d514q074jrv2in63bki5ov96ayd4zyc4ybm4xip3ibu5kde1br51lan1gwq3ggv3cke4av04qpd4urk4o043d4z4uct5uwj4b8y5nvc6f235w0e4m842hdq5c6p2amt2rgu4ax96g9n6hu26cho3v7d5iz92vev3dej2hxq4mvx2c3l5c291we26f9u1m6p2f802ooz4py24zcw5kx74m134dhp4kz65ypw2zdn1qf52i4w2xu31wbn5lt93zmv4efs7cpa2i724rpo2h134obo3f886g472y6d3o575a0c2fl65mja5jal3aqa3g9l5g225znp1hi41y2a6ay53cf83f5k1a0q3et74eky6bvb5u941m1b3ryv2peh3vw25e1e3i515fb01rtl2i4p1a9m6au54jyt4k3k2c5o2qu64hwr6bqk4bqh5cs64dea4x3r4iid6gzm2y2n3fuk2ypi1b3l4zsq4o442e1w3rdo4zme4zz24ucs3sl06ey95arg3p3r6an13eor2uue1n4h3gk23oot5i5z3hv32hzi5yc21g483bxg5wbq4a1w5q0q4axm6g914q0l1d8e1bb01lpg1gmy6gin5yy42pvv6ht85j822x5o3orn2nmb1pk03rik4lkd1v2n4ufl6ahi5bsk3uza2w8f4nka6bef5abw6bkh5l302clx4an14ufz5nk61syi3zsy5ul53irx5ux44r5n4bdc5fut3e2m3lgp2ivz1akv2ydi4i113zxv4m3e4kwg4g2w3o956gu42doo5yun3n5e3mqf2y5k2vnm3g0g1qfs4o7b3ty04uil3st53f366fqo4pkw5j6m4xbo1hxk6ghj1h8y2pq95em31rlp1yvf4cqg3srb6fmk4o6e5xmv4agq2j3q1ke91mfd1a5h4b1j4i0f3up22ay55mqx3lpu3bmq5wfw4j5b5alp5ee84qj01ka73k3h4np23bwj5osl5all4jze3b3x3sm02xa43t3v3t1n4yp84bc55f084qw65ofv2bdl4y834y4j2prj6cfc5eth1oky2ban4blb3f382uy36fdq4qmx4bo55wh56cvv2oph3owb1xlx2cf94av42wxv5v8p4eqj4aoc5jk34xtx2aoj1v7a3lzv3bum3fxw4qhc1b6j3f804or06dq55lsx4bdd4x8v4od93vye2yix1i7i4eoy2k4i2bv44z0f5dp74xiq3d205llo2ymd4hn25n314ffs4b5b5jf14i732pqb2i191cbx1gsz5ws34h3q5a5q4uvy4guj1i7g3c8a4ll34pp05hk14rux3coj3d6p1ndj1o793nsh5hl92e275iui4og53wdd1lnm3igb4x244tsx2gmk5ox51bqn4e8w5xyf4uco1eas2b7f4m5u5evk3ipu4p5d2fsa4ay54bcp5thj3tam4jsc3ug25e7n1ofz3uo45clm3gr22m0u6f7q3sdg1sme3g2i1oyt3h3c1xff4oc63b3c1xa51fe31g325olb5a852oz24d8i5swh1y2d1inc4obz1c7f2clh1qkn2etm4i5c3vd71p285j7s1y2j1aht4iq62pe24f3c4ih71hkk4puj3o1g4w9i3qrj1qj64azg4joo6dxx4sga1gja5k4j4yef1sbg3s005fcw4txe4mr51bxo5xxf5jic4abh3nzx5edl3pcf3k983qqu1hgj2qch2yim4dtt4l093f074hki4cl62z5o4e7r5amd1c1v1ym11s642w6t3tl51w1y4eoh5i584z5w1u2y6hu13wav1nxy3n4c5c912kzu5kre2jkk4hkp4y2y4w544bnu3lp73bla1gni2idw2xy92q6b3uxd5o9p3ao13v2o1i005ewj2rgp2xln6ma54d2w6eww4lkq4o7a5m4k5g3n1wm14fzj2nyr2mc12qky6eh25v1y4glw3arb4gq42vin4rss3q7j2h4g2x2c1gt41fo01ftk4kby1ch85fnu3sv72vvo5uah3k972wpa1a4h5lhg6eeh4mse3nnv6eq45f1l3q0z3elm2uzd3p2e1r0p1j162qhz5h0b4nyt5ij74l2l1afl5vd04i101opi2ves5tyn3gf23nuo5w2p4uv93sut2f3f1dmb3wd24xm84kp41hy74xbd5m6h1g054zh35d0c2e7l3kba5nhh2pax1p0y2l7u3wns5u4d3axk4qpl5jt22rk75lss3sni5aaa5wfm4pb13oe45m635xg53lle2yac4odk2x952ig02zdl4ay62c1a1nny1nw42fj03kah4db71bxq3ifl5f9e4p2t4exh6d2o5t2b6eee2oi03lpl4tk31o6i6eux2ojj3pyy4edz3jy03r5t4xdo3qo94u2w5nme6hdn4mre4ryg5ez03c145kzi6bix3uug5ldm1o2v4llx3lw02op94nhc5wqj5wi14e206fjf2x2m5l983qsd5lcj5t231adl2wa84q9y2rkg4gid3f702xk65t8e4lxb2xp23juk5uf03l1s6evr1lag1awi6ej41pmx4kln3wgg5g615n694o9v3kqc1him3cd02kbs1moq2f102zb02d414bdh1ebz5lcf5u134qwk4cd84d851tvr4l6s3pd41hq55tiu1o446g222ckm4btk2cli6cb53o0u5u4x4lp65afk2o3p1zpc3qo33d1z2z3h1hms5ox65fpp3f3d5t785hg53mxe4i7l1tuf5lmk3nu95om92qi33l5b4v0i2nv72wkt4ndu1aq13ddq1vyj5ods1b8n4xhl4jft3n7o4og65j9z5ufr4qjm3g4g5jox2std4uvx2yb93qaa5mwo2onz2hiw1xnz2agv4qgg5x282dw72ohk4oue1o4a6ds03t5u3ij14klv3lgl2wey1qk34i0d1rti3clp4f8h4qwj1bmb5jar5a5z5ofu2yiu2z5t5emm4ibm5lzh4xh23t092p951fmb1gj53s725ia54kp61s9t2fhy4del3ao54xii5cp93vb43sha5el22uup6bfe4jv63e8u3ubd1tys4p105ekj1d5j4bpi3n233amb4gue4n8q1o0d4d1j1a9q2vtq1h1d5uw56bfp3tfu5xyz2q1l4m7j3m8u5kbf3btl4ctj1koj2ajb3unz2xgs4pd95g1c5w195vqw5yc84ufd1w834qdk1tyn6buv4amw3dnd1d7j1nzv4ryl2f6j6bbx5lgp6ay31fwv2qg03mg43qmk4dma2r3c1d6s5dsx1tg56do35n7v1g5f1c5q1lb64pv73ii54rab4eke2w105i861uho5vsf3g082zxg4btl3hb45j4y5lgt6boy5kva5mka5wa82i0e3ptg5vp94mw23djf6b7d5t1a5hrw5e2o4xuc3vg16c4g2csn3q324q9m3vry3fv75lhh3fh52qry4f9g4c8r4m6p4riu3dp32r3i3bwk6ew34bs54g3e2wvz3wc54nb65xmr4ps54dvi3uvm5os72xix5alw3iaw2xnp6dvo1cgl4xv35dya3c792e9a6dil4caf4tpw5fov5n3w5ttv6f3b5cas5aqg3dz21xhy3t015th44i804q3t2ceq4yff3bti5vll4hy46g3y4ykn5lu25wg73fnu6g846ap66hpg1c3x5if45wgp3d6q2wer2qrq4cfl3uib6fgf5tx33plu1zzl6db45tpg3k8o2fxv3c2u1w8l1di83udh4cu15gvl5nvx1bt66d9x1vjb6b312qo13daz1v0l5nuu2qtb5ewy4i9u4afj5hzn2ohq4eqc3p8h5y531kat4kwo2hiz2cmf4bgx4hys4lww3k393rdq4ega5fsl3ehw5gnk5n8b6h291dy43nu65dxu5jf82qd95zaj1oif2v8w1ywi5uiq1xr84yvz2y821pkx2qbw1ebg3a4p3ful4d625qb26bgx1ela5j592q636cmj2p9a5nwk3w544rrg2l1r2gsu2wva2vpn1qji4gts6gnw4afg5ty94ps73r2f3qak4dgg5f671kak4mc94dpu4u5o3h062b4m4q994dgb4hw25uvc1yxd4cix4ehm5his2ihq4kmd5cin5v7i3itz3il53brn1h4w2ilp6bnk1me35fh71rgk3iub3p4q1njt1ya42x6i3e814yl01at63pr05wf34uzh5f2k4j934dwg5ti24pcs3qcj4qjo4dpf4qer2kp84o2p4pd62op36got2weq4lh75l976bed5o1e4ezt5y8w1err4rj72yol5t682ltx5g171mxl4c7t3uvu5a3r4yuz3nf92fix3pgu4kn13mi35dpw3e5a1y1z5j8i4e5d3cd86ccl4x9r3rtx2zmj1xp66cks3fw34znx4nyj1q1g2ews5o5m4w4v2w1d5d1j5fbe3ipq2qk52ydj3gv61mxo5l9h3odk6cze6c982wmx3qa25oax6gnm3q6z2oqv5exn3s535lzg3mo56drz5nn54x1q2mow3ow34ebw4a4c6ema2h6q2fjm5uez6et86ep91avd2q804nj34mdr5ely5dri1v2r1hk45xfj4z0q4heg5h3q2buv4l7d3nb51g9b3oay4aj41bxr2w9h2iws3oy13qpo2hog3rl81zgb1a4w3vvz5ia46f1n1x703q5u4do42pcp5m774a501elb1rri2ydm3ldp4k9g2ptz3uo62qwd5fdz6fiv1hqh5q125anv5k5e5aer1jys2zu32oiq5lwn1i9o1npv4piq2w0j6c5f1w8m5gjd5yql1m834djv3ns93zn14eg73u4r6hu04awq4l6q1ad83d9k5ucj3piz3ekt1g9a3m2w5q1c1mv06emh1ttv5u121lhf1w1p2i4t4z684gqr3uqp1rhq3oxc4mc63adt3ivi3r8u1udt1o364ou36apz5gmp2l842gg93o643uo94qht6f6r3hy71nox5u6v3ans1mdl3d2e2fsv5t2m3p794je73gta4q9z6f551gu15y6k3ert3ant5a3h3zdv3o1d6ar42ym43s3v3fk13pbb3r6c1xh85lh45q0w2psu5gty2qi02nn75vb64b8o1zp85uqv4pci5f5z4rj46dh43lce4ea24y6m5d3p1gsf4l7l1tkt3a295ljj4gpk3ayc3qkv3ern3zhf1f4y6bgg5uz02znt5du41utn5ayy1lzo1gym5k8s3kb33ijy5oa25wio1yei4hlh2eg85tkd1kpm3tpr3mt93tcy4qxr3uyt3o9l5ejv6ekn2fky5vp04rxa2xpa1kav3ecn5vlh4lko2g834m5r5iql5g533fhe2xj73u783zt34hkn4h584f1l5q0t2jkh5w133r881yvz4qmq5aag1b6m4i476d5e6c911z954ca64ysl4gbz1aj71wcq3m965t926gjl4yxo5l2m4wov3l2y5v5y3a3y2gmx2fo42h5j2r052qtt4jn45npf1gt54jfd2qhr2sfp3rx54e4l4mao1zkl3syr3jzj5h9q5one4io63lp22i4j3rlp5eta4yth3r243gsg2of45inh3ed03zlr5llp6esj5c8m3dkf4z6h4x6o2j471usk5w8j4x1p1xb71lqe4apr5khm2ga22ly04zro4e264g164uvw1f5l4ipn4hwt4g901kds4bck5k6s5eqp1vwn4uye4gtq6fe16gjj3hb82zdm5alz3eyg4lkk4os21j4q4o365dtm2wgi6faf1mx13lfn2i1r3hzy1a4k4zl41dub3qi33i903qgy6gfy1o2u4xyn3rk76atv2wu74tnw2uwo1z6p3p8o3my13s3q5w0l4tw86b8u5jg12azm4qw35ntk5jq83gcq2zcs2pvw1o0n1ph03nu55loh1t084m7b1qpl4ge54w9s5fat5l2w5nx22gst2pix5myn3ump2xoi4r7m5ful1kf62on35wa95tw31q4k6fu45umx2bdy4ezy4crj4pyx5t972cet1fao1n462ooh3dgo4io41xjd1q723mag6euv4g5f4dgm5o1c3ken4d2r5fnq4z7f2o3z4xgz4i2z6g155ypp2x095lt63k5g2xej1uyh4tln4mrw3c103sdi4tw63pa43q4k5l3a3b9g4ohp3nq35vfj4rqi4x7k2q8s1ca85a3x4wf65oh42qu35dq86ffs4loq4prb5vwk2yhw5eob5dgj2i4d5wlo5lo65aln3p5l4q1y6c4u1gi72jkt4yv13ctj4qfr4wmy5c843ie35mnn3l8v6eij1o2n4nmv5ok64yab2vnf3r0w2uyq5j191y2c3nth5ni04tpk1vyq4txs2wgs5gv21b3g3kad6hgz3dng4u7q5fnd2c5x5ho62aqu1ke65g5f3wff3m364bb43ai83ee25u144xe14ggz4av53bgc5i4v3g0d4bkj2aei4hup4yv94uwf2ovy2oo84dlj2v831ct85qan4nwc4msc4iti3guz6i8l2yof1oyn3qti5nf65n7x3t0t3oyw4ab93aw02x2l2lkk3oyq6c282ofv1b584cpt4em71t5a4xyf3duy4xh61j153b7j2isw3eqs3tkz3dgl3qw56df42jjb5auy2rcu5mqy2aoe1d8f1kl54zsg3e0p3su65tz34hco3i6c2ow12yjw4nue1uyd4hod3oik2viv4wtu4gih1b9s5i404zb65fns4x6h5hg95naw1h371uj03e9i3i5z1v2v5wb33lpt3k4d3nhi1cbr5uis3f685nk33okv3krr4gnf3zyf3ivg5d3n4rs05oxn1owd1w7h5o4s3hrf2r3h1yp95oyd4iif4uvb1b9j2bgd6giu5eek3tnh3gp03bxs2ay15cap3ta03mkf4uyf4zx65a3n3hek6b5r1fbm5wou3g762rkf5j865lav2rkn3jzo3kr52vo44lzr2srt4wbg1vyz3ebi2qbx3gbb3vnt3erd1o341lbk6czi4d1c1k1p2bmv1jlr5hx62igw4o0r2isv3kr84k3m5xiw2z5s2w974u034p4d1pwp5j273w5e5a3s1zz34y5i4rx94ty76g4z4j3e1s3k6ajh2wei5v5o4p454nbl4rxd1cp61r5h4nnw4cga3kb74phw3zpq4b3c1wv75hja1mfi3jzk1hsh6aro3vyf2v7d4k665eeq5mos3ska4bg14ql84lgg4anw6gr72x7s4ie41p054zbi5c6v3qzv5etq1nhw2xx41uys3zsq4h754d0w4pml3gyn2fm54r935usq4e3b2hwi3kl82vr43o0e3dab5h8g4ynb1kr34w9d4msl5k8v5ix15zaf6cve4h853d5m3v785uox5d1u4fcm2zz14i1r5hkm4y8c1fkn5he23n3g3g5v2evl3k3j1utr3ixg4u444ahs1o2y3fcf5dde3bgm2nxd4yhq4k195y7w3v3m4ph41nja5i233rsv5n174bt52ojg5x726eq73ehx1a5v6clv3qcs5cy93bgp3nf74dmn2dxs4msk2wmu4hws5c2a3lco4x3u5c7a1pa95he73m671j7z3s5y3oe04kql5l8y5cks4cc52rcb3bi13jzc2qzx4u732an52uvm6g2n1dzj6b975y6d1qvu4ymx1yej6f3d5tg72w1i3dv51vyw3sw94qz38a3h3o3j5gn94b7j2i4u3m8q2fu84hfp1swi2vd03pz12jo93q4c4bzo4tyl6fuj2x7c3hg13pty5f3i4q9o3e1r4j784ucv6h383wtk4lno2h653s4q3lp04ajo5maj3d7d4xe06hpw4p0b5fsb4f6u5h0g2zdk6hoy6bib3rpv1kel4v245k1i4j4v3kai3c9e2v595cs55jqb6as85dw21mq14gw14gj96e2n4qlu5jog4iu13tyq3r2b5alr5c4s3pa82qq74qn92uwd1yye1oir1gpy6ert3d7z6dq84lsj2wxm3pj23nwb3qxc4hwo3afk2rk86acb6g851kna4pvx5hex3jqa5xms4an23lcu3rdh2r3y4w7t6few4cd42gg24ga36anl1yyy3r164al44uru2ovv4ya84re33bgq5lpr5fap5cei3v5q1maw4p4f4jx94xqa3ghe3fci1zfp2l124lil6eq25vdv6b0v4l0i4zsl5yu91p041rnt2chm1nhx3ckb2vot5n1p2jke5ztn4j823hxb3qvu1hk54pyo3atl3jzi4ad34b6r3g8o4kc27upj5eyz6do55wfj2j4a3kmx5oy34o552qi54jfs4h3g2y683fv23ioc5jyp2gde4mm84jjm5ccl5umy4n7e4f643p9h4hz54kin6cqf3feg3aaq3sl11uxb4oee4i7d5ll54qlk3s9y3t3g2p3b2jbj2x8i4ui33po15ji63u904lts4xrq4jzr5nkb1km32qnx3myg2va74ymh4nms5ar72h3e4lp02ay95trs4fse6cdg6ful4x8n4w4x5m294ocx3sov4fxp3ex25uwl4wpn3bi05nwh1vik4uj95tg45hrx3wz61mm75v375eol4egi5n213vhe3cj34w9q2qtg4z933jqb5f3c5ll94zts5aei1o9d2iw95b5g1g543v5p2yk91ez94c6x2g241m9n5f601vzq1rt95jq53ha62yj94nra2h9t6afi3el84kni5v794fxf3ncg4x3s1dif4aa74d1b5av02clm4l101exv2ltv6g1v3rwh5yfs5xkm5mjb2i032v0z3udm3i3b1h1b6esa4ai85ak35j205jjm3wto1std1jjt4kxb1jdj2chw3ll85j795adq4r745n533ljg2lsr3rk91add5ja05x025cc23u9c5d121o6q1xn05f204lgh5etr3mj54km24f9u6el51hmr5n9k3are1lv85n994gly1sh94uns4cpu2or42rkd4psq5wcm5vsc4nl14um94wa93fxv2obj2ohm4zw35jao6htz3n2p5dda2vwy4ge25d7e4wx43sgv5w124gmc4dij1r5g4r3w5hn84fk65ggl2ks91tq42qu24oyk1my86mv33kqs3gz93eta1uv52bok1b425mlw5d294qr51r6n6f6u4pio6cee3mp14pz86fgy5moe5yfz5zwh4kb92wmw1nax1o4n2znu5gvp3ma33k155qae1v482psx4d8e1m5d2v2c2ql53h0y3wpn2qa81rs45tgy2b7d4pl62w8j3tdz2wxj5g2b4nrk3gwv1kne3kqe5khg4uiu4kyh4e932qg21a4m4byi5ngz4c1c6fam5lgq2hb34c1h3ms92pnx4qmw1lzq3aid3psb5w6r4c4e4jxw5ngr1utz3r7o3umq3hw11tkc1abt3mbp3i9g1rwq4iz06dh24rx74kwf2cn83bar1cny1npz2bys4y6p4y6s5q0s2uxx6eaa5cs24c1e4mgv2wxf5q1e5o833r4o6fyk1x8s5b254f394tk55nhp4lov1kui3art4d2v1bnv4kov6cyc4fkk6hvj2j4z2p3c1f0s3dy65lz73mww1hvk1x762aez1bio1lhe3k482krd4bbg5otc3kqp4esi2rku2kpl1erb2xx52fl24a4v1lqd1lfo3hf63bm81a993zly6cwn3d8y5icz1hgi4qgf6fug3tn86f3g5kq53tz21xws5uov2o9j3coh3h981mes3ot36f1x5gs92hha1pfy4j3j4rn14ze63zpt4f9y4lbu2nno5v422fyv4j8m6hjk4ha53tu71izh3o9d6g4m2r2b2xc01g303anq5uv54ty82vew3br91df83fgc1utt6cd86f4w3l8x4fe65adt5nzq6htt5k0t3pn14ryc4nga4crc4xcu3f3c3obx6agg6cq53w2r3dsu3zs04wkv3w071ntk4dk83kgq4anv4ery4jzd3tjh4jwk4hyi4kne3u9q5ih22h024c6u1i8z4bid3lmp5ohj4j815dey5k8n1pz51shd3hhm5n0f5kh33nba4u5s2ndo3shc3vid1ik41al71fq72x4r4kz36cen3s8l2aoc2xh52p934qfg5huy3ebo1agm1fv94jnj4c721vfn4xg33hl52xah5n583mof3r225o451utm3p8e1kl35o5h5lpk2zdx6q743miy5bpe2vta1bnq6f904myh5llm4poj1q6s1jws5xmp4ahv4e4n4qgi4o753ogp3dk14bdf2ybs4ght1e5j1veb4wrq5cqu1ow75nsp2wtx2rqu5kpl3g193gy74bhi3rjm3f3v4h424y161o3g1utc3wzu6b5q1u2r3sx91nju3drp6azk3r9d4awi1ce55vd25kzq2bal1y2f2xxt5hlp2y8c5auu1bwa6gbe2zv23f7b1e4h6arn3ryw6fr05wbz1c8v5kau1v414oew5fbo3l9h5hi73igg4hy05enf1cwc5yjo2e92186l6epy3qk06cq42jkq3gb25xmt2ybu3arz2o5k5c132amv4std4gfm2fm24pv03qx91hnn3bl25dhp6c7i5pzn5ur91pye3upf3ooz3zcl2vkm2jdl2uyi1usi1ezq4qz03g5d3ry82vnt5ehy1mqj5gs45xg43h591bv71br61mns2ybk1bcj3ktr1e021ykr5vja3r5j5edu3kga6b5t5f745qaq1jpl5hmi3mjl1eei4n8e1hrn2o4s1agw4yz54wn13tc52pjb6ea15epy3vc42i0g3ah81ogg1onh1tmb6bau4ad61a3e4drn1aw15fl12h2j4prg4ibe2yem3fql5zwf1x0n3pi56ehh1cps5akl3g2t3vsx4dhl1hsg3vhv3ro45myl4lyw3sl53e924o913ipa1imx1u715dx34hvi1h5v3p7b5v8o2rg55nx94i8x4rcf4yrd4bcn4d095f8y5mwp3n763gba4lyn1unl3e6v4dce3rsr1nlp5dxg3rcd2cji5zwi3o9a2x2k4n5d5l4f5gx75yqo4gzt3tki5dd05ivt5mnr3asl2oc03l3n5izf1i6v2y564x0f2h4k3ivh4yy61drj3hku3kfn6gmd2c3k1w5v5oha4myq3new1o5c4k5y5kbi5of05dhs1y193hky5nka1wax6h9b3i7i4b6c1h3h5xw64jql4cra3d4l2nwn2zyb3rm93q6s3g4i3zqt4bbe3olf6gxa5h4j4ljh4a4f4nw52vi53eqy4tpp1pi54bt33kiv1pb84xyc1zd22vur2k2r5j1x3pfp6g373nsq6eq82wi61bxl5eci5jrq5ehr4qz11nmk5zkb4f655a7b5sym3wti1j1a4nwk5l8t5k0f1mqh1h3b1wxz3tt45k0x2ez75wbp4ddl2ygu3e7a1aqj5m7s2odd4eon3fq73vf91pxm4umt4rlt4f8j5dp91ung4r5w5ais4btu4hyb3nyx3nif5hmk2qyk3tz43qxm6isd6g975ccm5u0z2wbd3aav5vzu2hai6evn2yga1p175fus5elw4azt6ea21xbo2yhy4u0m6b3e5hff3iu81dqx4o0v5t1u4gs62xei6gn12pze2j874hy13udn5nmg2pgz1wdq4er12l6j4cmo4gbd3itu5a7j3su43r6g5ea76eiq5qb14o613grj4xjs2x853b663le65t193itc5ett2esm3dc23p2k3u7s3c6w4fcr2clo3d0e2jqi1ekb4ovz3soq1hef5os04htp4tk24j224etz3gus3s764pyv3c491ktt2yz31xnx1elc5i246eif5t9z2qt55h1e5ekh5vdw3fbr2za05wej2yel4anx1rtf1r5y1pzo2ydw5kam5i135exw2xyr3qs12x9f2np85ci71m7y1fcx5ok31hp03l794jq84bhn1i9p4hyh1jil5f2s1bwn1xh75kbg4bg63qfy4ycu3lxk4w574kxl5mk96er42rcw4jpc6h1u3iae3fnm3mxr3c2o5eva4kbi3ogx5owa6bmr4mgb5ka92bza3sad4wj54o1d4pnc4mzf1f9e4whl2imb4llk4ih61vjd3stj3usn5tnt4i4e4hg75dxe1hc93dcc3d275azf5c5h4m7x1ysg5nve4dcy2qrh1r9l3l0k4iuv5j315ulg2wc32jxr4qwx4joe4djh3sm14prd5etn1ihy3ut54gjc5c1x2oxy5can5hz94uxq3nzi4hfz4mn31jif1svh4zsa5y245f9b4mka5wf74o0y5w8h1t1s5w7i4o2e3g584jmu3dg85u7o5owt2oic3mt75ka32wgj1orw1vea1j014yec6b7c5wg92fv91e553cfs5nhy4x6s5ak04q1w4o5b1b322fzk2p3g1h243qfd4xu03pe25ow14uyg3du84cby1mtr3bug4uj14omj2y581onz3esj1y2b1zyj1fig3cd72hf82v3u1o4f5w0q1ql73kv22wez2loz4zg65f4l4mo43mam2h443que4y325cwa5hyr4mnp3wix5tw54dem5di13zlq6en54ogv2r6y4k8o6c7w6eqv3dx45qa72qlm4tn45vm64x5r3k232q542pe14k2y4rfc6hqy4ie32qbq5o077std4mm73axz1a855etb4ylj2vpe2qln5zfi5wbk4bty1nvs5ftq3dyo2c9t2h6b5nz45ar41xfv6g6z4e1n2q2y2zwz2ozr3fei2xe43nin4py14j524mrf1ngw1m7q4m8t4qhp1my35fgk2ff25qat3chf4kox2nsx5v1b1det4cq02iwx4isi4bcg1pro4ebv2jh54mm64b824m5m4pp33v314yt73vp43imy1rbo4b1c2w7y1k9q4erq5tzh2a3x5f615orj3efr5g4o3el15lkr1mn95wdw4oym2iko1h395ddd5nu14qz41o5p4i9c3wmc4ajl4zud3kig3wde6fdu4psb4bw21hk11pph3wut2ate3nw95ceo1g2m1o3i5ald2hjb2cvd5za14cnh4pnw4uwl5c1w1m0n2nsj4imz4x3k4zgk3pvu2fah6ex06gz91ke83tkw2xfj4bo94cqf5sy23fh75u4f1k271msn5ow85ekx4re21dar6iil1bmm3tsk3tzm3ttz4ibd4zx52c4w1qf42xgo3bm62zfp2uyw3h8b4acx3ouh4zy11c1u3btc1azl4ivd1o4i5evb5dpx4k9y3wtm6mxe5ygf4mpe1o2q3ru14qtb3qw64yb52hzl1b5i1dbb4gj36bfw5y5n5jdi1kv54der2xc43s3r5lso5cu41ysi1n2v4jje5akw5f3z6dl95wgd3muk3uw91o321jq32zpk3hk12f1a2haw4psx4i545d3s5m562bkz5dxt1qw74abu2ggb5fjw4k5p5als2xjg5eqy4g2j2a4g3hf85em94ztl2g1q4phv2ylq5tdb6dh75kz03rz32vww5t4b5xs85j7g1f4f5mev5cgd3vrw5t8j2o484cgj4cts4cbt5ofw3q2m4ce22qqs2j754yw75wip6afl6b162cgu6exi3mt84o241z343fvg1w6j3py05nkc1os53t702nwl6dq41n3z4rme5z951tx74yc83t0m4e5w4f1s1hvr1xzx3fty6au94eu04d1a2p7a4z2k5ap71sqb3wt53eqb4o3c1rgl3r7q2ay85enm2ha75ak56dug3wgw6bfn2fx84rxc6bny6h365ugm5trj5xpo1jmf3ugc4jhz3p441zp51v2o5tbe1o2r4wsk5vdk3rni3kc34mi34pb25euk5ukk2k2g4a4q3m6q3btj4gtv5u0g4zh43v2p3kqt4im01ni13wp03vi74tkn6bg31o1s5d3l2qc65lp62br65ku65d3c5ny35hjb4txc3waw5b1s4trz2pwc3nu44x3i3djk3qw73ivx6b8j1y0x1ros4rwj6bto3ztc1jlx5h133l0v4ycn5qam4ke13wv14mep5tzc1bil4fl24u6r4k6i4g2r4pg92hzn3r8v5d9k4gg73d9n6cct2c931uxa3nfk5f272w6n3k8d4pl44b9z4uiy5fl42bbb3b501qon6ce81ydk4jv82bw71li24qag3hyg2qtr2cen4k3n2fes5kat1dzp3gcu4nbn4ctk1okx1nzq5fb14r5v4b7n4det2xm23exe1jje4wup3sjt6h8s6bx65tqf3lpk3h1x4ps13c722dua4w975diu2cbs4zy44alx1y6b1tnj2vo74qye4no95ct14elb5sz24u0x4ztq2nnd1xom4u0a4abj3uh41pop3hv53zll4rak5u7m5tuo5ur14iqu3kac1t7r4lqg4um15mwa3djp4zeb3r914o774r5t4ijq4mxa3d0b5ld83hdz4bxn3vb55q0j3rx71k9s6cjy4zjj5i3y2wos1bbz4rx54nzm1m5c4djs5ect5ejw4fvr5vtb6f201u9x1zea2zzu3rxp2z3z1oeb1gux4g8r1hk21g4k5dfp5vc44g554o7d1nc36cdp4gu95gvn3l8s4bis4lwi2baj5wik5a7i4pnq2xde6e4u1b383wzn5nn04fl13q6k6eab3s682dq71yw74x8p5vgo2o9k4yo64lv15ose4ogt5e8a4k762pr91z3j2g722l1b4gdy1lq26g0q6cv85tri1g7q1o4g4cg82ohl1v2u4b833wyj4hrd4kfq1no65lax3egk3f7g4deh5tmp4rad3d785l723avj4rg04qev5nt45svk2w083lxo3ljj4kif2jdo1v0o1k3n1rgj4zt86dub1zdp187l6dkb3n6k1tnk2h2g4mjq4a9i4pre2gni3bgb4ddm2p991mwt5nhl6b4w3sou3sm25qik1loq4yqh5mi74ynl2f9v1qbn2r2m3uod2w0z4ewo1fsy1tmm3va46b0y2adu5dtj3k3a1sm23ozs3o8g5g424h3a2fwp6fbw5tzw1xkk3tdu3efj3as22ity4zwy2nmy4amy5kad3qtv3ncq3p586h1i5x134d1d3zev6aum1ftm4dsu4hla2qoe5em53u0p3dx24kn24ce13np93t2w4b7r5o9q1rth3eq73i0s2pgl2yj82z6w3v9b6fs01dhi4hdp5svz4mz51a1c4p0n3n7s2aow1j194k3o1m7i3s9z1igb4o9s5xyx4mex5jy34jht3hxc2c3i4itp2fl54b123o6m2vd43tib5yj81aze4yad3w375e8z3pz42p4y2xda3n4l1i1e1tbz2bxu1g6r4h5e3fuz1f2p1b515lm65gx64wn03h213vd91x394bjc6d5g3nnu3d323l9l5i3w4kqo5w382p2i4ohk5l2i4jlh4whh3u6i2khh4gu61snk1ogu2p0d1zeo1iq14knb3lrh5a5r5iok5t6p4dx92a0t1c5x1qxw3d833pwh5g464wy61yw21bm64yhm1tka3qpp4g191pdz4fnz5mby3zt11y3v3tv42qmd2phb1bzf1m2r6g463hvj3mhl4w9c4imq5k4i3abt3vuc4oyt5qb35yv54n1b1pip5iu83zke5f1z4qvx4zlz4qfs5ai04op23tfn5cnm6dge1htg3rey1o6r3w5n4l524b765qar4nj92kaw4ezz3hkt5e1b3ufa4btx5mgj2ha25cst5ea55kgn3jq71qy24fpk3hq51at51hge5ty14b3d1lyb5mrd4zt44ovg4pp72w5i6ced4elg5j713i6o4mx54pnm2g0g1x814wkp4kxm1wht6q3q4gee2f702wd16aah4rfm2wvt3dx35t4v1owh4k7o4z7n5lla5ehw3jsi1ohr4k3h5y8y1pu82mg53l5f3tfk1t313t084iho3i915fdg5ntq5wa42iqg5tol4tz22d1o5ene4mc26ax44aoi1u3r4ngq3src5zzw1sw26g2m5fwa2q7m1xn25g6u1puq5ha93s563ckt2jaj2qlb1l6y4tzq5u9d4nzb3ccc3isj5kbr3u925duw3ijh1uti5tw22hd14wuy1riw3u8n6flg2qzk5w6o2v2q6e864e0w5jf45a8y2nq61tsy1rek2xht2gtk4kom6en63zmz3efs4whr5j1v1ld84o375qa54c9w2zdz1l5q3kek2olb4dru2h425jnn1w0x6chh3av93uzc1l832osm5i895wb63vdc1b4h5e0a1nyy4bqg5otr5axp2w1f4z1q4q4q4o073g0f4alv4jfx5kjn2jal4u0w2k0g3uwk3k265iq66hjj3o0g3iu94xg84xya1zfk3jvk5wxh3t0w5yg31xpz4b604j2t3ds02l0i5y1u1pxk4da51z6e6fi54pry8lpr2ya73zv74bnz6bh54x2s2vth3tvc5fky1i435jau4qsw1m214xsy2pvn5htl5o7i3skh5wic1fvt4rio3si36dnp4c4n4ufu2ork5dkr3m593tmk3btr5nps2oah5ywx4nxs3r8i1z1h4jik3oui4pzx5o1g5auw6cjv1t461uwb4lgu5xvu4x3t5dtk3qkl3meu3ove5mw32zcq4n7y4e4a2avs4e3l1hbv3tl03g156c5t4ayu4aba5ddb5mmg5k093fj74y3j3dxg5a6n5lvd3c2f1w514m3m4x6k6h7b5gow5n6s2f184kvm6d5j2qhn1ppm5y2f3fi23vzv4r735h5q5gic1g6g5j474tmr4inb1w6h1inf5alk3u8l2bvr5bnj5nk42c6g5tbn5ug82wbg6bgv3fzc5mgf4ngp4akn3k274gfn1vjc6ckc3bqc2k0x4o0a4m1d3cfn2ds13wnt2ogy6d286ffi6eu62it46h783s0e3u1y3r042nsl4knj5q141e1x5cs35hfc5zob4erz5ant6ft43th01ijr4lnw4pyq2r3t3ik35mkr2gz71joj1j171c5o3avf3u0t1c855w996d4o2qic2tmn4cc65q1h5k5n5n553rxj3njy3srg4bgm4m0r5nxv5j1w4bbf4mot1tl76gf94ivs1bmn1bju1w4o2pmn1k6p5akz4ca74joa1mfa4qqc5e2q1dgm2fxu3ejp1a1b5k0j3h5u5ha12rg64b774hzt5fe74pgd5uwm4rro4rr64o705cfa4ke04ju32wtw2qhm3m3z2vqt5q0d3gcv4fmn3s7l5kgx2n9e2vmf4x633fc11ok74pzv5dd94nru1udu6fmp5fxs4dk74e5f5ml03v6s4eeh5cjf5e1o6bw83h2f1yly4avs1sri1avn3i254fm84jg73fu61g7f4l1u4dr93ocg5wal4dq21uz84qjp2onb4hgc2lyw5xgl1ydr2r0h4q4s5j644riv4cp75d9p1il42qaf1idb3ft81hos2xnn5myv5ti43gi52wxh4eo63spk1g3f5iy45h1v1mem1rdt2c921n7m5dif2py44k9h4ehr1nfx4cst3h0v5z7j5ta25nu33k3i3gpe3zq95cqj6axk4len4nmp3b253ch95djv4hxw4euc1hvy2jk93ncz3bu14bb23wqh6alz3qch4jv72jmj3nan5vds1oth2aie3dln3mv55egu6dki5am03vrt6dpt1ew92w6u2ggu5jsj2xwd3zya5uwp2exc5e285k323g4f2xng4x5y6esm1gi43d2t5ttw3ekx2uwp1klg4y2x2dwx5lrq1od81ceb4ci24m5i1o9e1nq73ejr4wrs4eor1g1d5ofi2kce5eko4mhy1ndy2cc72nnk5ybe1svg5aes4pkr5j5x1cka3n7h3pxe4kz71tcw3v5j2xp84bv21gyx4i6b4oyb1ox92wf23zvv5f901rdj4azb3o5n4uub3d1e1n5z6b1y2o7e3o9v4hf46ety2qi65jas3gss1c5c5l9l3ifp1czk4fi91cs45e881mui5vp13vbt3sh04avw2asu1qf13hjo1iiq2r2w1ztq2c8x3wtj4lys4lv21u9v1dx63mtd5ii16d5h4nku1w1d1e374pte3c7p4glx1hvi5f4n5f6u1y8p3kwb5ggj3gx03ztx4uiz3ueu2vl42wnl4cl95aqn3ipx1i723dsz3mhi4ap72xcg7prc4e3o4int1zz15bjt2xas4ny35fi71owi3qd41ew84hdc4ac33h525nzp1lbf1b6p2ylp3qxt3kyr1ksn3twp3ti86ewe3t193eu54dvf2flr1oe72or91v2m5fjx1m2x2c803nm64nak5y122vwn5chk4dv95akg5x9h5m7u6axp1upk1j361uv63f2a1yet1ov34kwp1eoj1yms4o4g3p0g3tsz2hrm4tz85k4x3hzk5w5s4ekg6gh95l262lsv6eqa5fp02zc92jk73h033wb41xow4hra4mk11y205yc15lx62er05x4m4yih3mbl4a7i5koq3cx94zom5sz62vqm4yyn1syh1kwr6cyb3pm12zym5fv73shz4dmw6b5j1wn65vd31njc3ew25ia34a4e4a9n4iue2ewa1akq5ew95n8e5a544kow5w6i5mgg5oh34hmh4f3i3kd71w9u5da34n6y5jid1juy1f0r5iw04ui43tkh2gc85qc43wzj5l7h2kdh1uyk3sv93uex5os84b7q5a6i5om25lgu5uwk5u1q5unh5nw14ck31g422e9d5k4z4l7b1so26esn4pzw1ida3jzb1o2h5qby1nde6dne1f8d1nvr5ult1db54fr31g275alo4o154ryd4oar4zy04pd72aq76etj2zga5luu2l8j2wky4yrg2v222ndf1jsv4u6z5wdl5nxi6i8y4u6x4mw54ufj3ith1wb03arq3dp21lst3fqh2ivu1s5q6ct73pma2ay65e901re14l323g5k4bw41pig2xne4qme5ugh1cpi3wd91o5m5wfc4tun2y775laq1ax21b393hrb5dah5iza3thb4bi13arf4gwi6h1h5yzc5tg63vap4lkh2q2a2fle2vwf1g2k2zz25xhz4zim5fwr6g9i6bqa1g452ao63is92qmf3wt75vlr5fnr6cf65z9e5t1m3uda3ur93dp46c7g5kmf4hev6d8e5acx5ouh2fde6c0n4wt26cgp5zun5dyt4cwb2xcs4z1k4b112i2c5ko52ccc1xgj6ayt1ao81c5z1b9v5toe4bup4pox1gnn3a4o5kqg5am11i375uln3gpo2g013fx65nba1ke73my54inr1jp55eqe4muf5xhr2wmr3ebb4mwe5ap45nwg4bde4x8t5tbp1nl64oz13hvc1flr3pz34pkv4drp4awk2ww24tw95b4k4o3t4fev1o454bcj3upz1qkb5nho2x8d1aq75y215i123bsc4wki1ouy4jv95o9h4ez33dd85h7g1sqt3pn45aab2ha44enx1bap6enm5za73dbs4mvw3vrv2azc3mss3i605hld1zkn2wxq4y874m8x5f6v4fhi5auv4l7c3wcl3gqo5dhh5u7d6grp1xm61lpz2wf35cvd3zmj1g6s5eud3wyl4wh92oq62who2nmz2xiz4hbx6bee3ryx5ans5zvw4zwz3q964v052pyi5jf21wbv6c7x4qsx5m6u1m0b3qg63nyn1rm83lhj3g861ny03zj83o6l2vb83p9l4bnx5uch3sv64ynk223l5orr4o0j3rxm3rw94po04z844j215yjm5n254bky5svy5gmn5u7l1f1j4aji2oj93oli4r4o6ayq4ql13f7h1skj2wfj1wc12r3o3m5a4lwc4j5p3n463ttp1jjk5vb72pj03dog2bve5vfm4l2x3uvp4wno4y382c696eol2zx94q9s2alv3ip63sio4xoe3sn85y485u7j2g9u5f3g1xh44j795ghv2i2b1gah3kr15npd5mks1jwu4inh1tsl2wq56hkj2yek1hpo2e9u3mwe6aff6e995vlp2uxu4u5t2hwo4ury5byi4v045e2s3lj34bt94jt94rce6b5a4mk24idv4bah5lj13nal6d1m5kpm5sxn5doh3m6f3u816bsk5nfa1gui5i1q4m4q4ow05ur65iu76d551bma5uxn1oiu4ln72a5s5u5k5e4w6afg1oyq4xtv6eji2xdl3at11njb4u0g1tou2pj54q1a3avk6fmj2lto6czc3u8m2y5l3fjg5uwi6m9c5m3b3jxw4zqt5vc64bj85knx3pix3e6k4f7j3koo5n3y3jdw4pl34nmo1ody5tpc6bsm2cm85gn75hu01yq72gga4wy72brn2fmb5h144zsp3nus5n8t5x5g5yls5u3b4x144puk5wa62y2h4nmt3uol4jzf4um32wi25k7h2ccu5x743ddb1xd04mm91ulg3coz5epl4ear3vzg4qac4l5j1ai63d8w4mi92wtv5iee6ge04q3r4qb35cdh2vip3pz23f343rin5n2t5oqw3p4w4n5g2pvl1b0f5a3u4p6x3rsx3rcj5i9z5ai63c4f1o4o1sje3alt5f415yid3bgl4rdn4hso4ttv3ok95y0g5twx1wug4a6c3gxt4lzs2zx73jvr4as93f1a4cd64r065h5s7gpb5w0i4wp75e3g2ydt3hec4abb5ji84olc5ieo5i2z4zy54qga3t824dff2wr83i7b3v4v4gw82hxl4bkt2wj24xwk1xk92fgh3tv71ajp1tps3ag93ls45wg31cwb3mea1bjr5auz2y671q9m2i3i5ivj2vd11p2g4l7n5efj4jzi5mt05vlk3rt43zmm2wn92a254hmq5jim4zyy4bi71f3j2b522xkd1yys3vtr3zrl4kao5fnc1ke56hwz4d0x4mzs5mi54a6l4eg51sgu1w113dkg1s194wyo3ppp4rlu2jjk5ovp6cd93qio4wrb5h9p5na01wbt4ael5eu13nw61c5s1bl44ual2vsl5vil4o7f4dhr1pw61b5j3iad3rwg5wev2pjc3vi24xum2zmm3fv33ukr5myo3lbl4ppb1q0b4abi6bfx3kmy1q6k5ygd4z904omk5bqh5lrj1ta65jzn3ad85izu5ief4frj2pre4ty65nut3zps5e2v4k435e7r6ftz3rjc4uvc3uix5up34i312p151ag91gu36cw85ei84psh4i716f9v4yoz6hu35e2m5ap54fob1uod3e633mke3io74whz4mt94x211ppi3t2p5q0g5jjs5icp4g1f1csh4mwr5al14qxq3o9c2wxo4xmo4ii95mlj5hm34wr73iqv4xjr4w9w5fhm5o2d5osk3bv93i7e4kz42oz72vzr4d4d6eog1sfi5ehq5uy84u0d2l115v2p2vtm5ef81zgv4b2l3g324q4e4x502oax4r8y4c611w2g5er26b2q3up73r015izq3l6f3p9m6ey84b746fyz5g1z3t4h4wkc2o4j4bdj5mek4gvd5qil5go24m3f2e2b4bi25l0h5ugb2ynd2wzz5wyz5may4eev4kiw2y7i3tcg3s712qcd1vru1h004uat3nyd3bkk4n9d1bim5zt15ml23fpd6h7o3p8z4ewh4uva5a3q4dai5o553f694puz6f053g354qij4dxg3n1c4dt25u2e6c7j4cj42w7x6ccq4qsv5upz5iu44x0u3ffg1y6q5yba2f354gsc1jt14qvl1mwn1jeu1c3b3ual1rdn6dh15iub5mav3t833iof6cwf2fpz5ml45f2f1fpc7kme1erq5t9u1lhv2qlf5jmp4s3f6hm62qt94p4i5vih3mnu6djc5db04ca55mar2w772avq5eqq1tsi2vw22ggd6f6d1f4g3ndm3l175fni1c3r5trf1pau3vf36ewk4re94li81n4k4l7o5kbh2gj52oh44wht1joc1qxl6elp4qge2yfe3g8e1cea6czu2fs84mk54i605h5f5tcc4dpy3fh84h1m2anm1uom3oim6ezi3da93r171l6s2uzv4e1e3d284bcd5kez1bn46biz4lwt3jpv5fsm4mds4e6c3o9p2ylo5fyq4hxq3mj11zm71s634nk94qmm3g7l4zyw2q8i3gfe5ih64owo5o5f4x7q4wy11qbq5du61oe01g2a4iie4x5p1fhr1ntv1o5f3os32cbz4arb3lxs3lxg2g944gv15n871gz91b6l5kcx2xni3ig61p4u3r9h5n2x6aud5nee1bnw6bo63kaf2fvd2xaj4a955iv23n2u4q6e1i2s2f346evo5ksv2e9n5cgc1m511d4h5ncy5kls3s2p4o091zaj1f0u4k3l4tww5f883fcb4arw4o9w2ay75dcz5dqf3ttj3lc32xg31uml3qt64oty4wzv1hxb5l874ah95ma73npa4hs84qgd5zkc4d2t5elz1jk75cuh3jqg5w4s4n7m3tct5ie14n1t5aqh5oku5nhf2yge4gs96bu35vqr2am45wr74j584zsr1yon2bkt4buq3u7m3u513w552gfa3fum4hyu4pra4kyk4gzp3ekn3v2w2pog2bb73qj95d3t2w675fs55qaf4crb6fe03zmq5t1t2xm14oaz6e8k2fys5egs4aac1akr2wi12qbs5h2u1lke3smq5eds3wmb4azy3cz11s391n945lc05wg55ttg1ndz6gmx4cfe3fsj1cim3kry2f2h2g9x1o476aqf4knn1t294k5z2ycf5ijr5kks5tg24yxu4i7c3ftv1ke34bib3coy5orw5bns4bs03igp2uw44avj3qcy1yqj3a734uu84h3f4rwk5j5r2rkm1w144edu3e735o1s4ngn1mnc2ypp3wq54j743rz55upe4eh61c844fcf1sc83agm5w101gzg4qvv4qp64why3ip95he04yv53ril4uyd1nu33ozr5qin4utv5x9o1okv5m4c4xhv5ll73cyx4gm32w785q1d3bym5aqo1ga81p5e4c4f2mps4cxw4w9f3lmk3sz14tya4qjx2v855bw42ael4pv55osy4m8h3i026fs13twr2vt34rrn1h5u2qoa4lk63qtu3k5d2qhy5jmw3bun1ghy4l706cd44ymb6bh25h0h1ppx3r4p6gnr2x6k3f9n4oys3rf53hub4fcq5o1i3ohh4mqu4gw55m4f2r9w5yea1xp15lm42csm5t2g3n1w3t8s5nhz4zk51e6q4cg94bf12ycr1c503hd34ehe5tku5wle2r645l3j6ft85ti54tyt5lma3oct3zt25ai43zh83fl83old3fqs4xct4mjp3g2y6g8n5kkr1fjs6dxg4cxy3che3qfv1r5v1pr13nsn4p1u3szb5u114o0t3ux04q4i2nww2qp84rsp2p0x1fsg1u0g4djx6cco3opp4lg62clv1hps6bhe6bir5h093kwj2bed3e513msk6axj3udd1zvx5u6d4qnb4eox2rly3ob23osi5m7t5vqy5ei63mbz4f7n3ipb1w6r4zx96gy52hh53nmq1vjy4hy54ts12qcg5lwd1kjr3oyn3rbq3ujc3ekp3p7c4urv3gws3fw41ow84pov4k4j4m0f1ow43qaq4ovf1ps34gw65a4c2ovx5q191gwm2kwn4uce4y2p2q2c5lgn5oxg3i4b4qmo2wyg5eay2b4l2xd93sus5zu03gjt2b1v3ctq5tzz1h284b132q152aac3kw93qox4wku5wqk2fjp5eij4mga5ak25dp46f8u4inu4nrc5drt1tng3vhc1xh31toi2lya3mpm4k551qb95hlw6ej24i334cwp2fvc3r026ezh4muw3d913img4op14s3e3qxp4f5y4qmv5u624qtc6tim4h2j1x7e1b6h3opr4gjb5u5h5v3o5l442c6i4ezr5u4e1fta4z2j3n3j5eg42yiq4jmx4q2k2x2r2fzg1ajx2yki3ccw5u0e5j321y2e6gwr6gu75dxb1hyo3lc53arw3rz15kr85jv24xpj4l2f3vi55etj2a3w3bra1h796ed65w856mub5od55ejl3ubx2c6k4rn03pdq4unp5mng4w5j5afn6h0b5yc41ahx2jst1o3h3rz84na91f0t4eym5vew4k3p4zs93b9s5wcl4mmm2l654lph3frz3rz94kba5a8x5eps2wor5f1j2oxd3ldq4g0k1u325gr94fl33uxl3fud4x683k2f5lsg1h233zrm5v6u4lke1o4r5mw44fcb4qp81htf4q0k4yc03ebp3q4b5dh41bqo3sn74waf3gst5ecv1hvj3m3c4ocv2ewb5h193ryz3a2o4ea34wx61i324lge3cwe2hmu1h0r5m9w3jwr2q704iu01tl32gqn3bc34gk72wd32x8z4ybt5dms1nhg4mw13cgo5v4q4x6n3bh83f6h4au75i3a3l6x5d0j4c1u6fzx3ook5mt44hzx3udp4g8o4mrz4tyo4umj4rfz1rxp2zyn5t546bh34cd54hlk3t0x2az55dy51ft45org5to86eqx3b2q6ez96aox2y5f4x7o4y4v5oae1h255d2r2xch5ndd2cf82yi74nzo3mct5dia1iih3ime3tll2jle1h263l7b5v881o2o3e904j463dp95ngb5jh63rpy2vfz5xn31e6s4xx43ppo4qfo1o3d3s436ar23cyu1qf01ow65eml4amz5ye94mti6f295mk11qsc1uvr2off4whq4d086gu34b6q4agc4uu53blt2zb11g373krd3lm11noj1t323i6z5kbq1gwr4k6v2vba3zrc4nmx4mbc1ie93bgz2k621mqg1qy11mau2x7u3iqq5h8e2aig5n9l2g5p4fri4q3u5flo4bo15tyr5x262drc4bbh3gkz5e6o4qy31nq05e8w2gu81w9v5uci2veu5hvy3ewu1jm45yas4ojr1h0w5eou3as04e3g4euv2wly3lir3znr3q3t6ap83g3n3c523g2w4iku5bry4wvu3neo1abf5db21sjh3hc82liq5dtw5dhu1qhr2pl04wcu3exo1jvp4mrd5jxn2yjc2o9r5en35hpm4qf83k053h0q2a4l4xue3ewc1dtt4yzm4q4p3d9o3s8x4mq26ek35tgc2hds5fwj3kme1zog6ce64c6v1xdd5bvf1dud3lzu4c1d2er63f482xuz5fto4zei3c396fqu4fc01bzc3pj82auc4kp02y7p4ono3nc94bjb4qo43mz35edc2xzg6bqj1ga94oq64b805ee71bcu4y8z5ka15lpd3qi45vii5ele2ew61s9v4bqw2x6w5mnc5eni2xi71wqv2b8v6f924jve3oy06h414zx44q156czv2wti5j9l1o5r5n1v2bq74fic2ole3umw1a1e1ax04ux96bhi3pj35m552uw62bqv2ea25dl16g7f5o8t5nze5fkj5t1l4wj73ibi5h224bgh2j9h2iyf5m282v0c6ez65b6g2q3z4des3pcj5y0z3u6h3dtc3cr42igv4qaa1yhm3n355ylj5dls5h1u4qw44hv34jfi2go42m0o5vzy2h6t2qnn2aqb1zd53pxf1p1n1bnt2hm14z465e2n2p8s1h2k3uh21b2m5eiw4bfy5csx2z922rjp5o7n3d3p4ban4l0l3zo23zhx2hah3dx14dkt3sz93n0n4l4m6asz3hv43imc3eju5t6z4jaz1gjb5fl03r9n3sw85ggp1btn5j8u1x8t3bva2wtc5lom2vwc6bw26m9f4n1z3lzb1fwe2w162i6b5ytu4j8r4je83t602n9x6f8t4lwu6ebe6ajj5wap5a6k2xp73ql91q7a5dkn2gnl3rwc5npr2e9c1ajv6e4f1o7o5alf2xys6h5w2jfz2xdx4bda3rxd1f579icd3zpr4ciw2zcr2w9r3hnz4r1y3olg5lce1kwq5lrg5f0c3u8j1bl63amv1ej44ht03u6w4q095jss3qlc2b1i5cls3eyf6eln5mrh3nox2qe23u6j1qka3k5u1ws15ew06ft93kr45iug1ajn3zn02i3z1y3x2r9s5vpm4occ4nym3osw3hy54j864dfg5f1v5l4e2qve4erf1wss1ajq5h5r1ym21hee3rq71dxp1vgc3huc5fqb4mue1qbs1ujk6fa34xo84ww84qxt3in32wxp5j3s2h1h5d7a4lhm2rjs5nvf3l0n5b5f4oow3ej55fum1li65swg6eum3fas5klr2vv93v5t2byr5nr73suf2xb91f4x5v863kl61qng2a8g2j623zi01h6e3ap73zj64hp01bmk1nj15xp74iwd1if74ia03ms75yjk5j7f5aba5ake1h2t4mzk4ezj4an35jfp5v242xmy1yqy3aox4yjn2i0h4lwe4frs2hwg3o4l3ddg4cu82zfs5wfd4lnb4j174qyy2r3j4eoi3pdh1y3p4g5y3v4t4okp5meh1xpc3avl6gzl2pqc4g0y3wab5iop2ax93bex3cdb6afc1v0m3ksl3fvl6c7d1t2v5bot5yto2wed1jn24k4e1a943ozj1j813e931q9d4idt4k2f2whp3snc4otg2lty5bnr6c7r3as34ge94xg75dw13ivq2qrg2xdk1gno2gg51d4y5dqe3rwi4x8o3el94kup3eks2kff1w5y2flh2vwv3rvg4oeu3u4o2pv34i0t3aru4yv05ura5uv13vjc4bam5vc52ito1l5s3adv3oe65mnb5gvm1r1j2qe52rjr3wiz4cfm1gz43c1n6ma31z9h6g981qm44j243pju5cqx1wvj2yde4mqp2np94zyu3ua93fc22xp51umw5jer3dcv4aft4rhu3ahn4ytf5os25el93gjw4oth1lkl6ela5vkf2oz64q1f5usz2xfk3n514fxq4oc33ggu1hiv4d2s2fkf4oz36fkz3lhg1jyq3uvw4f6s2qk85jat1lvu11gs4cwt4gz35vkc1wu15m171rne1l2z3s0d4nxq5iu21x786bc96drx5juz4qvn5i7x5o7e4ktc1fl31enu2clf4zs04llp4djy5nrf4z0k4k8a6cdc6bin4e1z1a612q643s0o4z0u1ii54lk75ubt5m1z1t4j1g7v4q1n3l085d7r2emt4y2b4j0t2zof6ecz4gb94jfl2ow31ibg3fyz5g5z7lpr4g8n4bie2yir4yps5jdc3p4v2fum5c4o1kcs4r3s1cj16f094ce34ft22pcu4mo82g2r4lxk4utn1stc5nxp5t523iod1h014deb4jjs5ts03su04yhf1y4z3heg2g703p2h1sqq1swk2f4b1igj3fcq2pja4ase2o632xyf4j0v5ka75kzp3oob5w6t1h2u5a004zt32cer1w962pzi4qf73c884y674nrl4du84qtn3sue6fhu1qs45u6b5edb2p2h5gtr4hbp3tia3cbp2cgw4bio3gwt5t8r6fo71g9t3kr01gt35c832r9x3f8c5nk74cfu5e2r2wf13uil5fl61ms74csj4yat4f1q4lm14oc03hj02xwe3ms42jh03oad2y2j4bd36h7n5exm1ctu5l3f2ajd2c943g3r2zo34dro1uou6bsl1uy73zyb3t0b4o435q0l3wch5orb3kgp3zeb4pyy4b0j1jq83u4w2xyt5jhd3hmp4dxj5hg73zlx1zkk1gny4ju61il34daf4o0x5ygi6gla3mtw3mg03d9l2vcj5edq4bci4e4x2qdt3wuu3udv4dkq4bfp5i2e3q1x1qaq3rm84ahu1gx43wi24de25g2g2wuu5nud4hcu3k376prc2e7f4bb91amk4l1a4lqy4a165wkf4qsm3sxu3uqg5lif4azf5ntt3vsw5fos1qin3e7b1ll43vjm3ny36aqs1k6c4ngr6fc62gnj4zy63u8d2aou4b0b5t2p5efb5u0d5vjp5bui5e135f5i4ivk7hvp3d7k4vgc5g1p6b1h2br81cqp4w504ehv5kqf2yfa3ws94xkb5mrp3str5nkd5mpk5kqy4lw11avp3qdd5xxk4oks4hxr3ur04pns4i5m4hgl2vtd2gph3rme5fqp5hfu2iok4yux6g1u2hvx1n0s4l4v3s1y1g7p2rr42x002b554wmv4kc12x395joh2w0p4az61o0f3haw5w442xhr1h8s4ge13phe1evh6b301g352qfo5gjf6bt62gg35trr5ly35eh05ioy1xt83c3o5e743acl5abh5fol5ddf3qxv3iwy3ttm5n186beb5nxw5lxb4ra14muk4mm44hs65ncq3zmg4hcv4i724pee1qtn4awg4rfy5dyy3ud85itf5cuq5f1c5hey2ko73oil5tks3t3u5o3q4k724oma3hv66df75er44no65ugd1ciz1rev6hdq3c431a7t6fky5n1r3rr45bqg3b8r2pfy5c7f5l6j1etz3drf3k7f4b6e6asu1fd04zjc1y3g4joh4c384h5c5kej6aji4mvy3lpi4pms6fx13ioi2xbj1bnm4tuh4fgt5mhp4hwb6eo94aje1v2t5h851x8d3uoj2aog3o5x5vr82o4p1fh84jz15oq43zdh5otz3lnz1n9m3rak6ba76czb2wyj4qyo3mxd2ri92zq13ljo1kvo6g2a1gj65oug1g4o3mvm1iyl2cgx3v2x5iv44m2u4q1b3ggc2c683ind1laf4kxn2ada1om15eh74jk54q931b8y1x114mr64c4j4yik1osv4y7r4zow2hdx4ui64r6x1pxi5ni55v4b1h0a4pf55ggz1o4m1urc5mqt3ads5gn54mrg5ylt5k6a4nld2xl34auy1zoe4pum5lxd5csh3gbq5xs24ggl5a144au85n495x8i6c7f3fvk4kqp5y976gub5mxx3lox2oc73g1m6hsz1ilq3twj5vcx3svv4na43v5g4p7e2vwl4umu3v4j6gfz6duf5aqf5ezh5nar4yti4zyq4lop4nus2a3a2o9i3ia65nfh1e005u8a3n8n4axd3kxz3owd4fxj1gx04u901d7x3eq83q444ago5e2p1pxj4p6c1zoh4i7j4hlg5j6n3s2o4ec03wiy4k775yf11hsl4tjz6cbh6g384efu5wep1jwm3wfg5lvl5kqd1fq55nn63b5r5xag3w693udr4c4h5mgi5ad15zh34i7b6cwi1tkb3unj4u542x0y3isw2xbw6fzu5wgq4kzc1yhs5btr1juq2idk2v254prh5o5a3r0h1sle2ieh5ous2fqy1p7m3fuf1w101vot1guw1gbq5thn6b414xoc5ugc4h715i434oc13t0d4kw64jrg4ra54azp5sz35hbj1npa4wi14b7p3biz4bpj3lxe5qav4ge64k1e3vje4mic4qp92xg51w5x2rin3omc5ii23pax5elq3bpc1ec04x8g3cft4qd65n1x2v964ucc5ocj4mul3lok2e5y3eql5kyj1n5r3hfz2pg23g3m4fs31nnk4n9a4jp92j776cvd4tkb3tfp5a5o5nsx6bbv5myg3ws86ex12jkr5kcv2vw54ezl3dp05hyq5iyy2oc45div1gag2r383chp3ot82wqb6bqh3gxl2pgj6gfx2i3v5yqw5n9t6cc93p3s3oe92y1o2o4r1dzm3vp23djo4oz21p6d5mih4xt23tf75v196g9k4ipf3bim4nwm2aeb3blu3vtc3nww3mp61nu83wzk4zec3gvb4bt42f6v5xwr5m534yvc1ai41z1r1ryh1rhu5d1s3g0i1gpk4clb5cte4kmu6f9r3pjg1uz13tww2lbv5w1w1s263w9r4yes3sl85km02j792h031qnh4cpx5enk4mnv3r5m4tk45wg65uwf4cjp3uu14bxu3h304qwr2gyi1cnw4fzc6gdg4e5i3oq53wig5my84aj13b652e954xcb3wf55h155htb3t3e3h5b1ugp5anq6g4n1apb2ai74xxs1lrh1ove3v7t1xk54fiv4mcv1mrw4b145isl5cj65un93nil1x076fni4u2y4hbv6h2t4q6d3b8z2cnf4isu5u2f2cng4q904l0b1z6s6g3q4ylu3w5t4dei2zjv2x6y3ikg5j7p4mcc3vqs3u9n2g5t3owj5bnm3hkn3qtx3qzt5bpa3p176fag5nfb1o431nok3vby6as65vjn3skc3bg81tc15orh5bq05qac3l165kw23uj96byk5kgw4wvt1bv94ruz1fzq1mu81srg4y733upv4jj85xvf1xka4ewn4ewr4a7b2xab6g9b4u691qb63c6t3qar4k5o2gnf1u3q3g313oev4oc21eby3uef4k0o5ehi5h633wcg6hvi1hii4jhq3sgt4aua4hnc3bxh5g5v4j084anu3hac2vcq2f7p4ycl3s223obq1o9k4xy23k9x1xog5b0x4m5g4czs5eyr4lm55xup4rao3qcl3lkj2xno1hfs1gjd4bzs4j7d1fw01jfh2cgr4pd83mz65obj3gm04j3u1uvt5ml54fut4r3c4kfp4jck5xhs5mwz3n865qab5zeq1fo34eki5n8w2exm4klb5ikb2qhc5aqr4qn75nbw4k2g3qck3zo14knx3m6r6dh63p8n5f3e2vie4uyh5uoy4gr36cyd2f145v2q3h2m3ao21k1n3gfw4q192b1g4pdk1oxn2pj14o3a2y6s1inh4u5l4esg4mg64de53wke6dgy4mp74de14z6i2r4b5q0z4b332koh4qyh5y946fo83p4r4mny2vjx5lj05yqx5c264eb83lk13mg64oru2wpb4k7i5fsy3ava2z7r3ex64b8p3l135fbi3s3k3chc2wf04hgt6b5i4ayw3gk42lcs5fas1lyx6bvh6edr1ghz1dg91egh2x6f5o484avg3znc1czq5f392bpy2vc95op54ory3hu31xuc3hmo2ybt1v1k5o223qt74eo84bco2p3i3hii2xdm6axq2xhs5cyv1sre2y8o9lpr4l3o1dzk3lnj3fsm4ghi2nqi1i485mo26fr21bnn2jbl1r174rrf5jah6apw4trc1lgt2wl04i0z3oe53fjz2uyn3hxd6g3o2nqg3fc82zvj3mw12c5n3poz5ax93mhw5tdw5n7b4kij5axq3pxy2q963kjd5cf55id05e0j4kjv4e1m3gy45m341xqc2hzy5brn2d0k3s8n2j7f5zc53p5o1xh52vj74zt22b7a1thl1jmq5h7h5mz33dxj5q1g6ays3w2t1bkm3pb33vjl2a8h4pax5tt82y2p5lyx1zaf3mb62fuu4mw62j6m4rll3qai4kzq2uym5v843bm94egk2bqw2q8y4pji6ary4daw4i062wxk1r5n1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679684lp91me72zv92qo81cw23k5c2o654kqq3rdv1d4w1q4l4b5w4bgg4mm53iej3ftu830c2xye1olu2wk24pxf5o0j1my25czm4jit5mb11sqp3zlw4xqu3hkq6fns5e0l2p8o4gzw3n871lhc4itj4m7c4olh4q1e5l7e3faa5vqx3pka5x545a9u4n9e4est1il94igr3t2t6dar3gol3vbg2ydk4zpf5zo74xnw1fpy2r1y6m8w2jds5icx1hwr6bj24b4m1zsb4do33t3i1f8a2ke15ezx3p784rvm3ovn5wzv4udb1okz1mpl5npc5ff61hlf1nvq4bhf4y4g5mkz2o0u3bcs1wvc4fsl3oz16dgt1me82puy4odp1hpx4nrq1z2b3uik3mfv3vqh4w9g4xek4jok2wap1g504j0p2o9a3m944i1c5a824i9h1k1i4uro2f7i5fpk2lgf4l7f1g3d4ir53mta3jzg5f944nrt4yax5nhv2xtk4qh71tok4b6p3rg23q8d3obu4awj3daj2j505l2z5bml2bba5n342xvn1dpu5fnt1jyc4zz16hm74rrv4rww5orv3qo23uii6d1x3juq4qk46mr55hjc2p4s2hnc1k4g4g0c2y5g4u3f3tv51i3z4mw73n2c6cvw3v663wzp3s7m5ujv1p063ipy4wkt4ie05fot5i595za94gii4h2o4yrs5a6h2xo84e3n4m5k3dga6fse6ck61sqc4x1r3dnj3rvi2a584bf63zlk4mbj4tpm4d8c1ejn4yt62x7x4qp14de35yg41x7b5n9s2fme1ydt2bdf6baw6fsd2xn34tk03q4j1u9l1oqp5htz4glr5kj05ukl3fun4wk24ht65hv11uze4bcc3ff65if61tsm2r593iqh2v7a5d105nvh3eqr1jq91u1b6cer5uq91u3s5icy3exh2oqs1pzp1d4i4x6p4mb95emk1iky6b7f3chq3h5s5zmq4ib52wej6fjm5ewa2igx2z785lpm4wet3lxl2xba5wbl5zla2x6x4mw95t2d4j3m4aqh3lbk4djp4odl4x6j1ero5f3t4k3q5ta41caq2eg71f733rxg6ezq1qkt5l3e5c284pp94bgk3iaf5vrp5zz45ur53ft25ech4jjq5iz65dhr4l2g4r173wk64h1e2aq95g1n3zm95c4l5mfs1fzj2ltw4x7i4c942cfg2va53vb62hob5ah25syn3g6g3rwj5sz44f9v5n2d3n9r5ldo3vb71sqo3drg5j9y6b964yz91vcj5epr4tx63dz63czv5v491ahy3wzq1bq45u8c6bj32qnb4a9m3d4f5oui5wmg6ma44x5q5cbr6msy5avi1g3b2wi43kjn4dhn4o7e5kit5y5t3hfj2qd85vsj2y2i5m0m3tcp4bhz1jd65idn4zzx4kn42a5c6hly1au24jbo5cgj3ske3lq24pxm2wxg5tb62vc73iw45hct3skf5lyy3fmz4p5z5ktw6e4w1cx96em74mjr4u7t3rde4ux44i6f3l3x4ie64j701jd04iaw1szm2afw3ess3sap1olx1bzh5hfb4x3h5we93zsw5ny61hn23l3z4qp21d4p4xkc2is06c7e5zku4fai6g9a4xu35dry4d8z3zcz3kbz2y594nal4rpv4yje3vf84bqx4z9l4ep24ylk5mme4dht2uy46mu33kx15o0s4bch5c4k2br14ddh2f9k2w2i4ogn4up55o4y5hjd2qw15y8z4kqr1o2t6e053u7l2mip3hvg2p594d3h4pl53tzd2vnp4e3m3vgc5bqi1b7h1lhu3rlr3h222wnc2wot5d1t3mo04wn53p3u1nfs4e905aqu1bmq3kwz6f6n4rj54omd6min1ujj4ppa4uxl5y3n6df24wvl1xt35oaj4a9r5mli4p4e3juo1z9g2ykc5a0e3g0w5t9w1sqa3wci1fkw5u4g4mfe4kpx3nti3azb2xog3c3r2buc1hyz4dcd6azl3t3d3q4l4few1q954u0b3b7u4bo44o105wmt5v9t5aok1jtq5uit2vgc2gfd3mna1aqc4xtt4z0d4ty92yiv2hrp4zh22z4o1qku2xdw4n7j4yp13exf4c6z6ccu2wxn1bwb2gvf1hiy5c4t2za52xkf4q181o2p5th24dj73eyd4j0r2m3o2b534m3b2izl2vtr2x6d2i0a5ehg6cw44c373cwj1azm2qci5sz02gkl2z4z6awo1v114l533p552ynn2vu34dli2bcd4l0s4uda3m375j5t2p164gh61mfg3s3i4j732v5x2h4n4jsz4wk14igt4k633qqk16pk5aom1hyv5a3w3veh3g4l2ph85mkx5c4u4gto3cj54prj2vd75duc3odi6bg51qwu5jn81v1m1qpe5v3r2wc42vte1a524dhq2qta6ccy4jog4bgy5u9i3az91gt12jew3pdc1n3i5fyx4f494nzn6hm24a4l5xij5vk04xsx2aj84odq2n7b4ygf2a4q2jc04jsa1inq3dc35tob4urn6bik4ju45nya5oh25znr5ct23u4u4x7h3max3rbm3krj1aj61pmv5n0e4nhy4oem6fi44e3j1fq45myr2hkf1os03rqg4ivc5c7b3lq41u6q1qxz1l5r4xxh3m405or94okg4d892gm95x334de04gr85lz81p932brp2gg86fdt5cxh1jvu3wp11fzm5cxa2gbg2g785aml2y342qnp1v161njj2a5u4z884wmx5vo24fod2pou3jsw2ow25g3m3odl3o9e3eyh4ej23c4e4b6f1pl03pb86fap4iax2bua6fgg2o4h4uwh5wbf2yxj1ff12giu1qbt2ovq4bak2y3p2iwu3hvi2w0x3fcl1zpa5czb3t1l2cfd3k3g4cfw2e915op83hig6h7y3mtb4eb94lkg5ehv5ier4ode1xoq5d6p3kwa5np85v826ma13bz33myq4j0s4f4p4lh61uef4j3d4yx44amx4ptg2c974ec44r1v1zc94nuf3g2u6hlx5vij2x4o6hlz4lkj3s752gz81gvk2yhd3hqz3pb71thr4ris5twh4gql3n3l3acx5yvx3gy21xmu5l6p5l8n4msn4rz13f663ucj5hcl1t1r3kce3u151wbg5khi3er54qew5mft6eqp5gsw2qd74cli3f9w3msc1jgl3kid1ymx1ui03d1f1pxl5kos3vzd5fcz3ara4li65ks74wym5j7q4qsh2ce95vqz3o2m4bcm5orx1i413c5u4kai6gjy4tsz5o0e6drt1y573kqb3jup5ork3ikc3gwu4wke4x7l3lp15ivy3f164c361w2x2d061hbj1ols1iup5aix1ydd5w4r3h233rj74ish1ebw1fcy1d095hdv4x1n5boj2xn74b6s3f824clj4zzz5j5d2vts1k083u3f4jk64csy6hth2mnz2vpg2qd64jkw3ml51ih04at55dgu4g315n0d5aa94u4s5oa62wzm4b4q6fi16chn1z4u5aa81lpk3cib5d755x4o1ydb5dhq5t284zz03evf5vyy6eip1q633ldw5tq45uxf2j7x4kil1yda3bc42ew56ee34yrr3wax3bzf5ody1k064j845l6h5eok5nne5m6m2a4r3p1d2ayp3iux4b0g1jr14qo94bh44xt92ok12r7g4uib5mmn5akj3hs45wpb6e5x5vnd5evd5wlg5l4m4kiu4own5oh96arv1xr94hv71234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623636qqw6d086jap6np26uvp6oxq6jsn6hzb6qrc6oio6jag6moa6hld6i9a6e4c6g246jb46s556seo6dyz5zk56jid5ze66qlu6a6k6qgf6e3z6te66pka6g2o6jsf5zxk6qxd6n976jt36qtr6oy16n966qzh6qqz6qmt6ibx6hmt5zk76k3l6cjs6n9l6ibz6ott6gge6hot6e3p6md66hlb6fe56uwp6npp6g2f6mo76bqd6nsv6i766n536g2c6eeb6n0m6uvy6ovz6olx6v5l6hhg5zcu6dz26mjq6efk6s9w6gdy6kqi6ueg6oxt6oy06qr76i416cyg6qmr6g276ggb6g3c6n4e6fcj6quv6iql6i746qr46rnu6jib6izq6qw86qto6qrd6hza6e5s6dz36e6w6cyh5zlf6om46gga6pgp6qqv6qtq6gj66os56s076i776hhj6ahs6oxx6mjj6hor6jb06i686pz46mhb6uim6jsg6i786oxy6gbw6mo06ggf6qge6cjr6oxp6d076i636ten6uii6qlr6sen6oxv6g2b5zr36kjf6qr96g9f6e6v5zk96pnn6nri6uwv6ooz6npi6oip6miv6s576p8x6hoq6qts6ggd6pnm6oy26oi86mhd6agt6i5p6hhr6p8z6c856g5u6j066qsz6jbb6hhp6np56nlj6qlp6n946e136qls6uil6st36n926s566hzd6uhv6k056q366ic06hhi6e3m6qtx6jse5zjy6o3y6rpg6rr06gzy6qlt6ufo6o0h6o3x5zjz6i8t6ooy6oiq6od66nrh6qra6hhh6m7h6ufn6qr06o5u6h146jwa6ny06jan6ftf6oxw6jon6cf76rtn6jsz6o9c6mo86qln6qqu6i666mja6gwe6d3z6oxr6r4k6hle6h9v6hou6nv96py06qlq6nv76n4b6jaq6i8m6dz06oxs6k2n6cjj6ffg6a736qqt6a1c6oxu6qre6qtw6np46hv26n556e3o6kjd6sfc6qi76hzc6k046op06q386n8x6np36uvv6pgo6jbe6i756qqq6i626j9y6g296h7d6mo96jao6jmf6hmy6qfe5zml6i656e7m6i616rz66qtm6qlo6oie6miy6nrf6gj56jad6mj46h126d3y6qr26qxa6o9b6ckl6oir6d406e6j6i7a6g256oin6jam6oxz6hop6rot6uhu6mji6nrj6nt26op96pno6e4v6k1s6a876oim6cjp6pyb6h136qrf6mhc6j9w6nrg6fff6n936jut6g2e6nd36os66dql6inz6i676quw6qwi6npm6i646e3n6qrg6nxz6iby6gj76qr36qr16s9x6q4q6hbn6nw36tel6p8y6d5w6t6a6o5g6r7d6pya6ffe6d3x6gj86mo21234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431446qqw
6jap
6np2
6qrc
6oio
6jag
6i9a
6jb4
6seo
6jid
5ze6
6pka
6n97
6qtr
6n96
6qzh
6qqz
6k3l
6cjs
6n9l
6ott
6npp
6nsv
6n53
6eeb
6n0m
6ovz
5zcu
6mjq
6efk
6gdy
6kqi
6ueg
6qr7
6g3c
6iql
6qr4
6jib
6qto
6qrd
6e5s
5zlf
6om4
6qqv
6qtq
6os5
6s07
6mjj
6jb0
6uim
6mo0
6cjr
6uii
6sen
6kjf
6qr9
6g9f
6npi
6oip
6miv
6qts
6oi8
6c85
6qsz
6jbb
6np5
6nlj
6n94
6e13
6uil
6n92
6uhv
6q36
6qtx
6rr0
6ufo
6oiq
6qra
6m7h
6ufn
6qr0
6o5u
6ny0
6jan
6ftf
6jon
6cf7
6o9c
6qqu
6mja
6r4k
6h9v
6py0
6jaq
6k2n
6cjj
6a73
6qqt
6qre
6qtw
6np4
6n55
6kjd
6np3
6jbe
6qqq
6j9y
6h7d
6jao
6e7m
6rz6
6qtm
6miy
6jad
6mj4
6qr2
6qxa
6o9b
6ckl
6oir
6oin
6jam
6uhu
6mji
6nt2
6op9
6e4v
6a87
6cjp
6qrf
6j9w
6n93
6nd3
6os6
6dql
6qwi
6npm
6qrg
6nxz
6qr3
6qr1
6o5g
6r7d
6mo2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196import copy, timeimport numpy as npfrom collections import defaultdictfrom rdkit import Chem, RDLoggerfrom rdkit.Chem import AllChem, rdMolTransformsfrom rdkit import Geometryimport networkx as nxfrom scipy.optimize import differential_evolution
RDLogger.DisableLog('rdApp.*')
""" Conformer matching routines from Torsional Diffusion"""
def GetDihedral(conf, atom_idx): return rdMolTransforms.GetDihedralRad(conf, atom_idx[0], atom_idx[1], atom_idx[2], atom_idx[3])
def SetDihedral(conf, atom_idx, new_vale): rdMolTransforms.SetDihedralRad(conf, atom_idx[0], atom_idx[1], atom_idx[2], atom_idx[3], new_vale)
def apply_changes(mol, values, rotable_bonds, conf_id): opt_mol = copy.copy(mol) [SetDihedral(opt_mol.GetConformer(conf_id), rotable_bonds[r], values[r]) for r in range(len(rotable_bonds))] return opt_mol
def optimize_rotatable_bonds(mol, true_mol, rotable_bonds, probe_id=-1, ref_id=-1, seed=0, popsize=15, maxiter=500, mutation=(0.5, 1), recombination=0.8): opt = OptimizeConformer(mol, true_mol, rotable_bonds, seed=seed, probe_id=probe_id, ref_id=ref_id) max_bound = [np.pi] * len(opt.rotable_bonds) min_bound = [-np.pi] * len(opt.rotable_bonds) bounds = (min_bound, max_bound) bounds = list(zip(bounds[0], bounds[1]))
# Optimize conformations result = differential_evolution(opt.score_conformation, bounds, maxiter=maxiter, popsize=popsize, mutation=mutation, recombination=recombination, disp=False, seed=seed) opt_mol = apply_changes(opt.mol, result['x'], opt.rotable_bonds, conf_id=probe_id)
return opt_mol
class OptimizeConformer: def __init__(self, mol, true_mol, rotable_bonds, probe_id=-1, ref_id=-1, seed=None): super(OptimizeConformer, self).__init__() if seed: np.random.seed(seed) self.rotable_bonds = rotable_bonds self.mol = mol self.true_mol = true_mol self.probe_id = probe_id self.ref_id = ref_id
def score_conformation(self, values): for i, r in enumerate(self.rotable_bonds): SetDihedral(self.mol.GetConformer(self.probe_id), r, values[i]) return RMSD(self.mol, self.true_mol, self.probe_id, self.ref_id)
def get_torsion_angles(mol): torsions_list = [] G = nx.Graph() for i, atom in enumerate(mol.GetAtoms()): G.add_node(i) nodes = set(G.nodes()) for bond in mol.GetBonds(): start, end = bond.GetBeginAtomIdx(), bond.GetEndAtomIdx() G.add_edge(start, end) for e in G.edges(): G2 = copy.deepcopy(G) G2.remove_edge(*e) if nx.is_connected(G2): continue l = list(sorted(nx.connected_components(G2), key=len)[0]) if len(l) < 2: continue n0 = list(G2.neighbors(e[0])) n1 = list(G2.neighbors(e[1])) torsions_list.append( (n0[0], e[0], e[1], n1[0]) ) return torsions_list
# GeoMoldef get_torsions(mol_list): print('USING GEOMOL GET TORSIONS FUNCTION') atom_counter = 0 torsionList = [] for m in mol_list: torsionSmarts = '[!$(*#*)&!D1]-&!@[!$(*#*)&!D1]' torsionQuery = Chem.MolFromSmarts(torsionSmarts) matches = m.GetSubstructMatches(torsionQuery) for match in matches: idx2 = match[0] idx3 = match[1] bond = m.GetBondBetweenAtoms(idx2, idx3) jAtom = m.GetAtomWithIdx(idx2) kAtom = m.GetAtomWithIdx(idx3) for b1 in jAtom.GetBonds(): if (b1.GetIdx() == bond.GetIdx()): continue idx1 = b1.GetOtherAtomIdx(idx2) for b2 in kAtom.GetBonds(): if ((b2.GetIdx() == bond.GetIdx()) or (b2.GetIdx() == b1.GetIdx())): continue idx4 = b2.GetOtherAtomIdx(idx3) # skip 3-membered rings if (idx4 == idx1): continue if m.GetAtomWithIdx(idx4).IsInRing(): torsionList.append( (idx4 + atom_counter, idx3 + atom_counter, idx2 + atom_counter, idx1 + atom_counter)) break else: torsionList.append( (idx1 + atom_counter, idx2 + atom_counter, idx3 + atom_counter, idx4 + atom_counter)) break break
atom_counter += m.GetNumAtoms() return torsionList
def A_transpose_matrix(alpha): return np.array([[np.cos(alpha), np.sin(alpha)], [-np.sin(alpha), np.cos(alpha)]], dtype=np.double)
def S_vec(alpha): return np.array([[np.cos(alpha)], [np.sin(alpha)]], dtype=np.double)
def GetDihedralFromPointCloud(Z, atom_idx): p = Z[list(atom_idx)] b = p[:-1] - p[1:] b[0] *= -1 v = np.array([v - (v.dot(b[1]) / b[1].dot(b[1])) * b[1] for v in [b[0], b[2]]]) # Normalize vectors v /= np.sqrt(np.einsum('...i,...i', v, v)).reshape(-1, 1) b1 = b[1] / np.linalg.norm(b[1]) x = np.dot(v[0], v[1]) m = np.cross(v[0], b1) y = np.dot(m, v[1]) return np.arctan2(y, x)
def get_dihedral_vonMises(mol, conf, atom_idx, Z): Z = np.array(Z) v = np.zeros((2, 1)) iAtom = mol.GetAtomWithIdx(atom_idx[1]) jAtom = mol.GetAtomWithIdx(atom_idx[2]) k_0 = atom_idx[0] i = atom_idx[1] j = atom_idx[2] l_0 = atom_idx[3] for b1 in iAtom.GetBonds(): k = b1.GetOtherAtomIdx(i) if k == j: continue for b2 in jAtom.GetBonds(): l = b2.GetOtherAtomIdx(j) if l == i: continue assert k != l s_star = S_vec(GetDihedralFromPointCloud(Z, (k, i, j, l))) a_mat = A_transpose_matrix(GetDihedral(conf, (k, i, j, k_0)) + GetDihedral(conf, (l_0, i, j, l))) v = v + np.matmul(a_mat, s_star) v = v / np.linalg.norm(v) v = v.reshape(-1) return np.arctan2(v[1], v[0])
def get_von_mises_rms(mol, mol_rdkit, rotable_bonds, conf_id): new_dihedrals = np.zeros(len(rotable_bonds)) for idx, r in enumerate(rotable_bonds): new_dihedrals[idx] = get_dihedral_vonMises(mol_rdkit, mol_rdkit.GetConformer(conf_id), r, mol.GetConformer().GetPositions()) mol_rdkit = apply_changes(mol_rdkit, new_dihedrals, rotable_bonds, conf_id) return RMSD(mol_rdkit, mol, conf_id)
def mmff_func(mol): mol_mmff = copy.deepcopy(mol) AllChem.MMFFOptimizeMoleculeConfs(mol_mmff, mmffVariant='MMFF94s') for i in range(mol.GetNumConformers()): coords = mol_mmff.GetConformers()[i].GetPositions() for j in range(coords.shape[0]): mol.GetConformer(i).SetAtomPosition(j, Geometry.Point3D(*coords[j]))
RMSD = AllChem.AlignMol12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788import osfrom argparse import FileType, ArgumentParser
import numpy as npimport pandas as pdfrom Bio.PDB import PDBParserfrom Bio.Seq import Seqfrom Bio.SeqRecord import SeqRecordfrom tqdm import tqdmfrom Bio import SeqIO
def esm_embedding_prep(out_file, protein_path): biopython_parser = PDBParser()
three_to_one = { "ALA": "A", "ARG": "R", "ASN": "N", "ASP": "D", "CYS": "C", "GLN": "Q", "GLU": "E", "GLY": "G", "HIS": "H", "ILE": "I", "LEU": "L", "LYS": "K", "MET": "M", "MSE": "M", # MSE this is almost the same AA as MET. The sulfur is just replaced by Selen "PHE": "F", "PRO": "P", "PYL": "O", "SER": "S", "SEC": "U", "THR": "T", "TRP": "W", "TYR": "Y", "VAL": "V", "ASX": "B", "GLX": "Z", "XAA": "X", "XLE": "J", }
file_paths = [protein_path] sequences = [] ids = [] for file_path in tqdm(file_paths): structure = biopython_parser.get_structure("random_id", file_path) structure = structure[0] for i, chain in enumerate(structure): seq = "" for res_idx, residue in enumerate(chain): if residue.get_resname() == "HOH": continue residue_coords = [] c_alpha, n, c = None, None, None for atom in residue: if atom.name == "CA": c_alpha = list(atom.get_vector()) if atom.name == "N": n = list(atom.get_vector()) if atom.name == "C": c = list(atom.get_vector()) if ( c_alpha != None and n != None and c != None ): # only append residue if it is an amino acid try: seq += three_to_one[residue.get_resname()] except Exception as e: seq += "-" print( "encountered unknown AA: ", residue.get_resname(), " in the complex ", file_path, ". Replacing it with a dash - .", ) sequences.append(seq) ids.append(f"{os.path.basename(file_path)}_chain_{i}") records = [] for (index, seq) in zip(ids, sequences): record = SeqRecord(Seq(seq), str(index)) record.description = "" records.append(record) SeqIO.write(records, out_file, "fasta")1234567891011121314151617
import osfrom argparse import ArgumentParser
import torchfrom tqdm import tqdm
parser = ArgumentParser()parser.add_argument('--esm_embeddings_path', type=str, default='data/embeddings_output', help='')parser.add_argument('--output_path', type=str, default='data/esm2_3billion_embeddings.pt', help='')args = parser.parse_args()
dict = {}for filename in tqdm(os.listdir(args.esm_embeddings_path)): dict[filename.split('.')[0]] = torch.load(os.path.join(args.esm_embeddings_path,filename))['representations'][33]torch.save(dict,args.output_path)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705import binasciiimport globimport hashlibimport osimport picklefrom collections import defaultdictfrom multiprocessing import Poolimport randomimport copy
import numpy as npimport torchfrom rdkit.Chem import MolToSmiles, MolFromSmiles, AddHsfrom torch_geometric.data import Dataset, HeteroDatafrom torch_geometric.loader import DataLoader, DataListLoaderfrom torch_geometric.transforms import BaseTransformfrom tqdm import tqdm
from datasets.process_mols import ( read_molecule, get_rec_graph, generate_conformer, get_lig_graph_with_matching, extract_receptor_structure, parse_receptor, parse_pdb_from_path,)from utils.diffusion_utils import modify_conformer, set_timefrom utils.utils import read_strings_from_txtfrom utils import so3, torus
class NoiseTransform(BaseTransform): def __init__(self, t_to_sigma, no_torsion, all_atom): self.t_to_sigma = t_to_sigma self.no_torsion = no_torsion self.all_atom = all_atom
def __call__(self, data): t = np.random.uniform() t_tr, t_rot, t_tor = t, t, t return self.apply_noise(data, t_tr, t_rot, t_tor)
def apply_noise( self, data, t_tr, t_rot, t_tor, tr_update=None, rot_update=None, torsion_updates=None, ): if not torch.is_tensor(data["ligand"].pos): data["ligand"].pos = random.choice(data["ligand"].pos)
tr_sigma, rot_sigma, tor_sigma = self.t_to_sigma(t_tr, t_rot, t_tor) set_time(data, t_tr, t_rot, t_tor, 1, self.all_atom, device=None)
tr_update = ( torch.normal(mean=0, std=tr_sigma, size=(1, 3)) if tr_update is None else tr_update ) rot_update = so3.sample_vec(eps=rot_sigma) if rot_update is None else rot_update torsion_updates = ( np.random.normal( loc=0.0, scale=tor_sigma, size=data["ligand"].edge_mask.sum() ) if torsion_updates is None else torsion_updates ) torsion_updates = None if self.no_torsion else torsion_updates modify_conformer( data, tr_update, torch.from_numpy(rot_update).float(), torsion_updates )
data.tr_score = -tr_update / tr_sigma**2 data.rot_score = ( torch.from_numpy(so3.score_vec(vec=rot_update, eps=rot_sigma)) .float() .unsqueeze(0) ) data.tor_score = ( None if self.no_torsion else torch.from_numpy(torus.score(torsion_updates, tor_sigma)).float() ) data.tor_sigma_edge = ( None if self.no_torsion else np.ones(data["ligand"].edge_mask.sum()) * tor_sigma ) return data
class PDBBind(Dataset): def __init__( self, root, transform=None, cache_path="data/cache", split_path="data/", limit_complexes=0, receptor_radius=30, num_workers=1, c_alpha_max_neighbors=None, popsize=15, maxiter=15, matching=True, keep_original=False, max_lig_size=None, remove_hs=False, num_conformers=1, all_atoms=False, atom_radius=5, atom_max_neighbors=None, esm_embeddings_path=None, require_ligand=False, ligands_list=None, protein_path_list=None, ligand_descriptions=None, keep_local_structures=False, ):
super(PDBBind, self).__init__(root, transform) self.pdbbind_dir = root self.max_lig_size = max_lig_size self.split_path = split_path self.limit_complexes = limit_complexes self.receptor_radius = receptor_radius self.num_workers = num_workers self.c_alpha_max_neighbors = c_alpha_max_neighbors self.remove_hs = remove_hs self.esm_embeddings_path = esm_embeddings_path self.require_ligand = require_ligand self.protein_path_list = protein_path_list self.ligand_descriptions = ligand_descriptions self.keep_local_structures = keep_local_structures if ( matching or protein_path_list is not None and ligand_descriptions is not None ): cache_path += "_torsion" if all_atoms: cache_path += "_allatoms" self.full_cache_path = os.path.join( cache_path, f"limit{self.limit_complexes}" f"_INDEX{os.path.splitext(os.path.basename(self.split_path))[0]}" f"_maxLigSize{self.max_lig_size}_H{int(not self.remove_hs)}" f"_recRad{self.receptor_radius}_recMax{self.c_alpha_max_neighbors}" + ( "" if not all_atoms else f"_atomRad{atom_radius}_atomMax{atom_max_neighbors}" ) + ("" if not matching or num_conformers == 1 else f"_confs{num_conformers}") + ("" if self.esm_embeddings_path is None else f"_esmEmbeddings") + ("" if not keep_local_structures else f"_keptLocalStruct") + ( "" if protein_path_list is None or ligand_descriptions is None else str( binascii.crc32( "".join(ligand_descriptions + protein_path_list).encode() ) ) ), ) self.popsize, self.maxiter = popsize, maxiter self.matching, self.keep_original = matching, keep_original self.num_conformers = num_conformers self.all_atoms = all_atoms self.atom_radius, self.atom_max_neighbors = atom_radius, atom_max_neighbors if not os.path.exists( os.path.join(self.full_cache_path, "heterographs.pkl") ) or ( require_ligand and not os.path.exists( os.path.join(self.full_cache_path, "rdkit_ligands.pkl") ) ): os.makedirs(self.full_cache_path, exist_ok=True) if protein_path_list is None or ligand_descriptions is None: self.preprocessing() else: self.inference_preprocessing()
print( "loading data from memory: ", os.path.join(self.full_cache_path, "heterographs.pkl"), ) with open(os.path.join(self.full_cache_path, "heterographs.pkl"), "rb") as f: self.complex_graphs = pickle.load(f) if require_ligand: with open( os.path.join(self.full_cache_path, "rdkit_ligands.pkl"), "rb" ) as f: self.rdkit_ligands = pickle.load(f)
print_statistics(self.complex_graphs)
def len(self): return len(self.complex_graphs)
def get(self, idx): if self.require_ligand: complex_graph = copy.deepcopy(self.complex_graphs[idx]) complex_graph.mol = copy.deepcopy(self.rdkit_ligands[idx]) return complex_graph else: return copy.deepcopy(self.complex_graphs[idx])
def preprocessing(self): print( f"Processing complexes from [{self.split_path}] and saving it to [{self.full_cache_path}]" )
complex_names_all = read_strings_from_txt(self.split_path) if self.limit_complexes is not None and self.limit_complexes != 0: complex_names_all = complex_names_all[: self.limit_complexes] print(f"Loading {len(complex_names_all)} complexes.")
if self.esm_embeddings_path is not None: id_to_embeddings = torch.load(self.esm_embeddings_path) chain_embeddings_dictlist = defaultdict(list) for key, embedding in id_to_embeddings.items(): key_name = key.split("_")[0] if key_name in complex_names_all: chain_embeddings_dictlist[key_name].append(embedding) lm_embeddings_chains_all = [] for name in complex_names_all: lm_embeddings_chains_all.append(chain_embeddings_dictlist[name]) else: lm_embeddings_chains_all = [None] * len(complex_names_all)
if self.num_workers > 1: # running preprocessing in parallel on multiple workers and saving the progress every 1000 complexes for i in range(len(complex_names_all) // 1000 + 1): if os.path.exists( os.path.join(self.full_cache_path, f"heterographs{i}.pkl") ): continue complex_names = complex_names_all[1000 * i : 1000 * (i + 1)] lm_embeddings_chains = lm_embeddings_chains_all[ 1000 * i : 1000 * (i + 1) ] complex_graphs, rdkit_ligands = [], [] if self.num_workers > 1: p = Pool(self.num_workers, maxtasksperchild=1) p.__enter__() with tqdm( total=len(complex_names), desc=f"loading complexes {i}/{len(complex_names_all)//1000+1}", ) as pbar: map_fn = p.imap_unordered if self.num_workers > 1 else map for t in map_fn( self.get_complex, zip( complex_names, lm_embeddings_chains, [None] * len(complex_names), [None] * len(complex_names), ), ): complex_graphs.extend(t[0]) rdkit_ligands.extend(t[1]) pbar.update() if self.num_workers > 1: p.__exit__(None, None, None)
with open( os.path.join(self.full_cache_path, f"heterographs{i}.pkl"), "wb" ) as f: pickle.dump((complex_graphs), f) with open( os.path.join(self.full_cache_path, f"rdkit_ligands{i}.pkl"), "wb" ) as f: pickle.dump((rdkit_ligands), f)
complex_graphs_all = [] for i in range(len(complex_names_all) // 1000 + 1): with open( os.path.join(self.full_cache_path, f"heterographs{i}.pkl"), "rb" ) as f: l = pickle.load(f) complex_graphs_all.extend(l) with open( os.path.join(self.full_cache_path, f"heterographs.pkl"), "wb" ) as f: pickle.dump((complex_graphs_all), f)
rdkit_ligands_all = [] for i in range(len(complex_names_all) // 1000 + 1): with open( os.path.join(self.full_cache_path, f"rdkit_ligands{i}.pkl"), "rb" ) as f: l = pickle.load(f) rdkit_ligands_all.extend(l) with open( os.path.join(self.full_cache_path, f"rdkit_ligands.pkl"), "wb" ) as f: pickle.dump((rdkit_ligands_all), f) else: complex_graphs, rdkit_ligands = [], [] with tqdm(total=len(complex_names_all), desc="loading complexes") as pbar: for t in map( self.get_complex, zip( complex_names_all, lm_embeddings_chains_all, [None] * len(complex_names_all), [None] * len(complex_names_all), ), ): complex_graphs.extend(t[0]) rdkit_ligands.extend(t[1]) pbar.update() with open( os.path.join(self.full_cache_path, "heterographs.pkl"), "wb" ) as f: pickle.dump((complex_graphs), f) with open( os.path.join(self.full_cache_path, "rdkit_ligands.pkl"), "wb" ) as f: pickle.dump((rdkit_ligands), f)
def inference_preprocessing(self): ligands_list = [] print("Reading molecules and generating local structures with RDKit") for ligand_description in tqdm(self.ligand_descriptions): mol = MolFromSmiles(ligand_description) # check if it is a smiles or a path if mol is not None: mol = AddHs(mol) generate_conformer(mol) ligands_list.append(mol) else: mol = read_molecule(ligand_description, remove_hs=False, sanitize=True) if not self.keep_local_structures: mol.RemoveAllConformers() mol = AddHs(mol) generate_conformer(mol) ligands_list.append(mol)
if self.esm_embeddings_path is not None: print("Reading language model embeddings.") lm_embeddings_chains_all = [] if not os.path.exists(self.esm_embeddings_path): raise Exception( "ESM embeddings path does not exist: ", self.esm_embeddings_path ) for protein_path in self.protein_path_list: embeddings_paths = sorted( glob.glob( os.path.join( self.esm_embeddings_path, os.path.basename(protein_path) ) + "*" ) ) lm_embeddings_chains = [] for embeddings_path in embeddings_paths: lm_embeddings_chains.append( torch.load(embeddings_path)["representations"][33] ) lm_embeddings_chains_all.append(lm_embeddings_chains) else: lm_embeddings_chains_all = [None] * len(self.protein_path_list)
print("Generating graphs for ligands and proteins") if self.num_workers > 1: # running preprocessing in parallel on multiple workers and saving the progress every 1000 complexes for i in range(len(self.protein_path_list) // 1000 + 1): if os.path.exists( os.path.join(self.full_cache_path, f"heterographs{i}.pkl") ): continue protein_paths_chunk = self.protein_path_list[1000 * i : 1000 * (i + 1)] ligand_description_chunk = self.ligand_descriptions[ 1000 * i : 1000 * (i + 1) ] ligands_chunk = ligands_list[1000 * i : 1000 * (i + 1)] lm_embeddings_chains = lm_embeddings_chains_all[ 1000 * i : 1000 * (i + 1) ] complex_graphs, rdkit_ligands = [], [] if self.num_workers > 1: p = Pool(self.num_workers, maxtasksperchild=1) p.__enter__() with tqdm( total=len(protein_paths_chunk), desc=f"loading complexes {i}/{len(protein_paths_chunk)//1000+1}", ) as pbar: map_fn = p.imap_unordered if self.num_workers > 1 else map for t in map_fn( self.get_complex, zip( protein_paths_chunk, lm_embeddings_chains, ligands_chunk, ligand_description_chunk, ), ): complex_graphs.extend(t[0]) rdkit_ligands.extend(t[1]) pbar.update() if self.num_workers > 1: p.__exit__(None, None, None)
with open( os.path.join(self.full_cache_path, f"heterographs{i}.pkl"), "wb" ) as f: pickle.dump((complex_graphs), f) with open( os.path.join(self.full_cache_path, f"rdkit_ligands{i}.pkl"), "wb" ) as f: pickle.dump((rdkit_ligands), f)
complex_graphs_all = [] for i in range(len(self.protein_path_list) // 1000 + 1): with open( os.path.join(self.full_cache_path, f"heterographs{i}.pkl"), "rb" ) as f: l = pickle.load(f) complex_graphs_all.extend(l) with open( os.path.join(self.full_cache_path, f"heterographs.pkl"), "wb" ) as f: pickle.dump((complex_graphs_all), f)
rdkit_ligands_all = [] for i in range(len(self.protein_path_list) // 1000 + 1): with open( os.path.join(self.full_cache_path, f"rdkit_ligands{i}.pkl"), "rb" ) as f: l = pickle.load(f) rdkit_ligands_all.extend(l) with open( os.path.join(self.full_cache_path, f"rdkit_ligands.pkl"), "wb" ) as f: pickle.dump((rdkit_ligands_all), f) else: complex_graphs, rdkit_ligands = [], [] with tqdm( total=len(self.protein_path_list), desc="loading complexes" ) as pbar: for t in map( self.get_complex, zip( self.protein_path_list, lm_embeddings_chains_all, ligands_list, self.ligand_descriptions, ), ): complex_graphs.extend(t[0]) rdkit_ligands.extend(t[1]) pbar.update() with open( os.path.join(self.full_cache_path, "heterographs.pkl"), "wb" ) as f: pickle.dump((complex_graphs), f) with open( os.path.join(self.full_cache_path, "rdkit_ligands.pkl"), "wb" ) as f: pickle.dump((rdkit_ligands), f)
def get_complex(self, par): name, lm_embedding_chains, ligand, ligand_description = par if not os.path.exists(os.path.join(self.pdbbind_dir, name)) and ligand is None: print("Folder not found", name) return [], []
if ligand is not None: rec_model = parse_pdb_from_path(name) name = f"{name}____{ligand_description}" ligs = [ligand] else: try: rec_model = parse_receptor(name, self.pdbbind_dir) except Exception as e: print(f"Skipping {name} because of the error:") print(e) return [], []
ligs = read_mols(self.pdbbind_dir, name, remove_hs=False) complex_graphs = [] for i, lig in enumerate(ligs): if ( self.max_lig_size is not None and lig.GetNumHeavyAtoms() > self.max_lig_size ): print( f"Ligand with {lig.GetNumHeavyAtoms()} heavy atoms is larger than max_lig_size {self.max_lig_size}. Not including {name} in preprocessed data." ) continue complex_graph = HeteroData() complex_graph["name"] = name try: get_lig_graph_with_matching( lig, complex_graph, self.popsize, self.maxiter, self.matching, self.keep_original, self.num_conformers, remove_hs=self.remove_hs, ) print(lm_embedding_chains) ( rec, rec_coords, c_alpha_coords, n_coords, c_coords, lm_embeddings, ) = extract_receptor_structure( copy.deepcopy(rec_model), lig, lm_embedding_chains=lm_embedding_chains, ) if lm_embeddings is not None and len(c_alpha_coords) != len( lm_embeddings ): print( f"LM embeddings for complex {name} did not have the right length for the protein. Skipping {name}." ) continue
get_rec_graph( rec, rec_coords, c_alpha_coords, n_coords, c_coords, complex_graph, rec_radius=self.receptor_radius, c_alpha_max_neighbors=self.c_alpha_max_neighbors, all_atoms=self.all_atoms, atom_radius=self.atom_radius, atom_max_neighbors=self.atom_max_neighbors, remove_hs=self.remove_hs, lm_embeddings=lm_embeddings, )
except Exception as e: print(f"Skipping {name} because of the error:") print(e) raise e continue
protein_center = torch.mean( complex_graph["receptor"].pos, dim=0, keepdim=True ) complex_graph["receptor"].pos -= protein_center if self.all_atoms: complex_graph["atom"].pos -= protein_center
if (not self.matching) or self.num_conformers == 1: complex_graph["ligand"].pos -= protein_center else: for p in complex_graph["ligand"].pos: p -= protein_center
complex_graph.original_center = protein_center complex_graphs.append(complex_graph) return complex_graphs, ligs
def print_statistics(complex_graphs): statistics = ([], [], [], [])
for complex_graph in complex_graphs: lig_pos = ( complex_graph["ligand"].pos if torch.is_tensor(complex_graph["ligand"].pos) else complex_graph["ligand"].pos[0] ) radius_protein = torch.max( torch.linalg.vector_norm(complex_graph["receptor"].pos, dim=1) ) molecule_center = torch.mean(lig_pos, dim=0) radius_molecule = torch.max( torch.linalg.vector_norm(lig_pos - molecule_center.unsqueeze(0), dim=1) ) distance_center = torch.linalg.vector_norm(molecule_center) statistics[0].append(radius_protein) statistics[1].append(radius_molecule) statistics[2].append(distance_center) if "rmsd_matching" in complex_graph: statistics[3].append(complex_graph.rmsd_matching) else: statistics[3].append(0)
name = [ "radius protein", "radius molecule", "distance protein-mol", "rmsd matching", ] print("Number of complexes: ", len(complex_graphs)) for i in range(4): array = np.asarray(statistics[i]) print( f"{name[i]}: mean {np.mean(array)}, std {np.std(array)}, max {np.max(array)}" )
def construct_loader(args, t_to_sigma): transform = NoiseTransform( t_to_sigma=t_to_sigma, no_torsion=args.no_torsion, all_atom=args.all_atoms )
common_args = { "transform": transform, "root": args.data_dir, "limit_complexes": args.limit_complexes, "receptor_radius": args.receptor_radius, "c_alpha_max_neighbors": args.c_alpha_max_neighbors, "remove_hs": args.remove_hs, "max_lig_size": args.max_lig_size, "matching": not args.no_torsion, "popsize": args.matching_popsize, "maxiter": args.matching_maxiter, "num_workers": args.num_workers, "all_atoms": args.all_atoms, "atom_radius": args.atom_radius, "atom_max_neighbors": args.atom_max_neighbors, "esm_embeddings_path": args.esm_embeddings_path, }
train_dataset = PDBBind( cache_path=args.cache_path, split_path=args.split_train, keep_original=True, num_conformers=args.num_conformers, **common_args, ) val_dataset = PDBBind( cache_path=args.cache_path, split_path=args.split_val, keep_original=True, **common_args, )
loader_class = DataListLoader if torch.cuda.is_available() else DataLoader train_loader = loader_class( dataset=train_dataset, batch_size=args.batch_size, num_workers=args.num_dataloader_workers, shuffle=True, pin_memory=args.pin_memory, ) val_loader = loader_class( dataset=val_dataset, batch_size=args.batch_size, num_workers=args.num_dataloader_workers, shuffle=True, pin_memory=args.pin_memory, )
return train_loader, val_loader
def read_mol(pdbbind_dir, name, remove_hs=False): lig = read_molecule( os.path.join(pdbbind_dir, name, f"{name}_ligand.sdf"), remove_hs=remove_hs, sanitize=True, ) if lig is None: # read mol2 file if sdf file cannot be sanitized lig = read_molecule( os.path.join(pdbbind_dir, name, f"{name}_ligand.mol2"), remove_hs=remove_hs, sanitize=True, ) return lig
def read_mols(pdbbind_dir, name, remove_hs=False): ligs = [] for file in os.listdir(os.path.join(pdbbind_dir, name)): if file.endswith(".sdf") and "rdkit" not in file: lig = read_molecule( os.path.join(pdbbind_dir, name, file), remove_hs=remove_hs, sanitize=True, ) if lig is None and os.path.exists( os.path.join(pdbbind_dir, name, file[:-4] + ".mol2") ): # read mol2 file if sdf file cannot be sanitized print( "Using the .sdf file failed. We found a .mol2 file instead and are trying to use that." ) lig = read_molecule( os.path.join(pdbbind_dir, name, file[:-4] + ".mol2"), remove_hs=remove_hs, sanitize=True, ) if lig is not None: ligs.append(lig) return ligs12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394import osfrom argparse import FileType, ArgumentParser
import numpy as npfrom Bio.PDB import PDBParserfrom Bio.Seq import Seqfrom Bio.SeqRecord import SeqRecordfrom tqdm import tqdm
parser = ArgumentParser()parser.add_argument('--data_dir', type=str, default='data/PDBBind_processed', help='')parser.add_argument('--chain_cutoff', type=int, default=10, help='')parser.add_argument('--out_file', type=str, default="data/pdbbind_sequences.fasta")args = parser.parse_args()
cutoff = args.chain_cutoffdata_dir = args.data_dirnames = os.listdir(data_dir)#%%from Bio import SeqIObiopython_parser = PDBParser()
three_to_one = {'ALA': 'A','ARG': 'R','ASN': 'N','ASP': 'D','CYS': 'C','GLN': 'Q','GLU': 'E','GLY': 'G','HIS': 'H','ILE': 'I','LEU': 'L','LYS': 'K','MET': 'M','MSE': 'M', # this is almost the same AA as MET. The sulfur is just replaced by Selen'PHE': 'F','PRO': 'P','PYL': 'O','SER': 'S','SEC': 'U','THR': 'T','TRP': 'W','TYR': 'Y','VAL': 'V','ASX': 'B','GLX': 'Z','XAA': 'X','XLE': 'J'}
sequences = []ids = []for name in tqdm(names): if name == '.DS_Store': continue if os.path.exists(os.path.join(data_dir, name, f'{name}_protein_processed.pdb')): rec_path = os.path.join(data_dir, name, f'{name}_protein_processed.pdb') else: rec_path = os.path.join(data_dir, name, f'{name}_protein.pdb') if cutoff > 10: rec_path = os.path.join(data_dir, name, f'{name}_protein_obabel_reduce.pdb') if not os.path.exists(rec_path): rec_path = os.path.join(data_dir, name, f'{name}_protein.pdb') structure = biopython_parser.get_structure('random_id', rec_path) structure = structure[0] for i, chain in enumerate(structure): seq = '' for res_idx, residue in enumerate(chain): if residue.get_resname() == 'HOH': continue residue_coords = [] c_alpha, n, c = None, None, None for atom in residue: if atom.name == 'CA': c_alpha = list(atom.get_vector()) if atom.name == 'N': n = list(atom.get_vector()) if atom.name == 'C': c = list(atom.get_vector()) if c_alpha != None and n != None and c != None: # only append residue if it is an amino acid and not try: seq += three_to_one[residue.get_resname()] except Exception as e: seq += '-' print("encountered unknown AA: ", residue.get_resname(), ' in the complex ', name, '. Replacing it with a dash - .') sequences.append(seq) ids.append(f'{name}_chain_{i}')records = []for (index, seq) in zip(ids,sequences): record = SeqRecord(Seq(seq), str(index)) record.description = '' records.append(record)SeqIO.write(records, args.out_file, "fasta")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550import copyimport osimport warnings
import numpy as npimport scipy.spatial as spaimport torchfrom Bio.PDB import PDBParserfrom Bio.PDB.PDBExceptions import PDBConstructionWarningfrom rdkit import Chemfrom rdkit.Chem.rdchem import BondType as BTfrom rdkit.Chem import AllChem, GetPeriodicTable, RemoveHsfrom rdkit.Geometry import Point3Dfrom scipy import spatialfrom scipy.special import softmaxfrom torch_cluster import radius_graph
import torch.nn.functional as F
from datasets.conformer_matching import get_torsion_angles, optimize_rotatable_bondsfrom utils.torsion import get_transformation_mask
biopython_parser = PDBParser()periodic_table = GetPeriodicTable()allowable_features = { 'possible_atomic_num_list': list(range(1, 119)) + ['misc'], 'possible_chirality_list': [ 'CHI_UNSPECIFIED', 'CHI_TETRAHEDRAL_CW', 'CHI_TETRAHEDRAL_CCW', 'CHI_OTHER' ], 'possible_degree_list': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'misc'], 'possible_numring_list': [0, 1, 2, 3, 4, 5, 6, 'misc'], 'possible_implicit_valence_list': [0, 1, 2, 3, 4, 5, 6, 'misc'], 'possible_formal_charge_list': [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 'misc'], 'possible_numH_list': [0, 1, 2, 3, 4, 5, 6, 7, 8, 'misc'], 'possible_number_radical_e_list': [0, 1, 2, 3, 4, 'misc'], 'possible_hybridization_list': [ 'SP', 'SP2', 'SP3', 'SP3D', 'SP3D2', 'misc' ], 'possible_is_aromatic_list': [False, True], 'possible_is_in_ring3_list': [False, True], 'possible_is_in_ring4_list': [False, True], 'possible_is_in_ring5_list': [False, True], 'possible_is_in_ring6_list': [False, True], 'possible_is_in_ring7_list': [False, True], 'possible_is_in_ring8_list': [False, True], 'possible_amino_acids': ['ALA', 'ARG', 'ASN', 'ASP', 'CYS', 'GLN', 'GLU', 'GLY', 'HIS', 'ILE', 'LEU', 'LYS', 'MET', 'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL', 'HIP', 'HIE', 'TPO', 'HID', 'LEV', 'MEU', 'PTR', 'GLV', 'CYT', 'SEP', 'HIZ', 'CYM', 'GLM', 'ASQ', 'TYS', 'CYX', 'GLZ', 'misc'], 'possible_atom_type_2': ['C*', 'CA', 'CB', 'CD', 'CE', 'CG', 'CH', 'CZ', 'N*', 'ND', 'NE', 'NH', 'NZ', 'O*', 'OD', 'OE', 'OG', 'OH', 'OX', 'S*', 'SD', 'SG', 'misc'], 'possible_atom_type_3': ['C', 'CA', 'CB', 'CD', 'CD1', 'CD2', 'CE', 'CE1', 'CE2', 'CE3', 'CG', 'CG1', 'CG2', 'CH2', 'CZ', 'CZ2', 'CZ3', 'N', 'ND1', 'ND2', 'NE', 'NE1', 'NE2', 'NH1', 'NH2', 'NZ', 'O', 'OD1', 'OD2', 'OE1', 'OE2', 'OG', 'OG1', 'OH', 'OXT', 'SD', 'SG', 'misc'],}bonds = {BT.SINGLE: 0, BT.DOUBLE: 1, BT.TRIPLE: 2, BT.AROMATIC: 3}
lig_feature_dims = (list(map(len, [ allowable_features['possible_atomic_num_list'], allowable_features['possible_chirality_list'], allowable_features['possible_degree_list'], allowable_features['possible_formal_charge_list'], allowable_features['possible_implicit_valence_list'], allowable_features['possible_numH_list'], allowable_features['possible_number_radical_e_list'], allowable_features['possible_hybridization_list'], allowable_features['possible_is_aromatic_list'], allowable_features['possible_numring_list'], allowable_features['possible_is_in_ring3_list'], allowable_features['possible_is_in_ring4_list'], allowable_features['possible_is_in_ring5_list'], allowable_features['possible_is_in_ring6_list'], allowable_features['possible_is_in_ring7_list'], allowable_features['possible_is_in_ring8_list'],])), 0) # number of scalar features
rec_atom_feature_dims = (list(map(len, [ allowable_features['possible_amino_acids'], allowable_features['possible_atomic_num_list'], allowable_features['possible_atom_type_2'], allowable_features['possible_atom_type_3'],])), 0)
rec_residue_feature_dims = (list(map(len, [ allowable_features['possible_amino_acids']])), 0)
def lig_atom_featurizer(mol): ringinfo = mol.GetRingInfo() atom_features_list = [] for idx, atom in enumerate(mol.GetAtoms()): atom_features_list.append([ safe_index(allowable_features['possible_atomic_num_list'], atom.GetAtomicNum()), allowable_features['possible_chirality_list'].index(str(atom.GetChiralTag())), safe_index(allowable_features['possible_degree_list'], atom.GetTotalDegree()), safe_index(allowable_features['possible_formal_charge_list'], atom.GetFormalCharge()), safe_index(allowable_features['possible_implicit_valence_list'], atom.GetImplicitValence()), safe_index(allowable_features['possible_numH_list'], atom.GetTotalNumHs()), safe_index(allowable_features['possible_number_radical_e_list'], atom.GetNumRadicalElectrons()), safe_index(allowable_features['possible_hybridization_list'], str(atom.GetHybridization())), allowable_features['possible_is_aromatic_list'].index(atom.GetIsAromatic()), safe_index(allowable_features['possible_numring_list'], ringinfo.NumAtomRings(idx)), allowable_features['possible_is_in_ring3_list'].index(ringinfo.IsAtomInRingOfSize(idx, 3)), allowable_features['possible_is_in_ring4_list'].index(ringinfo.IsAtomInRingOfSize(idx, 4)), allowable_features['possible_is_in_ring5_list'].index(ringinfo.IsAtomInRingOfSize(idx, 5)), allowable_features['possible_is_in_ring6_list'].index(ringinfo.IsAtomInRingOfSize(idx, 6)), allowable_features['possible_is_in_ring7_list'].index(ringinfo.IsAtomInRingOfSize(idx, 7)), allowable_features['possible_is_in_ring8_list'].index(ringinfo.IsAtomInRingOfSize(idx, 8)), ])
return torch.tensor(atom_features_list)
def rec_residue_featurizer(rec): feature_list = [] for residue in rec.get_residues(): feature_list.append([safe_index(allowable_features['possible_amino_acids'], residue.get_resname())]) return torch.tensor(feature_list, dtype=torch.float32) # (N_res, 1)
def safe_index(l, e): """ Return index of element e in list l. If e is not present, return the last index """ try: return l.index(e) except: return len(l) - 1
def parse_receptor(pdbid, pdbbind_dir): rec = parsePDB(pdbid, pdbbind_dir) return rec
def parsePDB(pdbid, pdbbind_dir): rec_path = os.path.join(pdbbind_dir, pdbid, f'{pdbid}_protein_processed.pdb') return parse_pdb_from_path(rec_path)
def parse_pdb_from_path(path): with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=PDBConstructionWarning) structure = biopython_parser.get_structure('random_id', path) rec = structure[0] return rec
def extract_receptor_structure(rec, lig, lm_embedding_chains=None): conf = lig.GetConformer() lig_coords = conf.GetPositions() min_distances = [] coords = [] c_alpha_coords = [] n_coords = [] c_coords = [] valid_chain_ids = [] lengths = [] for i, chain in enumerate(rec): chain_coords = [] # num_residues, num_atoms, 3 chain_c_alpha_coords = [] chain_n_coords = [] chain_c_coords = [] count = 0 invalid_res_ids = [] for res_idx, residue in enumerate(chain): if residue.get_resname() == 'HOH': invalid_res_ids.append(residue.get_id()) continue residue_coords = [] c_alpha, n, c = None, None, None for atom in residue: if atom.name == 'CA': c_alpha = list(atom.get_vector()) if atom.name == 'N': n = list(atom.get_vector()) if atom.name == 'C': c = list(atom.get_vector()) residue_coords.append(list(atom.get_vector()))
if c_alpha != None and n != None and c != None: # only append residue if it is an amino acid and not some weird molecule that is part of the complex chain_c_alpha_coords.append(c_alpha) chain_n_coords.append(n) chain_c_coords.append(c) chain_coords.append(np.array(residue_coords)) count += 1 else: invalid_res_ids.append(residue.get_id()) for res_id in invalid_res_ids: chain.detach_child(res_id) if len(chain_coords) > 0: all_chain_coords = np.concatenate(chain_coords, axis=0) distances = spatial.distance.cdist(lig_coords, all_chain_coords) min_distance = distances.min() else: min_distance = np.inf
min_distances.append(min_distance) lengths.append(count) coords.append(chain_coords) c_alpha_coords.append(np.array(chain_c_alpha_coords)) n_coords.append(np.array(chain_n_coords)) c_coords.append(np.array(chain_c_coords)) if not count == 0: valid_chain_ids.append(chain.get_id())
min_distances = np.array(min_distances) if len(valid_chain_ids) == 0: valid_chain_ids.append(np.argmin(min_distances)) valid_coords = [] valid_c_alpha_coords = [] valid_n_coords = [] valid_c_coords = [] valid_lengths = [] invalid_chain_ids = [] valid_lm_embeddings = [] for i, chain in enumerate(rec): if chain.get_id() in valid_chain_ids: valid_coords.append(coords[i]) valid_c_alpha_coords.append(c_alpha_coords[i]) if lm_embedding_chains is not None: if i >= len(lm_embedding_chains): raise ValueError('Encountered valid chain id that was not present in the LM embeddings') valid_lm_embeddings.append(lm_embedding_chains[i]) valid_n_coords.append(n_coords[i]) valid_c_coords.append(c_coords[i]) valid_lengths.append(lengths[i]) else: invalid_chain_ids.append(chain.get_id()) coords = [item for sublist in valid_coords for item in sublist] # list with n_residues arrays: [n_atoms, 3]
c_alpha_coords = np.concatenate(valid_c_alpha_coords, axis=0) # [n_residues, 3] n_coords = np.concatenate(valid_n_coords, axis=0) # [n_residues, 3] c_coords = np.concatenate(valid_c_coords, axis=0) # [n_residues, 3] lm_embeddings = np.concatenate(valid_lm_embeddings, axis=0) if lm_embedding_chains is not None else None for invalid_id in invalid_chain_ids: rec.detach_child(invalid_id)
assert len(c_alpha_coords) == len(n_coords) assert len(c_alpha_coords) == len(c_coords) assert sum(valid_lengths) == len(c_alpha_coords) return rec, coords, c_alpha_coords, n_coords, c_coords, lm_embeddings
def get_lig_graph(mol, complex_graph): lig_coords = torch.from_numpy(mol.GetConformer().GetPositions()).float() atom_feats = lig_atom_featurizer(mol)
row, col, edge_type = [], [], [] for bond in mol.GetBonds(): start, end = bond.GetBeginAtomIdx(), bond.GetEndAtomIdx() row += [start, end] col += [end, start] edge_type += 2 * [bonds[bond.GetBondType()]] if bond.GetBondType() != BT.UNSPECIFIED else [0, 0]
edge_index = torch.tensor([row, col], dtype=torch.long) edge_type = torch.tensor(edge_type, dtype=torch.long) edge_attr = F.one_hot(edge_type, num_classes=len(bonds)).to(torch.float)
complex_graph['ligand'].x = atom_feats complex_graph['ligand'].pos = lig_coords complex_graph['ligand', 'lig_bond', 'ligand'].edge_index = edge_index complex_graph['ligand', 'lig_bond', 'ligand'].edge_attr = edge_attr return
def generate_conformer(mol): ps = AllChem.ETKDGv2() id = AllChem.EmbedMolecule(mol, ps) if id == -1: print('rdkit coords could not be generated without using random coords. using random coords now.') ps.useRandomCoords = True AllChem.EmbedMolecule(mol, ps) AllChem.MMFFOptimizeMolecule(mol, confId=0) # else: # AllChem.MMFFOptimizeMolecule(mol_rdkit, confId=0)
def get_lig_graph_with_matching(mol_, complex_graph, popsize, maxiter, matching, keep_original, num_conformers, remove_hs): if matching: mol_maybe_noh = copy.deepcopy(mol_) if remove_hs: mol_maybe_noh = RemoveHs(mol_maybe_noh, sanitize=True) if keep_original: complex_graph['ligand'].orig_pos = mol_maybe_noh.GetConformer().GetPositions()
rotable_bonds = get_torsion_angles(mol_maybe_noh) if not rotable_bonds: print("no_rotable_bonds but still using it")
for i in range(num_conformers): mol_rdkit = copy.deepcopy(mol_)
mol_rdkit.RemoveAllConformers() mol_rdkit = AllChem.AddHs(mol_rdkit) generate_conformer(mol_rdkit) if remove_hs: mol_rdkit = RemoveHs(mol_rdkit, sanitize=True) mol = copy.deepcopy(mol_maybe_noh) if rotable_bonds: optimize_rotatable_bonds(mol_rdkit, mol, rotable_bonds, popsize=popsize, maxiter=maxiter) mol.AddConformer(mol_rdkit.GetConformer()) rms_list = [] AllChem.AlignMolConformers(mol, RMSlist=rms_list) mol_rdkit.RemoveAllConformers() mol_rdkit.AddConformer(mol.GetConformers()[1])
if i == 0: complex_graph.rmsd_matching = rms_list[0] get_lig_graph(mol_rdkit, complex_graph) else: if torch.is_tensor(complex_graph['ligand'].pos): complex_graph['ligand'].pos = [complex_graph['ligand'].pos] complex_graph['ligand'].pos.append(torch.from_numpy(mol_rdkit.GetConformer().GetPositions()).float())
else: # no matching complex_graph.rmsd_matching = 0 if remove_hs: mol_ = RemoveHs(mol_) get_lig_graph(mol_, complex_graph)
edge_mask, mask_rotate = get_transformation_mask(complex_graph) complex_graph['ligand'].edge_mask = torch.tensor(edge_mask) complex_graph['ligand'].mask_rotate = mask_rotate
return
def get_calpha_graph(rec, c_alpha_coords, n_coords, c_coords, complex_graph, cutoff=20, max_neighbor=None, lm_embeddings=None): n_rel_pos = n_coords - c_alpha_coords c_rel_pos = c_coords - c_alpha_coords num_residues = len(c_alpha_coords) if num_residues <= 1: raise ValueError(f"rec contains only 1 residue!")
# Build the k-NN graph distances = spa.distance.cdist(c_alpha_coords, c_alpha_coords) src_list = [] dst_list = [] mean_norm_list = [] for i in range(num_residues): dst = list(np.where(distances[i, :] < cutoff)[0]) dst.remove(i) if max_neighbor != None and len(dst) > max_neighbor: dst = list(np.argsort(distances[i, :]))[1: max_neighbor + 1] if len(dst) == 0: dst = list(np.argsort(distances[i, :]))[1:2] # choose second because first is i itself print(f'The c_alpha_cutoff {cutoff} was too small for one c_alpha such that it had no neighbors. ' f'So we connected it to the closest other c_alpha') assert i not in dst src = [i] * len(dst) src_list.extend(src) dst_list.extend(dst) valid_dist = list(distances[i, dst]) valid_dist_np = distances[i, dst] sigma = np.array([1., 2., 5., 10., 30.]).reshape((-1, 1)) weights = softmax(- valid_dist_np.reshape((1, -1)) ** 2 / sigma, axis=1) # (sigma_num, neigh_num) assert weights[0].sum() > 1 - 1e-2 and weights[0].sum() < 1.01 diff_vecs = c_alpha_coords[src, :] - c_alpha_coords[dst, :] # (neigh_num, 3) mean_vec = weights.dot(diff_vecs) # (sigma_num, 3) denominator = weights.dot(np.linalg.norm(diff_vecs, axis=1)) # (sigma_num,) mean_vec_ratio_norm = np.linalg.norm(mean_vec, axis=1) / denominator # (sigma_num,) mean_norm_list.append(mean_vec_ratio_norm) assert len(src_list) == len(dst_list)
node_feat = rec_residue_featurizer(rec) mu_r_norm = torch.from_numpy(np.array(mean_norm_list).astype(np.float32)) side_chain_vecs = torch.from_numpy( np.concatenate([np.expand_dims(n_rel_pos, axis=1), np.expand_dims(c_rel_pos, axis=1)], axis=1))
complex_graph['receptor'].x = torch.cat([node_feat, torch.tensor(lm_embeddings)], axis=1) if lm_embeddings is not None else node_feat complex_graph['receptor'].pos = torch.from_numpy(c_alpha_coords).float() complex_graph['receptor'].mu_r_norm = mu_r_norm complex_graph['receptor'].side_chain_vecs = side_chain_vecs.float() complex_graph['receptor', 'rec_contact', 'receptor'].edge_index = torch.from_numpy(np.asarray([src_list, dst_list]))
return
def rec_atom_featurizer(rec): atom_feats = [] for i, atom in enumerate(rec.get_atoms()): atom_name, element = atom.name, atom.element if element == 'CD': element = 'C' assert not element == '' try: atomic_num = periodic_table.GetAtomicNumber(element) except: atomic_num = -1 atom_feat = [safe_index(allowable_features['possible_amino_acids'], atom.get_parent().get_resname()), safe_index(allowable_features['possible_atomic_num_list'], atomic_num), safe_index(allowable_features['possible_atom_type_2'], (atom_name + '*')[:2]), safe_index(allowable_features['possible_atom_type_3'], atom_name)] atom_feats.append(atom_feat)
return atom_feats
def get_rec_graph(rec, rec_coords, c_alpha_coords, n_coords, c_coords, complex_graph, rec_radius, c_alpha_max_neighbors=None, all_atoms=False, atom_radius=5, atom_max_neighbors=None, remove_hs=False, lm_embeddings=None): if all_atoms: return get_fullrec_graph(rec, rec_coords, c_alpha_coords, n_coords, c_coords, complex_graph, c_alpha_cutoff=rec_radius, c_alpha_max_neighbors=c_alpha_max_neighbors, atom_cutoff=atom_radius, atom_max_neighbors=atom_max_neighbors, remove_hs=remove_hs,lm_embeddings=lm_embeddings) else: return get_calpha_graph(rec, c_alpha_coords, n_coords, c_coords, complex_graph, rec_radius, c_alpha_max_neighbors,lm_embeddings=lm_embeddings)
def get_fullrec_graph(rec, rec_coords, c_alpha_coords, n_coords, c_coords, complex_graph, c_alpha_cutoff=20, c_alpha_max_neighbors=None, atom_cutoff=5, atom_max_neighbors=None, remove_hs=False, lm_embeddings=None): # builds the receptor graph with both residues and atoms
n_rel_pos = n_coords - c_alpha_coords c_rel_pos = c_coords - c_alpha_coords num_residues = len(c_alpha_coords) if num_residues <= 1: raise ValueError(f"rec contains only 1 residue!")
# Build the k-NN graph of residues distances = spa.distance.cdist(c_alpha_coords, c_alpha_coords) src_list = [] dst_list = [] mean_norm_list = [] for i in range(num_residues): dst = list(np.where(distances[i, :] < c_alpha_cutoff)[0]) dst.remove(i) if c_alpha_max_neighbors != None and len(dst) > c_alpha_max_neighbors: dst = list(np.argsort(distances[i, :]))[1: c_alpha_max_neighbors + 1] if len(dst) == 0: dst = list(np.argsort(distances[i, :]))[1:2] # choose second because first is i itself print(f'The c_alpha_cutoff {c_alpha_cutoff} was too small for one c_alpha such that it had no neighbors. ' f'So we connected it to the closest other c_alpha') assert i not in dst src = [i] * len(dst) src_list.extend(src) dst_list.extend(dst) valid_dist = list(distances[i, dst]) valid_dist_np = distances[i, dst] sigma = np.array([1., 2., 5., 10., 30.]).reshape((-1, 1)) weights = softmax(- valid_dist_np.reshape((1, -1)) ** 2 / sigma, axis=1) # (sigma_num, neigh_num) assert 1 - 1e-2 < weights[0].sum() < 1.01 diff_vecs = c_alpha_coords[src, :] - c_alpha_coords[dst, :] # (neigh_num, 3) mean_vec = weights.dot(diff_vecs) # (sigma_num, 3) denominator = weights.dot(np.linalg.norm(diff_vecs, axis=1)) # (sigma_num,) mean_vec_ratio_norm = np.linalg.norm(mean_vec, axis=1) / denominator # (sigma_num,) mean_norm_list.append(mean_vec_ratio_norm) assert len(src_list) == len(dst_list)
node_feat = rec_residue_featurizer(rec) mu_r_norm = torch.from_numpy(np.array(mean_norm_list).astype(np.float32)) side_chain_vecs = torch.from_numpy( np.concatenate([np.expand_dims(n_rel_pos, axis=1), np.expand_dims(c_rel_pos, axis=1)], axis=1))
complex_graph['receptor'].x = torch.cat([node_feat, torch.tensor(lm_embeddings)], axis=1) if lm_embeddings is not None else node_feat complex_graph['receptor'].pos = torch.from_numpy(c_alpha_coords).float() complex_graph['receptor'].mu_r_norm = mu_r_norm complex_graph['receptor'].side_chain_vecs = side_chain_vecs.float() complex_graph['receptor', 'rec_contact', 'receptor'].edge_index = torch.from_numpy(np.asarray([src_list, dst_list]))
src_c_alpha_idx = np.concatenate([np.asarray([i]*len(l)) for i, l in enumerate(rec_coords)]) atom_feat = torch.from_numpy(np.asarray(rec_atom_featurizer(rec))) atom_coords = torch.from_numpy(np.concatenate(rec_coords, axis=0)).float()
if remove_hs: not_hs = (atom_feat[:, 1] != 0) src_c_alpha_idx = src_c_alpha_idx[not_hs] atom_feat = atom_feat[not_hs] atom_coords = atom_coords[not_hs]
atoms_edge_index = radius_graph(atom_coords, atom_cutoff, max_num_neighbors=atom_max_neighbors if atom_max_neighbors else 1000) atom_res_edge_index = torch.from_numpy(np.asarray([np.arange(len(atom_feat)), src_c_alpha_idx])).long()
complex_graph['atom'].x = atom_feat complex_graph['atom'].pos = atom_coords complex_graph['atom', 'atom_contact', 'atom'].edge_index = atoms_edge_index complex_graph['atom', 'atom_rec_contact', 'receptor'].edge_index = atom_res_edge_index
return
def write_mol_with_coords(mol, new_coords, path): w = Chem.SDWriter(path) conf = mol.GetConformer() for i in range(mol.GetNumAtoms()): x,y,z = new_coords.astype(np.double)[i] conf.SetAtomPosition(i,Point3D(x,y,z)) w.write(mol) w.close()
def read_molecule(molecule_file, sanitize=False, calc_charges=False, remove_hs=False): if molecule_file.endswith('.mol2'): mol = Chem.MolFromMol2File(molecule_file, sanitize=False, removeHs=False) elif molecule_file.endswith('.sdf'): print(molecule_file) supplier = Chem.SDMolSupplier(molecule_file, sanitize=False, removeHs=False) mol = supplier[0] print(mol) elif molecule_file.endswith('.pdbqt'): with open(molecule_file) as file: pdbqt_data = file.readlines() pdb_block = '' for line in pdbqt_data: pdb_block += '{}\n'.format(line[:66]) mol = Chem.MolFromPDBBlock(pdb_block, sanitize=False, removeHs=False) elif molecule_file.endswith('.pdb'): mol = Chem.MolFromPDBFile(molecule_file, sanitize=False, removeHs=False) else: return ValueError('Expect the format of the molecule_file to be ' 'one of .mol2, .sdf, .pdbqt and .pdb, got {}'.format(molecule_file))
print(sanitize, calc_charges, remove_hs)
try: if sanitize or calc_charges: Chem.SanitizeMol(mol)
if calc_charges: # Compute Gasteiger charges on the molecule. try: AllChem.ComputeGasteigerCharges(mol) except: warnings.warn('Unable to compute charges for the molecule.')
if remove_hs: mol = Chem.RemoveHs(mol, sanitize=sanitize) except Exception as e: print(e) return None
return mol
def read_sdf_or_mol2(sdf_fileName, mol2_fileName):
mol = Chem.MolFromMolFile(sdf_fileName, sanitize=False) problem = False try: Chem.SanitizeMol(mol) mol = Chem.RemoveHs(mol) except Exception as e: problem = True if problem: mol = Chem.MolFromMol2File(mol2_fileName, sanitize=False) try: Chem.SanitizeMol(mol) mol = Chem.RemoveHs(mol) problem = False except Exception as e: problem = True
return mol, problem123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102name: diffdockchannels: - pytorch - defaultsdependencies: - blas=1.0 - brotlipy=0.7.0 - bzip2=1.0.8 - ca-certificates=2022.07.19 - certifi=2022.9.14 - cffi=1.15.1 - charset-normalizer=2.0.4 - cryptography=37.0.1 - ffmpeg=4.3 - freetype=2.11.0 - gettext=0.21.0 - giflib=5.2.1 - gmp=6.2.1 - gnutls=3.6.15 - icu=58.2 - idna=3.3 - intel-openmp=2021.4.0 - jpeg=9e - lame=3.100 - lcms2=2.12 - lerc=3.0 - libcxx=14.0.6 - libdeflate=1.8 - libffi=3.3 - libiconv=1.16 - libidn2=2.3.2 - libpng=1.6.37 - libtasn1=4.16.0 - libtiff=4.4.0 - libunistring=0.9.10 - libwebp=1.2.2 - libwebp-base=1.2.2 - libxml2=2.9.14 - llvm-openmp=14.0.6 - lz4-c=1.9.3 - mkl=2021.4.0 - mkl-service=2.4.0 - mkl_fft=1.3.1 - mkl_random=1.2.2 - ncurses=6.3 - nettle=3.7.3 - numpy=1.23.1 - numpy-base=1.23.1 - openh264=2.1.1 - openssl=1.1.1q - pillow=9.2.0 - pip=22.2.2 - pycparser=2.21 - pyopenssl=22.0.0 - pysocks=1.7.1 - python=3.9.13 - pytorch=1.12.1 - readline=8.1.2 - requests=2.28.1 - setuptools=63.4.1 - six=1.16.0 - sqlite=3.39.3 - tk=8.6.12 - torchaudio=0.12.1 - torchvision=0.13.1 - typing_extensions=4.3.0 - tzdata=2022c - urllib3=1.26.11 - wheel=0.37.1 - xz=5.2.6 - zlib=1.2.12 - zstd=1.5.2 - pip: - biopandas==0.4.1 - biopython==1.79 - e3nn==0.5.0 - jinja2==3.1.2 - joblib==1.2.0 - markupsafe==2.1.1 - mpmath==1.2.1 - networkx==2.8.7 - opt-einsum==3.3.0 - opt-einsum-fx==0.1.4 - packaging==21.3 - pandas==1.5.0 - pyaml==21.10.1 - pyparsing==3.0.9 - python-dateutil==2.8.2 - pytz==2022.4 - pyyaml==6.0 - rdkit-pypi==2022.3.5 - scikit-learn==1.1.2 - scipy==1.9.1 - spyrmsd==0.5.2 - sympy==1.11.1 - threadpoolctl==3.1.0 - torch-cluster==1.6.0 - torch-geometric==2.1.0.post1 - torch-scatter==2.0.9 - torch-sparse==0.6.15 - torch-spline-conv==1.2.1 - tqdm==4.64.1123456789101112131415161718192021MIT License
Copyright (c) Facebook, Inc. and its affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
from .version import version as __version__ # noqa
from .data import Alphabet, BatchConverter, FastaBatchedDataset # noqafrom .model.esm1 import ProteinBertModel # noqafrom .model.esm2 import ESM2 # noqafrom .model.msa_transformer import MSATransformer #noqafrom . import pretrained # noqa123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import mathimport torchimport torch.nn as nn
class RowSelfAttention(nn.Module): """Compute self-attention over rows of a 2D input."""
def __init__( self, embed_dim, num_heads, dropout=0.0, max_tokens_per_msa: int = 2 ** 16, ): super().__init__() self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads self.scaling = self.head_dim ** -0.5 self.max_tokens_per_msa = max_tokens_per_msa self.attn_shape = "hnij"
self.k_proj = nn.Linear(embed_dim, embed_dim) self.v_proj = nn.Linear(embed_dim, embed_dim) self.q_proj = nn.Linear(embed_dim, embed_dim)
self.out_proj = nn.Linear(embed_dim, embed_dim) self.dropout_module = nn.Dropout(dropout)
def align_scaling(self, q): num_rows = q.size(0) return self.scaling / math.sqrt(num_rows)
def _batched_forward( self, x, self_attn_mask=None, self_attn_padding_mask=None, ): num_rows, num_cols, batch_size, embed_dim = x.size() max_rows = max(1, self.max_tokens_per_msa // num_cols) attns = 0 scaling = self.align_scaling(x) for start in range(0, num_rows, max_rows): attn_weights = self.compute_attention_weights( x[start : start + max_rows], scaling, self_attn_mask=self_attn_mask, self_attn_padding_mask=self_attn_padding_mask[:, start : start + max_rows] if self_attn_padding_mask is not None else None, ) attns += attn_weights attn_probs = attns.softmax(-1) attn_probs = self.dropout_module(attn_probs)
outputs = [] for start in range(0, num_rows, max_rows): output = self.compute_attention_update(x[start : start + max_rows], attn_probs) outputs.append(output)
output = torch.cat(outputs, 0) return output, attn_probs
def compute_attention_weights( self, x, scaling: float, self_attn_mask=None, self_attn_padding_mask=None, ): num_rows, num_cols, batch_size, embed_dim = x.size() q = self.q_proj(x).view(num_rows, num_cols, batch_size, self.num_heads, self.head_dim) k = self.k_proj(x).view(num_rows, num_cols, batch_size, self.num_heads, self.head_dim) q *= scaling if self_attn_padding_mask is not None: # Zero out any padded aligned positions - this is important since # we take a sum across the alignment axis. q *= 1 - self_attn_padding_mask.permute(1, 2, 0).unsqueeze(3).unsqueeze(4).to(q)
attn_weights = torch.einsum(f"rinhd,rjnhd->{self.attn_shape}", q, k)
if self_attn_mask is not None: raise NotImplementedError # Mask Size: [B x R x C], Weights Size: [H x B x C x C]
if self_attn_padding_mask is not None: attn_weights = attn_weights.masked_fill( self_attn_padding_mask[:, 0].unsqueeze(0).unsqueeze(2), -10000, )
return attn_weights
def compute_attention_update( self, x, attn_probs, ): num_rows, num_cols, batch_size, embed_dim = x.size() v = self.v_proj(x).view(num_rows, num_cols, batch_size, self.num_heads, self.head_dim) context = torch.einsum(f"{self.attn_shape},rjnhd->rinhd", attn_probs, v) context = context.contiguous().view(num_rows, num_cols, batch_size, embed_dim) output = self.out_proj(context) return output
def forward( self, x, self_attn_mask=None, self_attn_padding_mask=None, ): num_rows, num_cols, batch_size, embed_dim = x.size() if (num_rows * num_cols > self.max_tokens_per_msa) and not torch.is_grad_enabled(): return self._batched_forward(x, self_attn_mask, self_attn_padding_mask) else: scaling = self.align_scaling(x) attn_weights = self.compute_attention_weights( x, scaling, self_attn_mask, self_attn_padding_mask ) attn_probs = attn_weights.softmax(-1) attn_probs = self.dropout_module(attn_probs) output = self.compute_attention_update(x, attn_probs) return output, attn_probs
class ColumnSelfAttention(nn.Module): """Compute self-attention over columns of a 2D input."""
def __init__( self, embed_dim, num_heads, dropout=0.0, max_tokens_per_msa: int = 2 ** 16, ): super().__init__()
self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads self.scaling = self.head_dim ** -0.5 self.max_tokens_per_msa = max_tokens_per_msa
self.k_proj = nn.Linear(embed_dim, embed_dim) self.v_proj = nn.Linear(embed_dim, embed_dim) self.q_proj = nn.Linear(embed_dim, embed_dim)
self.out_proj = nn.Linear(embed_dim, embed_dim) self.dropout_module = nn.Dropout(dropout)
def _batched_forward( self, x, self_attn_mask=None, self_attn_padding_mask=None, ): num_rows, num_cols, batch_size, embed_dim = x.size() max_cols = max(1, self.max_tokens_per_msa // num_rows) outputs = [] attns = [] for start in range(0, num_cols, max_cols): output, attn = self( x[:, start : start + max_cols], self_attn_mask=self_attn_mask, self_attn_padding_mask=self_attn_padding_mask[:, :, start : start + max_cols] if self_attn_padding_mask is not None else None, ) outputs.append(output) attns.append(attn) output = torch.cat(outputs, 1) attns = torch.cat(attns, 1) return output, attns
def compute_attention_update( self, x, self_attn_mask=None, self_attn_padding_mask=None, ): num_rows, num_cols, batch_size, embed_dim = x.size() if num_rows == 1: # if there is only 1 position, this is equivalent and doesn't break with padding attn_probs = torch.ones( self.num_heads, num_cols, batch_size, num_rows, num_rows, device=x.device, dtype=x.dtype, ) output = self.out_proj(self.v_proj(x)) else: q = self.q_proj(x).view(num_rows, num_cols, batch_size, self.num_heads, self.head_dim) k = self.k_proj(x).view(num_rows, num_cols, batch_size, self.num_heads, self.head_dim) v = self.v_proj(x).view(num_rows, num_cols, batch_size, self.num_heads, self.head_dim) q *= self.scaling
attn_weights = torch.einsum("icnhd,jcnhd->hcnij", q, k)
if self_attn_mask is not None: raise NotImplementedError if self_attn_padding_mask is not None: attn_weights = attn_weights.masked_fill( self_attn_padding_mask.permute(2, 0, 1).unsqueeze(0).unsqueeze(3), -10000, )
attn_probs = attn_weights.softmax(-1) attn_probs = self.dropout_module(attn_probs) context = torch.einsum("hcnij,jcnhd->icnhd", attn_probs, v) context = context.contiguous().view(num_rows, num_cols, batch_size, embed_dim) output = self.out_proj(context) return output, attn_probs
def forward( self, x, self_attn_mask=None, self_attn_padding_mask=None, ): num_rows, num_cols, batch_size, embed_dim = x.size() # if False and num_rows * num_cols > 2 ** 14 and not torch.is_grad_enabled(): if (num_rows * num_cols) > self.max_tokens_per_msa and not torch.is_grad_enabled(): return self._batched_forward( x, self_attn_mask, self_attn_padding_mask, ) else: return self.compute_attention_update(x, self_attn_mask, self_attn_padding_mask)12345678910# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
# fmt: offproteinseq_toks = { 'toks': ['L', 'A', 'G', 'V', 'S', 'E', 'R', 'T', 'I', 'D', 'P', 'K', 'Q', 'N', 'F', 'Y', 'M', 'H', 'W', 'C', 'X', 'B', 'U', 'Z', 'O', '.', '-']}# fmt: on123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import itertoolsimport osfrom typing import Sequence, Tuple, List, Unionimport pickleimport reimport shutilimport torchfrom pathlib import Pathfrom esm.constants import proteinseq_toks
RawMSA = Sequence[Tuple[str, str]]
class FastaBatchedDataset(object): def __init__(self, sequence_labels, sequence_strs): self.sequence_labels = list(sequence_labels) self.sequence_strs = list(sequence_strs)
@classmethod def from_file(cls, fasta_file): sequence_labels, sequence_strs = [], [] cur_seq_label = None buf = []
def _flush_current_seq(): nonlocal cur_seq_label, buf if cur_seq_label is None: return sequence_labels.append(cur_seq_label) sequence_strs.append("".join(buf)) cur_seq_label = None buf = []
with open(fasta_file, "r") as infile: for line_idx, line in enumerate(infile): if line.startswith(">"): # label line _flush_current_seq() line = line[1:].strip() if len(line) > 0: cur_seq_label = line else: cur_seq_label = f"seqnum{line_idx:09d}" else: # sequence line buf.append(line.strip())
_flush_current_seq()
assert len(set(sequence_labels)) == len( sequence_labels ), "Found duplicate sequence labels"
return cls(sequence_labels, sequence_strs)
def __len__(self): return len(self.sequence_labels)
def __getitem__(self, idx): return self.sequence_labels[idx], self.sequence_strs[idx]
def get_batch_indices(self, toks_per_batch, extra_toks_per_seq=0): sizes = [(len(s), i) for i, s in enumerate(self.sequence_strs)] sizes.sort() batches = [] buf = [] max_len = 0
def _flush_current_buf(): nonlocal max_len, buf if len(buf) == 0: return batches.append(buf) buf = [] max_len = 0
for sz, i in sizes: sz += extra_toks_per_seq if max(sz, max_len) * (len(buf) + 1) > toks_per_batch: _flush_current_buf() max_len = max(max_len, sz) buf.append(i)
_flush_current_buf() return batches
class Alphabet(object): def __init__( self, standard_toks: Sequence[str], prepend_toks: Sequence[str] = ("<null_0>", "<pad>", "<eos>", "<unk>"), append_toks: Sequence[str] = ("<cls>", "<mask>", "<sep>"), prepend_bos: bool = True, append_eos: bool = False, use_msa: bool = False, ): self.standard_toks = list(standard_toks) self.prepend_toks = list(prepend_toks) self.append_toks = list(append_toks) self.prepend_bos = prepend_bos self.append_eos = append_eos self.use_msa = use_msa
self.all_toks = list(self.prepend_toks) self.all_toks.extend(self.standard_toks) for i in range((8 - (len(self.all_toks) % 8)) % 8): self.all_toks.append(f"<null_{i + 1}>") self.all_toks.extend(self.append_toks)
self.tok_to_idx = {tok: i for i, tok in enumerate(self.all_toks)}
self.unk_idx = self.tok_to_idx["<unk>"] self.padding_idx = self.get_idx("<pad>") self.cls_idx = self.get_idx("<cls>") self.mask_idx = self.get_idx("<mask>") self.eos_idx = self.get_idx("<eos>") self.all_special_tokens = ['<eos>', '<unk>', '<pad>', '<cls>', '<mask>'] self.unique_no_split_tokens = self.all_toks
def __len__(self): return len(self.all_toks)
def get_idx(self, tok): return self.tok_to_idx.get(tok, self.unk_idx)
def get_tok(self, ind): return self.all_toks[ind]
def to_dict(self): return self.tok_to_idx.copy()
def get_batch_converter(self, truncation_seq_length: int = None): if self.use_msa: return MSABatchConverter(self, truncation_seq_length) else: return BatchConverter(self, truncation_seq_length)
@classmethod def from_architecture(cls, name: str) -> "Alphabet": if name in ("ESM-1", "protein_bert_base"): standard_toks = proteinseq_toks["toks"] prepend_toks: Tuple[str, ...] = ("<null_0>", "<pad>", "<eos>", "<unk>") append_toks: Tuple[str, ...] = ("<cls>", "<mask>", "<sep>") prepend_bos = True append_eos = False use_msa = False elif name in ("ESM-1b", "roberta_large"): standard_toks = proteinseq_toks["toks"] prepend_toks = ("<cls>", "<pad>", "<eos>", "<unk>") append_toks = ("<mask>",) prepend_bos = True append_eos = True use_msa = False elif name in ("MSA Transformer", "msa_transformer"): standard_toks = proteinseq_toks["toks"] prepend_toks = ("<cls>", "<pad>", "<eos>", "<unk>") append_toks = ("<mask>",) prepend_bos = True append_eos = False use_msa = True elif "invariant_gvp" in name.lower(): standard_toks = proteinseq_toks["toks"] prepend_toks = ("<null_0>", "<pad>", "<eos>", "<unk>") append_toks = ("<mask>", "<cath>", "<af2>") prepend_bos = True append_eos = False use_msa = False else: raise ValueError("Unknown architecture selected") return cls(standard_toks, prepend_toks, append_toks, prepend_bos, append_eos, use_msa)
def _tokenize(self, text) -> str: return text.split()
def tokenize(self, text, **kwargs) -> List[str]: """ Inspired by https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils.py Converts a string in a sequence of tokens, using the tokenizer.
Args: text (:obj:`str`): The sequence to be encoded.
Returns: :obj:`List[str]`: The list of tokens. """
def split_on_token(tok, text): result = [] split_text = text.split(tok) for i, sub_text in enumerate(split_text): # AddedToken can control whitespace stripping around them. # We use them for GPT2 and Roberta to have different behavior depending on the special token # Cf. https://github.com/huggingface/transformers/pull/2778 # and https://github.com/huggingface/transformers/issues/3788 # We strip left and right by default if i < len(split_text) - 1: sub_text = sub_text.rstrip() if i > 0: sub_text = sub_text.lstrip()
if i == 0 and not sub_text: result.append(tok) elif i == len(split_text) - 1: if sub_text: result.append(sub_text) else: pass else: if sub_text: result.append(sub_text) result.append(tok) return result
def split_on_tokens(tok_list, text): if not text.strip(): return []
tokenized_text = [] text_list = [text] for tok in tok_list: tokenized_text = [] for sub_text in text_list: if sub_text not in self.unique_no_split_tokens: tokenized_text.extend(split_on_token(tok, sub_text)) else: tokenized_text.append(sub_text) text_list = tokenized_text
return list( itertools.chain.from_iterable( ( self._tokenize(token) if token not in self.unique_no_split_tokens else [token] for token in tokenized_text ) ) )
no_split_token = self.unique_no_split_tokens tokenized_text = split_on_tokens(no_split_token, text) return tokenized_text
def encode(self, text): return [self.tok_to_idx[tok] for tok in self.tokenize(text)]
class BatchConverter(object): """Callable to convert an unprocessed (labels + strings) batch to a processed (labels + tensor) batch. """
def __init__(self, alphabet, truncation_seq_length: int = None): self.alphabet = alphabet self.truncation_seq_length = truncation_seq_length
def __call__(self, raw_batch: Sequence[Tuple[str, str]]): # RoBERTa uses an eos token, while ESM-1 does not. batch_size = len(raw_batch) batch_labels, seq_str_list = zip(*raw_batch) seq_encoded_list = [self.alphabet.encode(seq_str) for seq_str in seq_str_list] if self.truncation_seq_length: seq_encoded_list = [seq_str[:self.truncation_seq_length] for seq_str in seq_encoded_list] max_len = max(len(seq_encoded) for seq_encoded in seq_encoded_list) tokens = torch.empty( ( batch_size, max_len + int(self.alphabet.prepend_bos) + int(self.alphabet.append_eos), ), dtype=torch.int64, ) tokens.fill_(self.alphabet.padding_idx) labels = [] strs = []
for i, (label, seq_str, seq_encoded) in enumerate( zip(batch_labels, seq_str_list, seq_encoded_list) ): labels.append(label) strs.append(seq_str) if self.alphabet.prepend_bos: tokens[i, 0] = self.alphabet.cls_idx seq = torch.tensor(seq_encoded, dtype=torch.int64) tokens[ i, int(self.alphabet.prepend_bos) : len(seq_encoded) + int(self.alphabet.prepend_bos), ] = seq if self.alphabet.append_eos: tokens[i, len(seq_encoded) + int(self.alphabet.prepend_bos)] = self.alphabet.eos_idx
return labels, strs, tokens
class MSABatchConverter(BatchConverter): def __call__(self, inputs: Union[Sequence[RawMSA], RawMSA]): if isinstance(inputs[0][0], str): # Input is a single MSA raw_batch: Sequence[RawMSA] = [inputs] # type: ignore else: raw_batch = inputs # type: ignore
batch_size = len(raw_batch) max_alignments = max(len(msa) for msa in raw_batch) max_seqlen = max(len(msa[0][1]) for msa in raw_batch)
tokens = torch.empty( ( batch_size, max_alignments, max_seqlen + int(self.alphabet.prepend_bos) + int(self.alphabet.append_eos), ), dtype=torch.int64, ) tokens.fill_(self.alphabet.padding_idx) labels = [] strs = []
for i, msa in enumerate(raw_batch): msa_seqlens = set(len(seq) for _, seq in msa) if not len(msa_seqlens) == 1: raise RuntimeError( "Received unaligned sequences for input to MSA, all sequence " "lengths must be equal." ) msa_labels, msa_strs, msa_tokens = super().__call__(msa) labels.append(msa_labels) strs.append(msa_strs) tokens[i, : msa_tokens.size(0), : msa_tokens.size(1)] = msa_tokens
return labels, strs, tokens
def read_fasta( path, keep_gaps=True, keep_insertions=True, to_upper=False,): with open(path, "r") as f: for result in read_alignment_lines( f, keep_gaps=keep_gaps, keep_insertions=keep_insertions, to_upper=to_upper ): yield result
def read_alignment_lines( lines, keep_gaps=True, keep_insertions=True, to_upper=False,): seq = desc = None
def parse(s): if not keep_gaps: s = re.sub("-", "", s) if not keep_insertions: s = re.sub("[a-z]", "", s) return s.upper() if to_upper else s
for line in lines: # Line may be empty if seq % file_line_width == 0 if len(line) > 0 and line[0] == ">": if seq is not None: yield desc, parse(seq) desc = line.strip() seq = "" else: assert isinstance(seq, str) seq += line.strip() assert isinstance(seq, str) and isinstance(desc, str) yield desc, parse(seq)
class ESMStructuralSplitDataset(torch.utils.data.Dataset): """ Structural Split Dataset as described in section A.10 of the supplement of our paper. https://doi.org/10.1101/622803
We use the full version of SCOPe 2.07, clustered at 90% sequence identity, generated on January 23, 2020.
For each SCOPe domain: - We extract the sequence from the corresponding PDB file - We extract the 3D coordinates of the Carbon beta atoms, aligning them to the sequence. We put NaN where Cb atoms are missing. - From the 3D coordinates, we calculate a pairwise distance map, based on L2 distance - We use DSSP to generate secondary structure labels for the corresponding PDB file. This is also aligned to the sequence. We put - where SSP labels are missing.
For each SCOPe classification level of family/superfamily/fold (in order of difficulty), we have split the data into 5 partitions for cross validation. These are provided in a downloaded splits folder, in the format: splits/{split_level}/{cv_partition}/{train|valid}.txt where train is the partition and valid is the concatentation of the remaining 4.
For each SCOPe domain, we provide a pkl dump that contains: - seq : The domain sequence, stored as an L-length string - ssp : The secondary structure labels, stored as an L-length string - dist : The distance map, stored as an LxL numpy array - coords : The 3D coordinates, stored as an Lx3 numpy array
"""
base_folder = "structural-data" file_list = [ # url tar filename filename MD5 Hash ( "https://dl.fbaipublicfiles.com/fair-esm/structural-data/splits.tar.gz", "splits.tar.gz", "splits", "456fe1c7f22c9d3d8dfe9735da52411d", ), ( "https://dl.fbaipublicfiles.com/fair-esm/structural-data/pkl.tar.gz", "pkl.tar.gz", "pkl", "644ea91e56066c750cd50101d390f5db", ), ]
def __init__( self, split_level, cv_partition, split, root_path=os.path.expanduser("~/.cache/torch/data/esm"), download=False, ): super().__init__() assert split in [ "train", "valid", ], "train_valid must be 'train' or 'valid'" self.root_path = root_path self.base_path = os.path.join(self.root_path, self.base_folder)
# check if root path has what you need or else download it if download: self.download()
self.split_file = os.path.join( self.base_path, "splits", split_level, cv_partition, f"{split}.txt" ) self.pkl_dir = os.path.join(self.base_path, "pkl") self.names = [] with open(self.split_file) as f: self.names = f.read().splitlines()
def __len__(self): return len(self.names)
def _check_exists(self) -> bool: for (_, _, filename, _) in self.file_list: fpath = os.path.join(self.base_path, filename) if not os.path.exists(fpath) or not os.path.isdir(fpath): return False return True
def download(self):
if self._check_exists(): print("Files already downloaded and verified") return
from torchvision.datasets.utils import download_url
for url, tar_filename, filename, md5_hash in self.file_list: download_path = os.path.join(self.base_path, tar_filename) download_url(url=url, root=self.base_path, filename=tar_filename, md5=md5_hash) shutil.unpack_archive(download_path, self.base_path)
def __getitem__(self, idx): """ Returns a dict with the following entires - seq : Str (domain sequence) - ssp : Str (SSP labels) - dist : np.array (distance map) - coords : np.array (3D coordinates) """ name = self.names[idx] pkl_fname = os.path.join(self.pkl_dir, name[1:3], f"{name}.pkl") with open(pkl_fname, "rb") as f: obj = pickle.load(f) return obj12345678# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
from . import gvp_transformerfrom . import utilfrom . import multichain_util123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.# # Portions of this file were adapted from the open source code for the following# two papers:## Ingraham, J., Garg, V., Barzilay, R., & Jaakkola, T. (2019). Generative# models for graph-based protein design. Advances in Neural Information# Processing Systems, 32.## Jing, B., Eismann, S., Suriana, P., Townshend, R. J. L., & Dror, R. (2020).# Learning from Protein Structure with Geometric Vector Perceptrons. In# International Conference on Learning Representations.## MIT License# # Copyright (c) 2020 Bowen Jing, Stephan Eismann, Patricia Suriana, Raphael Townshend, Ron Dror# # Permission is hereby granted, free of charge, to any person obtaining a copy# of this software and associated documentation files (the "Software"), to deal# in the Software without restriction, including without limitation the rights# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell# copies of the Software, and to permit persons to whom the Software is# furnished to do so, subject to the following conditions:# # The above copyright notice and this permission notice shall be included in all# copies or substantial portions of the Software.# # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE# SOFTWARE.# # ================================================================# The below license applies to the portions of the code (parts of # src/datasets.py and src/models.py) adapted from Ingraham, et al.# ================================================================# # MIT License# # Copyright (c) 2019 John Ingraham, Vikas Garg, Regina Barzilay, Tommi Jaakkola# # Permission is hereby granted, free of charge, to any person obtaining a copy# of this software and associated documentation files (the "Software"), to deal# in the Software without restriction, including without limitation the rights# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell# copies of the Software, and to permit persons to whom the Software is# furnished to do so, subject to the following conditions:# # The above copyright notice and this permission notice shall be included in all# copies or substantial portions of the Software.# # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE# SOFTWARE.
import mathimport numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as F
from .gvp_utils import flatten_graphfrom .gvp_modules import GVP, LayerNormfrom .util import normalize, norm, nan_to_num, rbf
class GVPInputFeaturizer(nn.Module):
@staticmethod def get_node_features(coords, coord_mask, with_coord_mask=True): # scalar features node_scalar_features = GVPInputFeaturizer._dihedrals(coords) if with_coord_mask: node_scalar_features = torch.cat([ node_scalar_features, coord_mask.float().unsqueeze(-1) ], dim=-1) # vector features X_ca = coords[:, :, 1] orientations = GVPInputFeaturizer._orientations(X_ca) sidechains = GVPInputFeaturizer._sidechains(coords) node_vector_features = torch.cat([orientations, sidechains.unsqueeze(-2)], dim=-2) return node_scalar_features, node_vector_features
@staticmethod def _orientations(X): forward = normalize(X[:, 1:] - X[:, :-1]) backward = normalize(X[:, :-1] - X[:, 1:]) forward = F.pad(forward, [0, 0, 0, 1]) backward = F.pad(backward, [0, 0, 1, 0]) return torch.cat([forward.unsqueeze(-2), backward.unsqueeze(-2)], -2) @staticmethod def _sidechains(X): n, origin, c = X[:, :, 0], X[:, :, 1], X[:, :, 2] c, n = normalize(c - origin), normalize(n - origin) bisector = normalize(c + n) perp = normalize(torch.cross(c, n, dim=-1)) vec = -bisector * math.sqrt(1 / 3) - perp * math.sqrt(2 / 3) return vec
@staticmethod def _dihedrals(X, eps=1e-7): X = torch.flatten(X[:, :, :3], 1, 2) bsz = X.shape[0] dX = X[:, 1:] - X[:, :-1] U = normalize(dX, dim=-1) u_2 = U[:, :-2] u_1 = U[:, 1:-1] u_0 = U[:, 2:] # Backbone normals n_2 = normalize(torch.cross(u_2, u_1, dim=-1), dim=-1) n_1 = normalize(torch.cross(u_1, u_0, dim=-1), dim=-1) # Angle between normals cosD = torch.sum(n_2 * n_1, -1) cosD = torch.clamp(cosD, -1 + eps, 1 - eps) D = torch.sign(torch.sum(u_2 * n_1, -1)) * torch.acos(cosD) # This scheme will remove phi[0], psi[-1], omega[-1] D = F.pad(D, [1, 2]) D = torch.reshape(D, [bsz, -1, 3]) # Lift angle representations to the circle D_features = torch.cat([torch.cos(D), torch.sin(D)], -1) return D_features
@staticmethod def _positional_embeddings(edge_index, num_embeddings=None, num_positional_embeddings=16, period_range=[2, 1000]): # From https://github.com/jingraham/neurips19-graph-protein-design num_embeddings = num_embeddings or num_positional_embeddings d = edge_index[0] - edge_index[1] frequency = torch.exp( torch.arange(0, num_embeddings, 2, dtype=torch.float32, device=edge_index.device) * -(np.log(10000.0) / num_embeddings) ) angles = d.unsqueeze(-1) * frequency E = torch.cat((torch.cos(angles), torch.sin(angles)), -1) return E
@staticmethod def _dist(X, coord_mask, padding_mask, top_k_neighbors, eps=1e-8): """ Pairwise euclidean distances """ bsz, maxlen = X.size(0), X.size(1) coord_mask_2D = torch.unsqueeze(coord_mask,1) * torch.unsqueeze(coord_mask,2) residue_mask = ~padding_mask residue_mask_2D = torch.unsqueeze(residue_mask,1) * torch.unsqueeze(residue_mask,2) dX = torch.unsqueeze(X,1) - torch.unsqueeze(X,2) D = coord_mask_2D * norm(dX, dim=-1) # sorting preference: first those with coords, then among the residues that # exist but are masked use distance in sequence as tie breaker, and then the # residues that came from padding are last seqpos = torch.arange(maxlen, device=X.device) Dseq = torch.abs(seqpos.unsqueeze(1) - seqpos.unsqueeze(0)).repeat(bsz, 1, 1) D_adjust = nan_to_num(D) + (~coord_mask_2D) * (1e8 + Dseq*1e6) + ( ~residue_mask_2D) * (1e10) if top_k_neighbors == -1: D_neighbors = D_adjust E_idx = seqpos.repeat( *D_neighbors.shape[:-1], 1) else: # Identify k nearest neighbors (including self) k = min(top_k_neighbors, X.size(1)) D_neighbors, E_idx = torch.topk(D_adjust, k, dim=-1, largest=False) coord_mask_neighbors = (D_neighbors < 5e7) residue_mask_neighbors = (D_neighbors < 5e9) return D_neighbors, E_idx, coord_mask_neighbors, residue_mask_neighbors
class Normalize(nn.Module): def __init__(self, features, epsilon=1e-6): super(Normalize, self).__init__() self.gain = nn.Parameter(torch.ones(features)) self.bias = nn.Parameter(torch.zeros(features)) self.epsilon = epsilon
def forward(self, x, dim=-1): mu = x.mean(dim, keepdim=True) sigma = torch.sqrt(x.var(dim, keepdim=True) + self.epsilon) gain = self.gain bias = self.bias # Reshape if dim != -1: shape = [1] * len(mu.size()) shape[dim] = self.gain.size()[0] gain = gain.view(shape) bias = bias.view(shape) return gain * (x - mu) / (sigma + self.epsilon) + bias
class DihedralFeatures(nn.Module): def __init__(self, node_embed_dim): """ Embed dihedral angle features. """ super(DihedralFeatures, self).__init__() # 3 dihedral angles; sin and cos of each angle node_in = 6 # Normalization and embedding self.node_embedding = nn.Linear(node_in, node_embed_dim, bias=True) self.norm_nodes = Normalize(node_embed_dim)
def forward(self, X): """ Featurize coordinates as an attributed graph """ V = self._dihedrals(X) V = self.node_embedding(V) V = self.norm_nodes(V) return V
@staticmethod def _dihedrals(X, eps=1e-7, return_angles=False): # First 3 coordinates are N, CA, C X = X[:,:,:3,:].reshape(X.shape[0], 3*X.shape[1], 3)
# Shifted slices of unit vectors dX = X[:,1:,:] - X[:,:-1,:] U = F.normalize(dX, dim=-1) u_2 = U[:,:-2,:] u_1 = U[:,1:-1,:] u_0 = U[:,2:,:] # Backbone normals n_2 = F.normalize(torch.cross(u_2, u_1, dim=-1), dim=-1) n_1 = F.normalize(torch.cross(u_1, u_0, dim=-1), dim=-1)
# Angle between normals cosD = (n_2 * n_1).sum(-1) cosD = torch.clamp(cosD, -1+eps, 1-eps) D = torch.sign((u_2 * n_1).sum(-1)) * torch.acos(cosD)
# This scheme will remove phi[0], psi[-1], omega[-1] D = F.pad(D, (1,2), 'constant', 0) D = D.view((D.size(0), int(D.size(1)/3), 3)) phi, psi, omega = torch.unbind(D,-1)
if return_angles: return phi, psi, omega
# Lift angle representations to the circle D_features = torch.cat((torch.cos(D), torch.sin(D)), 2) return D_features
class GVPGraphEmbedding(GVPInputFeaturizer):
def __init__(self, args): super().__init__() self.top_k_neighbors = args.top_k_neighbors self.num_positional_embeddings = 16 self.remove_edges_without_coords = True node_input_dim = (7, 3) edge_input_dim = (34, 1) node_hidden_dim = (args.node_hidden_dim_scalar, args.node_hidden_dim_vector) edge_hidden_dim = (args.edge_hidden_dim_scalar, args.edge_hidden_dim_vector) self.embed_node = nn.Sequential( GVP(node_input_dim, node_hidden_dim, activations=(None, None)), LayerNorm(node_hidden_dim, eps=1e-4) ) self.embed_edge = nn.Sequential( GVP(edge_input_dim, edge_hidden_dim, activations=(None, None)), LayerNorm(edge_hidden_dim, eps=1e-4) ) self.embed_confidence = nn.Linear(16, args.node_hidden_dim_scalar)
def forward(self, coords, coord_mask, padding_mask, confidence): with torch.no_grad(): node_features = self.get_node_features(coords, coord_mask) edge_features, edge_index = self.get_edge_features( coords, coord_mask, padding_mask) node_embeddings_scalar, node_embeddings_vector = self.embed_node(node_features) edge_embeddings = self.embed_edge(edge_features)
rbf_rep = rbf(confidence, 0., 1.) node_embeddings = ( node_embeddings_scalar + self.embed_confidence(rbf_rep), node_embeddings_vector )
node_embeddings, edge_embeddings, edge_index = flatten_graph( node_embeddings, edge_embeddings, edge_index) return node_embeddings, edge_embeddings, edge_index
def get_edge_features(self, coords, coord_mask, padding_mask): X_ca = coords[:, :, 1] # Get distances to the top k neighbors E_dist, E_idx, E_coord_mask, E_residue_mask = GVPInputFeaturizer._dist( X_ca, coord_mask, padding_mask, self.top_k_neighbors) # Flatten the graph to be batch size 1 for torch_geometric package dest = E_idx B, L, k = E_idx.shape[:3] src = torch.arange(L, device=E_idx.device).view([1, L, 1]).expand(B, L, k) # After flattening, [2, B, E] edge_index = torch.stack([src, dest], dim=0).flatten(2, 3) # After flattening, [B, E] E_dist = E_dist.flatten(1, 2) E_coord_mask = E_coord_mask.flatten(1, 2).unsqueeze(-1) E_residue_mask = E_residue_mask.flatten(1, 2) # Calculate relative positional embeddings and distance RBF pos_embeddings = GVPInputFeaturizer._positional_embeddings( edge_index, num_positional_embeddings=self.num_positional_embeddings, ) D_rbf = rbf(E_dist, 0., 20.) # Calculate relative orientation X_src = X_ca.unsqueeze(2).expand(-1, -1, k, -1).flatten(1, 2) X_dest = torch.gather( X_ca, 1, edge_index[1, :, :].unsqueeze(-1).expand([B, L*k, 3]) ) coord_mask_src = coord_mask.unsqueeze(2).expand(-1, -1, k).flatten(1, 2) coord_mask_dest = torch.gather( coord_mask, 1, edge_index[1, :, :].expand([B, L*k]) ) E_vectors = X_src - X_dest # For the ones without coordinates, substitute in the average vector E_vector_mean = torch.sum(E_vectors * E_coord_mask, dim=1, keepdims=True) / torch.sum(E_coord_mask, dim=1, keepdims=True) E_vectors = E_vectors * E_coord_mask + E_vector_mean * ~(E_coord_mask) # Normalize and remove nans edge_s = torch.cat([D_rbf, pos_embeddings], dim=-1) edge_v = normalize(E_vectors).unsqueeze(-2) edge_s, edge_v = map(nan_to_num, (edge_s, edge_v)) # Also add indications of whether the coordinates are present edge_s = torch.cat([ edge_s, (~coord_mask_src).float().unsqueeze(-1), (~coord_mask_dest).float().unsqueeze(-1), ], dim=-1) edge_index[:, ~E_residue_mask] = -1 if self.remove_edges_without_coords: edge_index[:, ~E_coord_mask.squeeze(-1)] = -1 return (edge_s, edge_v), edge_index.transpose(0, 1) 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
from argparse import Namespace
import torchimport torch.nn as nnimport torch.nn.functional as F
from .features import GVPGraphEmbeddingfrom .gvp_modules import GVPConvLayer, LayerNorm from .gvp_utils import unflatten_graph
class GVPEncoder(nn.Module):
def __init__(self, args): super().__init__() self.args = args self.embed_graph = GVPGraphEmbedding(args)
node_hidden_dim = (args.node_hidden_dim_scalar, args.node_hidden_dim_vector) edge_hidden_dim = (args.edge_hidden_dim_scalar, args.edge_hidden_dim_vector) conv_activations = (F.relu, torch.sigmoid) self.encoder_layers = nn.ModuleList( GVPConvLayer( node_hidden_dim, edge_hidden_dim, drop_rate=args.dropout, vector_gate=True, attention_heads=0, n_message=3, conv_activations=conv_activations, n_edge_gvps=0, eps=1e-4, layernorm=True, ) for i in range(args.num_encoder_layers) )
def forward(self, coords, coord_mask, padding_mask, confidence): node_embeddings, edge_embeddings, edge_index = self.embed_graph( coords, coord_mask, padding_mask, confidence) for i, layer in enumerate(self.encoder_layers): node_embeddings, edge_embeddings = layer(node_embeddings, edge_index, edge_embeddings)
node_embeddings = unflatten_graph(node_embeddings, coords.shape[0]) return node_embeddings123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473# Contents of this file are from the open source code for## Jing, B., Eismann, S., Suriana, P., Townshend, R. J. L., & Dror, R. (2020).# Learning from Protein Structure with Geometric Vector Perceptrons. In# International Conference on Learning Representations.## MIT License# # Copyright (c) 2020 Bowen Jing, Stephan Eismann, Patricia Suriana, Raphael Townshend, Ron Dror# # Permission is hereby granted, free of charge, to any person obtaining a copy# of this software and associated documentation files (the "Software"), to deal# in the Software without restriction, including without limitation the rights# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell# copies of the Software, and to permit persons to whom the Software is# furnished to do so, subject to the following conditions:# # The above copyright notice and this permission notice shall be included in all# copies or substantial portions of the Software.# # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE# SOFTWARE.
import typing as Timport torchfrom torch import nnimport torch.nn.functional as Ffrom torch_geometric.nn import MessagePassingfrom torch_scatter import scatter_add, scatter
def tuple_size(tp): return tuple([0 if a is None else a.size() for a in tp])
def tuple_sum(tp1, tp2): s1, v1 = tp1 s2, v2 = tp2 if v2 is None and v2 is None: return (s1 + s2, None) return (s1 + s2, v1 + v2)
def tuple_cat(*args, dim=-1): ''' Concatenates any number of tuples (s, V) elementwise. :param dim: dimension along which to concatenate when viewed as the `dim` index for the scalar-channel tensors. This means that `dim=-1` will be applied as `dim=-2` for the vector-channel tensors. ''' dim %= len(args[0][0].shape) s_args, v_args = list(zip(*args)) return torch.cat(s_args, dim=dim), torch.cat(v_args, dim=dim)
def tuple_index(x, idx): ''' Indexes into a tuple (s, V) along the first dimension. :param idx: any object which can be used to index into a `torch.Tensor` ''' return x[0][idx], x[1][idx]
def randn(n, dims, device="cpu"): ''' Returns random tuples (s, V) drawn elementwise from a normal distribution. :param n: number of data points :param dims: tuple of dimensions (n_scalar, n_vector) :return: (s, V) with s.shape = (n, n_scalar) and V.shape = (n, n_vector, 3) ''' return torch.randn(n, dims[0], device=device), \ torch.randn(n, dims[1], 3, device=device)
def _norm_no_nan(x, axis=-1, keepdims=False, eps=1e-8, sqrt=True): ''' L2 norm of tensor clamped above a minimum value `eps`. :param sqrt: if `False`, returns the square of the L2 norm ''' # clamp is slow # out = torch.clamp(torch.sum(torch.square(x), axis, keepdims), min=eps) out = torch.sum(torch.square(x), axis, keepdims) + eps return torch.sqrt(out) if sqrt else out
def _split(x, nv): ''' Splits a merged representation of (s, V) back into a tuple. Should be used only with `_merge(s, V)` and only if the tuple representation cannot be used. :param x: the `torch.Tensor` returned from `_merge` :param nv: the number of vector channels in the input to `_merge` ''' v = torch.reshape(x[..., -3*nv:], x.shape[:-1] + (nv, 3)) s = x[..., :-3*nv] return s, v
def _merge(s, v): ''' Merges a tuple (s, V) into a single `torch.Tensor`, where the vector channels are flattened and appended to the scalar channels. Should be used only if the tuple representation cannot be used. Use `_split(x, nv)` to reverse. ''' v = torch.reshape(v, v.shape[:-2] + (3*v.shape[-2],)) return torch.cat([s, v], -1)
class GVP(nn.Module): ''' Geometric Vector Perceptron. See manuscript and README.md for more details. :param in_dims: tuple (n_scalar, n_vector) :param out_dims: tuple (n_scalar, n_vector) :param h_dim: intermediate number of vector channels, optional :param activations: tuple of functions (scalar_act, vector_act) :param tuple_io: whether to keep accepting tuple inputs and outputs when vi or vo = 0 ''' def __init__(self, in_dims, out_dims, h_dim=None, vector_gate=False, activations=(F.relu, torch.sigmoid), tuple_io=True, eps=1e-8): super(GVP, self).__init__() self.si, self.vi = in_dims self.so, self.vo = out_dims self.tuple_io = tuple_io if self.vi: self.h_dim = h_dim or max(self.vi, self.vo) self.wh = nn.Linear(self.vi, self.h_dim, bias=False) self.ws = nn.Linear(self.h_dim + self.si, self.so) if self.vo: self.wv = nn.Linear(self.h_dim, self.vo, bias=False) if vector_gate: self.wg = nn.Linear(self.so, self.vo) else: self.ws = nn.Linear(self.si, self.so) self.vector_gate = vector_gate self.scalar_act, self.vector_act = activations self.eps = eps def forward(self, x): ''' :param x: tuple (s, V) of `torch.Tensor`, or (if vectors_in is 0), a single `torch.Tensor` :return: tuple (s, V) of `torch.Tensor`, or (if vectors_out is 0), a single `torch.Tensor` ''' if self.vi: s, v = x v = torch.transpose(v, -1, -2) vh = self.wh(v) vn = _norm_no_nan(vh, axis=-2, eps=self.eps) s = self.ws(torch.cat([s, vn], -1)) if self.scalar_act: s = self.scalar_act(s) if self.vo: v = self.wv(vh) v = torch.transpose(v, -1, -2) if self.vector_gate: g = self.wg(s).unsqueeze(-1) else: g = _norm_no_nan(v, axis=-1, keepdims=True, eps=self.eps) if self.vector_act: g = self.vector_act(g) v = v * g else: if self.tuple_io: assert x[1] is None x = x[0] s = self.ws(x) if self.scalar_act: s = self.scalar_act(s) if self.vo: v = torch.zeros(list(s.shape)[:-1] + [self.vo, 3], device=s.device) if self.vo: return (s, v) elif self.tuple_io: return (s, None) else: return s
class _VDropout(nn.Module): ''' Vector channel dropout where the elements of each vector channel are dropped together. ''' def __init__(self, drop_rate): super(_VDropout, self).__init__() self.drop_rate = drop_rate
def forward(self, x): ''' :param x: `torch.Tensor` corresponding to vector channels ''' if x is None: return None device = x.device if not self.training: return x mask = torch.bernoulli( (1 - self.drop_rate) * torch.ones(x.shape[:-1], device=device) ).unsqueeze(-1) x = mask * x / (1 - self.drop_rate) return x
class Dropout(nn.Module): ''' Combined dropout for tuples (s, V). Takes tuples (s, V) as input and as output. ''' def __init__(self, drop_rate): super(Dropout, self).__init__() self.sdropout = nn.Dropout(drop_rate) self.vdropout = _VDropout(drop_rate)
def forward(self, x): ''' :param x: tuple (s, V) of `torch.Tensor`, or single `torch.Tensor` (will be assumed to be scalar channels) ''' if type(x) is torch.Tensor: return self.sdropout(x) s, v = x return self.sdropout(s), self.vdropout(v)
class LayerNorm(nn.Module): ''' Combined LayerNorm for tuples (s, V). Takes tuples (s, V) as input and as output. ''' def __init__(self, dims, tuple_io=True, eps=1e-8): super(LayerNorm, self).__init__() self.tuple_io = tuple_io self.s, self.v = dims self.scalar_norm = nn.LayerNorm(self.s) self.eps = eps def forward(self, x): ''' :param x: tuple (s, V) of `torch.Tensor`, or single `torch.Tensor` (will be assumed to be scalar channels) ''' if not self.v: if self.tuple_io: return self.scalar_norm(x[0]), None return self.scalar_norm(x) s, v = x vn = _norm_no_nan(v, axis=-1, keepdims=True, sqrt=False, eps=self.eps) nonzero_mask = (vn > 2 * self.eps) vn = torch.sum(vn * nonzero_mask, dim=-2, keepdim=True ) / (self.eps + torch.sum(nonzero_mask, dim=-2, keepdim=True)) vn = torch.sqrt(vn + self.eps) v = nonzero_mask * (v / vn) return self.scalar_norm(s), v
class GVPConv(MessagePassing): ''' Graph convolution / message passing with Geometric Vector Perceptrons. Takes in a graph with node and edge embeddings, and returns new node embeddings. This does NOT do residual updates and pointwise feedforward layers ---see `GVPConvLayer`. :param in_dims: input node embedding dimensions (n_scalar, n_vector) :param out_dims: output node embedding dimensions (n_scalar, n_vector) :param edge_dims: input edge embedding dimensions (n_scalar, n_vector) :param n_layers: number of GVPs in the message function :param module_list: preconstructed message function, overrides n_layers :param aggr: should be "add" if some incoming edges are masked, as in a masked autoregressive decoder architecture ''' def __init__(self, in_dims, out_dims, edge_dims, n_layers=3, vector_gate=False, module_list=None, aggr="mean", eps=1e-8, activations=(F.relu, torch.sigmoid)): super(GVPConv, self).__init__(aggr=aggr) self.eps = eps self.si, self.vi = in_dims self.so, self.vo = out_dims self.se, self.ve = edge_dims module_list = module_list or [] if not module_list: if n_layers == 1: module_list.append( GVP((2*self.si + self.se, 2*self.vi + self.ve), (self.so, self.vo), activations=(None, None))) else: module_list.append( GVP((2*self.si + self.se, 2*self.vi + self.ve), out_dims, vector_gate=vector_gate, activations=activations) ) for i in range(n_layers - 2): module_list.append(GVP(out_dims, out_dims, vector_gate=vector_gate)) module_list.append(GVP(out_dims, out_dims, activations=(None, None))) self.message_func = nn.Sequential(*module_list)
def forward(self, x, edge_index, edge_attr): ''' :param x: tuple (s, V) of `torch.Tensor` :param edge_index: array of shape [2, n_edges] :param edge_attr: tuple (s, V) of `torch.Tensor` ''' x_s, x_v = x message = self.propagate(edge_index, s=x_s, v=x_v.reshape(x_v.shape[0], 3*x_v.shape[1]), edge_attr=edge_attr) return _split(message, self.vo)
def message(self, s_i, v_i, s_j, v_j, edge_attr): v_j = v_j.view(v_j.shape[0], v_j.shape[1]//3, 3) v_i = v_i.view(v_i.shape[0], v_i.shape[1]//3, 3) message = tuple_cat((s_j, v_j), edge_attr, (s_i, v_i)) message = self.message_func(message) return _merge(*message)
class GVPConvLayer(nn.Module): ''' Full graph convolution / message passing layer with Geometric Vector Perceptrons. Residually updates node embeddings with aggregated incoming messages, applies a pointwise feedforward network to node embeddings, and returns updated node embeddings. To only compute the aggregated messages, see `GVPConv`. :param node_dims: node embedding dimensions (n_scalar, n_vector) :param edge_dims: input edge embedding dimensions (n_scalar, n_vector) :param n_message: number of GVPs to use in message function :param n_feedforward: number of GVPs to use in feedforward function :param drop_rate: drop probability in all dropout layers :param autoregressive: if `True`, this `GVPConvLayer` will be used with a different set of input node embeddings for messages where src >= dst ''' def __init__(self, node_dims, edge_dims, vector_gate=False, n_message=3, n_feedforward=2, drop_rate=.1, autoregressive=False, attention_heads=0, conv_activations=(F.relu, torch.sigmoid), n_edge_gvps=0, layernorm=True, eps=1e-8): super(GVPConvLayer, self).__init__() if attention_heads == 0: self.conv = GVPConv( node_dims, node_dims, edge_dims, n_layers=n_message, vector_gate=vector_gate, aggr="add" if autoregressive else "mean", activations=conv_activations, eps=eps, ) else: raise NotImplementedError if layernorm: self.norm = nn.ModuleList([LayerNorm(node_dims, eps=eps) for _ in range(2)]) else: self.norm = nn.ModuleList([nn.Identity() for _ in range(2)]) self.dropout = nn.ModuleList([Dropout(drop_rate) for _ in range(2)])
ff_func = [] if n_feedforward == 1: ff_func.append(GVP(node_dims, node_dims, activations=(None, None))) else: hid_dims = 4*node_dims[0], 2*node_dims[1] ff_func.append(GVP(node_dims, hid_dims, vector_gate=vector_gate)) for i in range(n_feedforward-2): ff_func.append(GVP(hid_dims, hid_dims, vector_gate=vector_gate)) ff_func.append(GVP(hid_dims, node_dims, activations=(None, None))) self.ff_func = nn.Sequential(*ff_func)
self.edge_message_func = None if n_edge_gvps > 0: si, vi = node_dims se, ve = edge_dims module_list = [ GVP((2*si + se, 2*vi + ve), edge_dims, vector_gate=vector_gate) ] for i in range(n_edge_gvps - 2): module_list.append(GVP(edge_dims, edge_dims, vector_gate=vector_gate)) if n_edge_gvps > 1: module_list.append(GVP(edge_dims, edge_dims, activations=(None, None))) self.edge_message_func = nn.Sequential(*module_list) if layernorm: self.edge_norm = LayerNorm(edge_dims, eps=eps) else: self.edge_norm = nn.Identity() self.edge_dropout = Dropout(drop_rate)
def forward(self, x, edge_index, edge_attr, autoregressive_x=None, node_mask=None): ''' :param x: tuple (s, V) of `torch.Tensor` :param edge_index: array of shape [2, n_edges] :param edge_attr: tuple (s, V) of `torch.Tensor` :param autoregressive_x: tuple (s, V) of `torch.Tensor`. If not `None`, will be used as srcqq node embeddings for forming messages where src >= dst. The corrent node embeddings `x` will still be the base of the update and the pointwise feedforward. :param node_mask: array of type `bool` to index into the first dim of node embeddings (s, V). If not `None`, only these nodes will be updated. ''' if self.edge_message_func: src, dst = edge_index if autoregressive_x is None: x_src = x[0][src], x[1][src] else: mask = (src < dst).unsqueeze(-1) x_src = ( torch.where(mask, x[0][src], autoregressive_x[0][src]), torch.where(mask.unsqueeze(-1), x[1][src], autoregressive_x[1][src]) ) x_dst = x[0][dst], x[1][dst] x_edge = ( torch.cat([x_src[0], edge_attr[0], x_dst[0]], dim=-1), torch.cat([x_src[1], edge_attr[1], x_dst[1]], dim=-2) ) edge_attr_dh = self.edge_message_func(x_edge) edge_attr = self.edge_norm(tuple_sum(edge_attr, self.edge_dropout(edge_attr_dh))) if autoregressive_x is not None: src, dst = edge_index mask = src < dst edge_index_forward = edge_index[:, mask] edge_index_backward = edge_index[:, ~mask] edge_attr_forward = tuple_index(edge_attr, mask) edge_attr_backward = tuple_index(edge_attr, ~mask) dh = tuple_sum( self.conv(x, edge_index_forward, edge_attr_forward), self.conv(autoregressive_x, edge_index_backward, edge_attr_backward) ) count = scatter_add(torch.ones_like(dst), dst, dim_size=dh[0].size(0)).clamp(min=1).unsqueeze(-1) dh = dh[0] / count, dh[1] / count.unsqueeze(-1)
else: dh = self.conv(x, edge_index, edge_attr) if node_mask is not None: x_ = x x, dh = tuple_index(x, node_mask), tuple_index(dh, node_mask) x = self.norm[0](tuple_sum(x, self.dropout[0](dh))) dh = self.ff_func(x) x = self.norm[1](tuple_sum(x, self.dropout[1](dh))) if node_mask is not None: x_[0][node_mask], x_[1][node_mask] = x[0], x[1] x = x_
return x, edge_attr123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import argparsefrom typing import Any, Dict, List, Optional, Tuple, NamedTupleimport torchfrom torch import nnfrom torch import Tensorimport torch.nn.functional as Ffrom scipy.spatial import transform
from esm.data import Alphabet
from .features import DihedralFeaturesfrom .gvp_encoder import GVPEncoderfrom .gvp_utils import unflatten_graphfrom .gvp_transformer_encoder import GVPTransformerEncoderfrom .transformer_decoder import TransformerDecoderfrom .util import rotate, CoordBatchConverter
class GVPTransformerModel(nn.Module): """ GVP-Transformer inverse folding model.
Architecture: Geometric GVP-GNN as initial layers, followed by sequence-to-sequence Transformer encoder and decoder. """
def __init__(self, args, alphabet): super().__init__() encoder_embed_tokens = self.build_embedding( args, alphabet, args.encoder_embed_dim, ) decoder_embed_tokens = self.build_embedding( args, alphabet, args.decoder_embed_dim, ) encoder = self.build_encoder(args, alphabet, encoder_embed_tokens) decoder = self.build_decoder(args, alphabet, decoder_embed_tokens) self.args = args self.encoder = encoder self.decoder = decoder
@classmethod def build_encoder(cls, args, src_dict, embed_tokens): encoder = GVPTransformerEncoder(args, src_dict, embed_tokens) return encoder
@classmethod def build_decoder(cls, args, tgt_dict, embed_tokens): decoder = TransformerDecoder( args, tgt_dict, embed_tokens, ) return decoder
@classmethod def build_embedding(cls, args, dictionary, embed_dim): num_embeddings = len(dictionary) padding_idx = dictionary.padding_idx emb = nn.Embedding(num_embeddings, embed_dim, padding_idx) nn.init.normal_(emb.weight, mean=0, std=embed_dim ** -0.5) nn.init.constant_(emb.weight[padding_idx], 0) return emb
def forward( self, coords, padding_mask, confidence, prev_output_tokens, return_all_hiddens: bool = False, features_only: bool = False, ): encoder_out = self.encoder(coords, padding_mask, confidence, return_all_hiddens=return_all_hiddens) logits, extra = self.decoder( prev_output_tokens, encoder_out=encoder_out, features_only=features_only, return_all_hiddens=return_all_hiddens, ) return logits, extra def sample(self, coords, partial_seq=None, temperature=1.0, confidence=None): """ Samples sequences based on multinomial sampling (no beam search).
Args: coords: L x 3 x 3 list representing one backbone partial_seq: Optional, partial sequence with mask tokens if part of the sequence is known temperature: sampling temperature, use low temperature for higher sequence recovery and high temperature for higher diversity confidence: optional length L list of confidence scores for coordinates """ L = len(coords) # Convert to batch format batch_converter = CoordBatchConverter(self.decoder.dictionary) batch_coords, confidence, _, _, padding_mask = ( batch_converter([(coords, confidence, None)]) ) # Start with prepend token mask_idx = self.decoder.dictionary.get_idx('<mask>') sampled_tokens = torch.full((1, 1+L), mask_idx, dtype=int) sampled_tokens[0, 0] = self.decoder.dictionary.get_idx('<cath>') if partial_seq is not None: for i, c in enumerate(partial_seq): sampled_tokens[0, i+1] = self.decoder.dictionary.get_idx(c) # Save incremental states for faster sampling incremental_state = dict() # Run encoder only once encoder_out = self.encoder(batch_coords, padding_mask, confidence) # Decode one token at a time for i in range(1, L+1): if sampled_tokens[0, i] != mask_idx: continue logits, _ = self.decoder( sampled_tokens[:, :i], encoder_out, incremental_state=incremental_state, ) logits = logits[0].transpose(0, 1) logits /= temperature probs = F.softmax(logits, dim=-1) sampled_tokens[:, i] = torch.multinomial(probs, 1).squeeze(-1) sampled_seq = sampled_tokens[0, 1:] # Convert back to string via lookup return ''.join([self.decoder.dictionary.get_tok(a) for a in sampled_seq])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184# Copyright (c) Facebook, Inc. and its affiliates.## Contents of this file were adapted from the open source fairseq repository.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import argparseimport mathfrom typing import Dict, List, Optional
import torchimport torch.nn as nnfrom torch import Tensor
from esm.modules import SinusoidalPositionalEmbeddingfrom .features import GVPInputFeaturizer, DihedralFeaturesfrom .gvp_encoder import GVPEncoderfrom .transformer_layer import TransformerEncoderLayerfrom .util import nan_to_num, get_rotation_frames, rotate, rbf
class GVPTransformerEncoder(nn.Module): """ Transformer encoder consisting of *args.encoder.layers* layers. Each layer is a :class:`TransformerEncoderLayer`.
Args: args (argparse.Namespace): parsed command-line arguments dictionary (~fairseq.data.Dictionary): encoding dictionary embed_tokens (torch.nn.Embedding): input embedding """
def __init__(self, args, dictionary, embed_tokens): super().__init__() self.args = args self.dictionary = dictionary
self.dropout_module = nn.Dropout(args.dropout)
embed_dim = embed_tokens.embedding_dim self.padding_idx = embed_tokens.padding_idx
self.embed_tokens = embed_tokens self.embed_scale = math.sqrt(embed_dim) self.embed_positions = SinusoidalPositionalEmbedding( embed_dim, self.padding_idx, ) self.embed_gvp_input_features = nn.Linear(15, embed_dim) self.embed_confidence = nn.Linear(16, embed_dim) self.embed_dihedrals = DihedralFeatures(embed_dim)
gvp_args = argparse.Namespace() for k, v in vars(args).items(): if k.startswith("gvp_"): setattr(gvp_args, k[4:], v) self.gvp_encoder = GVPEncoder(gvp_args) gvp_out_dim = gvp_args.node_hidden_dim_scalar + (3 * gvp_args.node_hidden_dim_vector) self.embed_gvp_output = nn.Linear(gvp_out_dim, embed_dim)
self.layers = nn.ModuleList([]) self.layers.extend( [self.build_encoder_layer(args) for i in range(args.encoder_layers)] ) self.num_layers = len(self.layers) self.layer_norm = nn.LayerNorm(embed_dim)
def build_encoder_layer(self, args): return TransformerEncoderLayer(args)
def forward_embedding(self, coords, padding_mask, confidence): """ Args: coords: N, CA, C backbone coordinates in shape length x 3 (atoms) x 3 padding_mask: boolean Tensor (true for padding) of shape length confidence: confidence scores between 0 and 1 of shape length """ components = dict() coord_mask = torch.all(torch.all(torch.isfinite(coords), dim=-1), dim=-1) coords = nan_to_num(coords) mask_tokens = ( padding_mask * self.dictionary.padding_idx + ~padding_mask * self.dictionary.get_idx("<mask>") ) components["tokens"] = self.embed_tokens(mask_tokens) * self.embed_scale components["diherals"] = self.embed_dihedrals(coords)
# GVP encoder gvp_out_scalars, gvp_out_vectors = self.gvp_encoder(coords, coord_mask, padding_mask, confidence) R = get_rotation_frames(coords) # Rotate to local rotation frame for rotation-invariance gvp_out_features = torch.cat([ gvp_out_scalars, rotate(gvp_out_vectors, R.transpose(-2, -1)).flatten(-2, -1), ], dim=-1) components["gvp_out"] = self.embed_gvp_output(gvp_out_features)
components["confidence"] = self.embed_confidence( rbf(confidence, 0., 1.))
# In addition to GVP encoder outputs, also directly embed GVP input node # features to the Transformer scalar_features, vector_features = GVPInputFeaturizer.get_node_features( coords, coord_mask, with_coord_mask=False) features = torch.cat([ scalar_features, rotate(vector_features, R.transpose(-2, -1)).flatten(-2, -1), ], dim=-1) components["gvp_input_features"] = self.embed_gvp_input_features(features)
embed = sum(components.values()) # for k, v in components.items(): # print(k, torch.mean(v, dim=(0,1)), torch.std(v, dim=(0,1)))
x = embed x = x + self.embed_positions(mask_tokens) x = self.dropout_module(x) return x, components
def forward( self, coords, encoder_padding_mask, confidence, return_all_hiddens: bool = False, ): """ Args: coords (Tensor): backbone coordinates shape batch_size x num_residues x num_atoms (3 for N, CA, C) x 3 encoder_padding_mask (ByteTensor): the positions of padding elements of shape `(batch_size x num_residues)` confidence (Tensor): the confidence score of shape (batch_size x num_residues). The value is between 0. and 1. for each residue coordinate, or -1. if no coordinate is given return_all_hiddens (bool, optional): also return all of the intermediate hidden states (default: False).
Returns: dict: - **encoder_out** (Tensor): the last encoder layer's output of shape `(num_residues, batch_size, embed_dim)` - **encoder_padding_mask** (ByteTensor): the positions of padding elements of shape `(batch_size, num_residues)` - **encoder_embedding** (Tensor): the (scaled) embedding lookup of shape `(batch_size, num_residues, embed_dim)` - **encoder_states** (List[Tensor]): all intermediate hidden states of shape `(num_residues, batch_size, embed_dim)`. Only populated if *return_all_hiddens* is True. """ x, encoder_embedding = self.forward_embedding(coords, encoder_padding_mask, confidence) # account for padding while computing the representation x = x * (1 - encoder_padding_mask.unsqueeze(-1).type_as(x))
# B x T x C -> T x B x C x = x.transpose(0, 1)
encoder_states = []
if return_all_hiddens: encoder_states.append(x)
# encoder layers for layer in self.layers: x = layer( x, encoder_padding_mask=encoder_padding_mask ) if return_all_hiddens: assert encoder_states is not None encoder_states.append(x)
if self.layer_norm is not None: x = self.layer_norm(x)
return { "encoder_out": [x], # T x B x C "encoder_padding_mask": [encoder_padding_mask], # B x T "encoder_embedding": [encoder_embedding], # dictionary "encoder_states": encoder_states, # List[T x B x C] }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import torch
def flatten_graph(node_embeddings, edge_embeddings, edge_index): """ Flattens the graph into a batch size one (with disconnected subgraphs for each example) to be compatible with pytorch-geometric package. Args: node_embeddings: node embeddings in tuple form (scalar, vector) - scalar: shape batch size x nodes x node_embed_dim - vector: shape batch size x nodes x node_embed_dim x 3 edge_embeddings: edge embeddings of in tuple form (scalar, vector) - scalar: shape batch size x edges x edge_embed_dim - vector: shape batch size x edges x edge_embed_dim x 3 edge_index: shape batch_size x 2 (source node and target node) x edges Returns: node_embeddings: node embeddings in tuple form (scalar, vector) - scalar: shape batch total_nodes x node_embed_dim - vector: shape batch total_nodes x node_embed_dim x 3 edge_embeddings: edge embeddings of in tuple form (scalar, vector) - scalar: shape batch total_edges x edge_embed_dim - vector: shape batch total_edges x edge_embed_dim x 3 edge_index: shape 2 x total_edges """ x_s, x_v = node_embeddings e_s, e_v = edge_embeddings batch_size, N = x_s.shape[0], x_s.shape[1] node_embeddings = (torch.flatten(x_s, 0, 1), torch.flatten(x_v, 0, 1)) edge_embeddings = (torch.flatten(e_s, 0, 1), torch.flatten(e_v, 0, 1))
edge_mask = torch.any(edge_index != -1, dim=1) # Re-number the nodes by adding batch_idx * N to each batch edge_index = edge_index + (torch.arange(batch_size, device=edge_index.device) * N).unsqueeze(-1).unsqueeze(-1) edge_index = edge_index.permute(1, 0, 2).flatten(1, 2) edge_mask = edge_mask.flatten() edge_index = edge_index[:, edge_mask] edge_embeddings = ( edge_embeddings[0][edge_mask, :], edge_embeddings[1][edge_mask, :] ) return node_embeddings, edge_embeddings, edge_index
def unflatten_graph(node_embeddings, batch_size): """ Unflattens node embeddings. Args: node_embeddings: node embeddings in tuple form (scalar, vector) - scalar: shape batch total_nodes x node_embed_dim - vector: shape batch total_nodes x node_embed_dim x 3 batch_size: int Returns: node_embeddings: node embeddings in tuple form (scalar, vector) - scalar: shape batch size x nodes x node_embed_dim - vector: shape batch size x nodes x node_embed_dim x 3 """ x_s, x_v = node_embeddings x_s = x_s.reshape(batch_size, -1, x_s.shape[1]) x_v = x_v.reshape(batch_size, -1, x_v.shape[1], x_v.shape[2]) return (x_s, x_v)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import biotite.structureimport numpy as npimport torchfrom typing import Sequence, Tuple, List
from esm.inverse_folding.util import ( load_structure, extract_coords_from_structure, load_coords, get_sequence_loss, get_encoder_output,)
def extract_coords_from_complex(structure: biotite.structure.AtomArray): """ Args: structure: biotite AtomArray Returns: Tuple (coords_list, seq_list) - coords: Dictionary mapping chain ids to L x 3 x 3 array for N, CA, C coordinates representing the backbone of each chain - seqs: Dictionary mapping chain ids to native sequences of each chain """ coords = {} seqs = {} all_chains = biotite.structure.get_chains(structure) for chain_id in all_chains: chain = structure[structure.chain_id == chain_id] coords[chain_id], seqs[chain_id] = extract_coords_from_structure(chain) return coords, seqs
def load_complex_coords(fpath, chains): """ Args: fpath: filepath to either pdb or cif file chains: the chain ids (the order matters for autoregressive model) Returns: Tuple (coords_list, seq_list) - coords: Dictionary mapping chain ids to L x 3 x 3 array for N, CA, C coordinates representing the backbone of each chain - seqs: Dictionary mapping chain ids to native sequences of each chain """ structure = load_structure(fpath, chains) return extract_coords_from_complex(structure)
def _concatenate_coords(coords, target_chain_id, padding_length=10): """ Args: coords: Dictionary mapping chain ids to L x 3 x 3 array for N, CA, C coordinates representing the backbone of each chain target_chain_id: The chain id to sample sequences for padding_length: Length of padding between concatenated chains Returns: Tuple (coords, seq) - coords is an L x 3 x 3 array for N, CA, C coordinates, a concatenation of the chains with padding in between - seq is the extracted sequence, with padding tokens inserted between the concatenated chains """ pad_coords = np.full((padding_length, 3, 3), np.nan, dtype=np.float32) # For best performance, put the target chain first in concatenation. coords_list = [coords[target_chain_id]] for chain_id in coords: if chain_id == target_chain_id: continue coords_list.append(pad_coords) coords_list.append(coords[chain_id]) coords_concatenated = np.concatenate(coords_list, axis=0) return coords_concatenated
def sample_sequence_in_complex(model, coords, target_chain_id, temperature=1., padding_length=10): """ Samples sequence for one chain in a complex. Args: model: An instance of the GVPTransformer model coords: Dictionary mapping chain ids to L x 3 x 3 array for N, CA, C coordinates representing the backbone of each chain target_chain_id: The chain id to sample sequences for padding_length: padding length in between chains Returns: Sampled sequence for the target chain """ target_chain_len = coords[target_chain_id].shape[0] all_coords = _concatenate_coords(coords, target_chain_id)
# Supply padding tokens for other chains to avoid unused sampling for speed padding_pattern = ['<pad>'] * all_coords.shape[0] for i in range(target_chain_len): padding_pattern[i] = '<mask>' sampled = model.sample(all_coords, partial_seq=padding_pattern, temperature=temperature) sampled = sampled[:target_chain_len] return sampled
def score_sequence_in_complex(model, alphabet, coords, target_chain_id, target_seq, padding_length=10): """ Scores sequence for one chain in a complex. Args: model: An instance of the GVPTransformer model alphabet: Alphabet for the model coords: Dictionary mapping chain ids to L x 3 x 3 array for N, CA, C coordinates representing the backbone of each chain target_chain_id: The chain id to sample sequences for target_seq: Target sequence for the target chain for scoring. padding_length: padding length in between chains Returns: Tuple (ll_fullseq, ll_withcoord) - ll_fullseq: Average log-likelihood over the full target chain - ll_withcoord: Average log-likelihood in target chain excluding those residues without coordinates """ all_coords = _concatenate_coords(coords, target_chain_id)
loss, target_padding_mask = get_sequence_loss(model, alphabet, all_coords, target_seq) ll_fullseq = -np.sum(loss * ~target_padding_mask) / np.sum( ~target_padding_mask)
# Also calculate average when excluding masked portions coord_mask = np.all(np.isfinite(coords[target_chain_id]), axis=(-1, -2)) ll_withcoord = -np.sum(loss * coord_mask) / np.sum(coord_mask) return ll_fullseq, ll_withcoord
def get_encoder_output_for_complex(model, alphabet, coords, target_chain_id): """ Args: model: An instance of the GVPTransformer model alphabet: Alphabet for the model coords: Dictionary mapping chain ids to L x 3 x 3 array for N, CA, C coordinates representing the backbone of each chain target_chain_id: The chain id to sample sequences for Returns: Dictionary mapping chain id to encoder output for each chain """ all_coords = _concatenate_coords(coords, target_chain_id) all_rep = get_encoder_output(model, alphabet, all_coords) target_chain_len = coords[target_chain_id].shape[0] return all_rep[:target_chain_len]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228# Copyright (c) Facebook, Inc. and its affiliates.## Contents of this file were adapted from the open source fairseq repository.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import mathfrom typing import Any, Dict, List, Optional
import torchimport torch.nn as nnfrom torch import Tensor
from esm.modules import SinusoidalPositionalEmbeddingfrom .transformer_layer import TransformerDecoderLayer
def fill_with_neg_inf(t): """FP16-compatible function that fills a tensor with -inf.""" return t.float().fill_(float("-inf")).type_as(t)
class TransformerDecoder(nn.Module): """ Transformer decoder consisting of *args.decoder.layers* layers. Each layer is a :class:`TransformerDecoderLayer`.
Args: args (argparse.Namespace): parsed command-line arguments dictionary (~fairseq.data.Dictionary): decoding dictionary embed_tokens (torch.nn.Embedding): output embedding no_encoder_attn (bool, optional): whether to attend to encoder outputs (default: False). """
def __init__( self, args, dictionary, embed_tokens, ): super().__init__() self.args = args self.dictionary = dictionary self._future_mask = torch.empty(0)
self.dropout_module = nn.Dropout(args.dropout)
input_embed_dim = embed_tokens.embedding_dim embed_dim = args.decoder_embed_dim self.embed_dim = embed_dim
self.padding_idx = embed_tokens.padding_idx
self.embed_tokens = embed_tokens self.embed_scale = math.sqrt(embed_dim)
self.project_in_dim = ( nn.Linear(input_embed_dim, embed_dim, bias=False) if embed_dim != input_embed_dim else None ) self.embed_positions = SinusoidalPositionalEmbedding( embed_dim, self.padding_idx, )
self.layers = nn.ModuleList([]) self.layers.extend( [ self.build_decoder_layer(args) for _ in range(args.decoder_layers) ] ) self.num_layers = len(self.layers) self.layer_norm = nn.LayerNorm(embed_dim)
self.build_output_projection(args, dictionary)
def build_output_projection(self, args, dictionary): self.output_projection = nn.Linear( args.decoder_embed_dim, len(dictionary), bias=False ) nn.init.normal_( self.output_projection.weight, mean=0, std=args.decoder_embed_dim ** -0.5 )
def build_decoder_layer(self, args): return TransformerDecoderLayer(args)
def forward( self, prev_output_tokens, encoder_out: Optional[Dict[str, List[Tensor]]] = None, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, features_only: bool = False, return_all_hiddens: bool = False, ): """ Args: prev_output_tokens (LongTensor): previous decoder outputs of shape `(batch, tgt_len)`, for teacher forcing encoder_out (optional): output from the encoder, used for encoder-side attention, should be of size T x B x C incremental_state (dict): dictionary used for storing state during :ref:`Incremental decoding` features_only (bool, optional): only return features without applying output layer (default: False).
Returns: tuple: - the decoder's output of shape `(batch, tgt_len, vocab)` - a dictionary with any model-specific outputs """
x, extra = self.extract_features( prev_output_tokens, encoder_out=encoder_out, incremental_state=incremental_state, )
if not features_only: x = self.output_layer(x) x = x.transpose(1, 2) # B x T x C -> B x C x T return x, extra
def extract_features( self, prev_output_tokens, encoder_out: Optional[Dict[str, List[Tensor]]], incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, ): """ Similar to *forward* but only return features.
Includes several features from "Jointly Learning to Align and Translate with Transformer Models" (Garg et al., EMNLP 2019).
Returns: tuple: - the decoder's features of shape `(batch, tgt_len, embed_dim)` - a dictionary with any model-specific outputs """ bs, slen = prev_output_tokens.size()
enc: Optional[Tensor] = None padding_mask: Optional[Tensor] = None if encoder_out is not None and len(encoder_out["encoder_out"]) > 0: enc = encoder_out["encoder_out"][0] assert ( enc.size()[1] == bs ), f"Expected enc.shape == (t, {bs}, c) got {enc.shape}" if encoder_out is not None and len(encoder_out["encoder_padding_mask"]) > 0: padding_mask = encoder_out["encoder_padding_mask"][0]
# embed positions positions = self.embed_positions( prev_output_tokens )
if incremental_state is not None: prev_output_tokens = prev_output_tokens[:, -1:] positions = positions[:, -1:]
# embed tokens and positions x = self.embed_scale * self.embed_tokens(prev_output_tokens)
if self.project_in_dim is not None: x = self.project_in_dim(x)
x += positions
x = self.dropout_module(x)
# B x T x C -> T x B x C x = x.transpose(0, 1)
self_attn_padding_mask: Optional[Tensor] = None if prev_output_tokens.eq(self.padding_idx).any(): self_attn_padding_mask = prev_output_tokens.eq(self.padding_idx)
# decoder layers attn: Optional[Tensor] = None inner_states: List[Optional[Tensor]] = [x] for idx, layer in enumerate(self.layers): if incremental_state is None: self_attn_mask = self.buffered_future_mask(x) else: self_attn_mask = None
x, layer_attn, _ = layer( x, enc, padding_mask, incremental_state, self_attn_mask=self_attn_mask, self_attn_padding_mask=self_attn_padding_mask, need_attn=False, need_head_weights=False, ) inner_states.append(x)
if self.layer_norm is not None: x = self.layer_norm(x)
# T x B x C -> B x C x T x = x.transpose(0, 1)
return x, {"inner_states": inner_states}
def output_layer(self, features): """Project features to the vocabulary size.""" return self.output_projection(features)
def buffered_future_mask(self, tensor): dim = tensor.size(0) # self._future_mask.device != tensor.device is not working in TorchScript. This is a workaround. if ( self._future_mask.size(0) == 0 or (not self._future_mask.device == tensor.device) or self._future_mask.size(0) < dim ): self._future_mask = torch.triu( fill_with_neg_inf(torch.zeros([dim, dim])), 1 ) self._future_mask = self._future_mask.to(tensor) return self._future_mask[:dim, :dim]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304# Copyright (c) Facebook, Inc. and its affiliates.## Contents of this file were adapted from the open source fairseq repository.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
from typing import Dict, List, Optional
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom esm.multihead_attention import MultiheadAttentionfrom torch import Tensor
class TransformerEncoderLayer(nn.Module): """Encoder layer block. `layernorm -> dropout -> add residual`
Args: args (argparse.Namespace): parsed command-line arguments """
def __init__(self, args): super().__init__() self.args = args self.embed_dim = args.encoder_embed_dim self.self_attn = self.build_self_attention(self.embed_dim, args) self.self_attn_layer_norm = torch.nn.LayerNorm(self.embed_dim) self.dropout_module = nn.Dropout(args.dropout) self.activation_fn = F.relu self.fc1 = self.build_fc1( self.embed_dim, args.encoder_ffn_embed_dim, ) self.fc2 = self.build_fc2( args.encoder_ffn_embed_dim, self.embed_dim, )
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
def build_fc1(self, input_dim, output_dim): return nn.Linear(input_dim, output_dim)
def build_fc2(self, input_dim, output_dim): return nn.Linear(input_dim, output_dim)
def build_self_attention(self, embed_dim, args): return MultiheadAttention( embed_dim, args.encoder_attention_heads, dropout=args.attention_dropout, self_attention=True, )
def residual_connection(self, x, residual): return residual + x
def forward( self, x, encoder_padding_mask: Optional[Tensor], attn_mask: Optional[Tensor] = None, ): """ Args: x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)` encoder_padding_mask (ByteTensor): binary ByteTensor of shape `(batch, seq_len)` where padding elements are indicated by ``1``. attn_mask (ByteTensor): binary tensor of shape `(tgt_len, src_len)`, where `tgt_len` is the length of output and `src_len` is the length of input, though here both are equal to `seq_len`. `attn_mask[tgt_i, src_j] = 1` means that when calculating the embedding for `tgt_i`, we exclude (mask out) `src_j`. This is useful for strided self-attention.
Returns: encoded output of shape `(seq_len, batch, embed_dim)` """ # anything in original attn_mask = 1, becomes -1e8 # anything in original attn_mask = 0, becomes 0 # Note that we cannot use -inf here, because at some edge cases, # the attention weight (before softmax) for some padded element in query # will become -inf, which results in NaN in model parameters if attn_mask is not None: attn_mask = attn_mask.masked_fill( attn_mask.to(torch.bool), -1e8 if x.dtype == torch.float32 else -1e4 )
residual = x x = self.self_attn_layer_norm(x) x, _ = self.self_attn( query=x, key=x, value=x, key_padding_mask=encoder_padding_mask, need_weights=False, attn_mask=attn_mask, ) x = self.dropout_module(x) x = self.residual_connection(x, residual)
residual = x x = self.final_layer_norm(x) x = self.activation_fn(self.fc1(x)) x = self.fc2(x) x = self.dropout_module(x) x = self.residual_connection(x, residual) return x
class TransformerDecoderLayer(nn.Module): """Decoder layer block. `layernorm -> dropout -> add residual`
Args: args (argparse.Namespace): parsed command-line arguments no_encoder_attn (bool, optional): whether to attend to encoder outputs (default: False). """
def __init__( self, args, no_encoder_attn=False, add_bias_kv=False, add_zero_attn=False ): super().__init__() self.embed_dim = args.decoder_embed_dim self.dropout_module = nn.Dropout(args.dropout)
self.self_attn = self.build_self_attention( self.embed_dim, args, add_bias_kv=add_bias_kv, add_zero_attn=add_zero_attn, ) self.nh = self.self_attn.num_heads self.head_dim = self.self_attn.head_dim
self.activation_fn = F.relu
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
if no_encoder_attn: self.encoder_attn = None self.encoder_attn_layer_norm = None else: self.encoder_attn = self.build_encoder_attention(self.embed_dim, args) self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
self.ffn_layernorm = ( LayerNorm(args.decoder_ffn_embed_dim) if getattr(args, "scale_fc", False) else None ) self.w_resid = ( nn.Parameter( torch.ones( self.embed_dim, ), requires_grad=True, ) if getattr(args, "scale_resids", False) else None )
self.fc1 = self.build_fc1( self.embed_dim, args.decoder_ffn_embed_dim, ) self.fc2 = self.build_fc2( args.decoder_ffn_embed_dim, self.embed_dim, )
self.final_layer_norm = nn.LayerNorm(self.embed_dim) self.need_attn = True
def build_fc1(self, input_dim, output_dim): return nn.Linear(input_dim, output_dim)
def build_fc2(self, input_dim, output_dim): return nn.Linear(input_dim, output_dim)
def build_self_attention( self, embed_dim, args, add_bias_kv=False, add_zero_attn=False ): return MultiheadAttention( embed_dim, args.decoder_attention_heads, dropout=args.attention_dropout, add_bias_kv=add_bias_kv, add_zero_attn=add_zero_attn, self_attention=True, )
def build_encoder_attention(self, embed_dim, args): return MultiheadAttention( embed_dim, args.decoder_attention_heads, kdim=args.encoder_embed_dim, vdim=args.encoder_embed_dim, dropout=args.attention_dropout, encoder_decoder_attention=True, )
def residual_connection(self, x, residual): return residual + x
def forward( self, x, encoder_out: Optional[torch.Tensor] = None, encoder_padding_mask: Optional[torch.Tensor] = None, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, prev_self_attn_state: Optional[List[torch.Tensor]] = None, prev_attn_state: Optional[List[torch.Tensor]] = None, self_attn_mask: Optional[torch.Tensor] = None, self_attn_padding_mask: Optional[torch.Tensor] = None, need_attn: bool = False, need_head_weights: bool = False, ): """ Args: x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)` encoder_padding_mask (ByteTensor, optional): binary ByteTensor of shape `(batch, src_len)` where padding elements are indicated by ``1``. need_attn (bool, optional): return attention weights need_head_weights (bool, optional): return attention weights for each head (default: return average over heads).
Returns: encoded output of shape `(seq_len, batch, embed_dim)` """ if need_head_weights: need_attn = True
residual = x x = self.self_attn_layer_norm(x) if prev_self_attn_state is not None: prev_key, prev_value = prev_self_attn_state[:2] saved_state: Dict[str, Optional[Tensor]] = { "prev_key": prev_key, "prev_value": prev_value, } if len(prev_self_attn_state) >= 3: saved_state["prev_key_padding_mask"] = prev_self_attn_state[2] assert incremental_state is not None self.self_attn._set_input_buffer(incremental_state, saved_state) _self_attn_input_buffer = self.self_attn._get_input_buffer(incremental_state) y = x
x, attn = self.self_attn( query=x, key=y, value=y, key_padding_mask=self_attn_padding_mask, incremental_state=incremental_state, need_weights=False, attn_mask=self_attn_mask, ) x = self.dropout_module(x) x = self.residual_connection(x, residual)
if self.encoder_attn is not None and encoder_out is not None: residual = x x = self.encoder_attn_layer_norm(x) if prev_attn_state is not None: prev_key, prev_value = prev_attn_state[:2] saved_state: Dict[str, Optional[Tensor]] = { "prev_key": prev_key, "prev_value": prev_value, } if len(prev_attn_state) >= 3: saved_state["prev_key_padding_mask"] = prev_attn_state[2] assert incremental_state is not None self.encoder_attn._set_input_buffer(incremental_state, saved_state)
x, attn = self.encoder_attn( query=x, key=encoder_out, value=encoder_out, key_padding_mask=encoder_padding_mask, incremental_state=incremental_state, static_kv=True, need_weights=need_attn or (not self.training and self.need_attn), need_head_weights=need_head_weights, ) x = self.dropout_module(x) x = self.residual_connection(x, residual)
residual = x x = self.final_layer_norm(x)
x = self.activation_fn(self.fc1(x)) if self.ffn_layernorm is not None: x = self.ffn_layernorm(x) x = self.fc2(x) x = self.dropout_module(x) if self.w_resid is not None: residual = torch.mul(self.w_resid, residual) x = self.residual_connection(x, residual) return x, attn, None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import jsonimport math
import biotite.structurefrom biotite.structure.io import pdbx, pdbfrom biotite.structure.residues import get_residuesfrom biotite.structure import filter_backbonefrom biotite.structure import get_chainsfrom biotite.sequence import ProteinSequenceimport numpy as npfrom scipy.spatial import transformfrom scipy.stats import special_ortho_groupimport torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.utils.data as datafrom typing import Sequence, Tuple, List
from esm.data import BatchConverter
def load_structure(fpath, chain=None): """ Args: fpath: filepath to either pdb or cif file chain: the chain id or list of chain ids to load Returns: biotite.structure.AtomArray """ if fpath.endswith('cif'): with open(fpath) as fin: pdbxf = pdbx.PDBxFile.read(fin) structure = pdbx.get_structure(pdbxf, model=1) elif fpath.endswith('pdb'): with open(fpath) as fin: pdbf = pdb.PDBFile.read(fin) structure = pdb.get_structure(pdbf, model=1) bbmask = filter_backbone(structure) structure = structure[bbmask] all_chains = get_chains(structure) if len(all_chains) == 0: raise ValueError('No chains found in the input file.') if chain is None: chain_ids = all_chains elif isinstance(chain, list): chain_ids = chain else: chain_ids = [chain] for chain in chain_ids: if chain not in all_chains: raise ValueError(f'Chain {chain} not found in input file') chain_filter = [a.chain_id in chain_ids for a in structure] structure = structure[chain_filter] return structure
def extract_coords_from_structure(structure: biotite.structure.AtomArray): """ Args: structure: An instance of biotite AtomArray Returns: Tuple (coords, seq) - coords is an L x 3 x 3 array for N, CA, C coordinates - seq is the extracted sequence """ coords = get_atom_coords_residuewise(["N", "CA", "C"], structure) residue_identities = get_residues(structure)[1] seq = ''.join([ProteinSequence.convert_letter_3to1(r) for r in residue_identities]) return coords, seq
def load_coords(fpath, chain): """ Args: fpath: filepath to either pdb or cif file chain: the chain id Returns: Tuple (coords, seq) - coords is an L x 3 x 3 array for N, CA, C coordinates - seq is the extracted sequence """ structure = load_structure(fpath, chain) return extract_coords_from_structure(structure)
def get_atom_coords_residuewise(atoms: List[str], struct: biotite.structure.AtomArray): """ Example for atoms argument: ["N", "CA", "C"] """ def filterfn(s, axis=None): filters = np.stack([s.atom_name == name for name in atoms], axis=1) sum = filters.sum(0) if not np.all(sum <= np.ones(filters.shape[1])): raise RuntimeError("structure has multiple atoms with same name") index = filters.argmax(0) coords = s[index].coord coords[sum == 0] = float("nan") return coords
return biotite.structure.apply_residue_wise(struct, struct, filterfn)
def get_sequence_loss(model, alphabet, coords, seq): batch_converter = CoordBatchConverter(alphabet) batch = [(coords, None, seq)] coords, confidence, strs, tokens, padding_mask = batch_converter(batch) prev_output_tokens = tokens[:, :-1] target = tokens[:, 1:] target_padding_mask = (target == alphabet.padding_idx) logits, _ = model.forward(coords, padding_mask, confidence, prev_output_tokens) loss = F.cross_entropy(logits, target, reduction='none') loss = loss[0].detach().numpy() target_padding_mask = target_padding_mask[0].numpy() return loss, target_padding_mask
def score_sequence(model, alphabet, coords, seq): loss, target_padding_mask = get_sequence_loss(model, alphabet, coords, seq) ll_fullseq = -np.sum(loss * ~target_padding_mask) / np.sum(~target_padding_mask) # Also calculate average when excluding masked portions coord_mask = np.all(np.isfinite(coords), axis=(-1, -2)) ll_withcoord = -np.sum(loss * coord_mask) / np.sum(coord_mask) return ll_fullseq, ll_withcoord
def get_encoder_output(model, alphabet, coords): batch_converter = CoordBatchConverter(alphabet) # the batch_converter is essential for forming the correct input format batch = [(coords, None, None)] coords, confidence, _, _, padding_mask = batch_converter(batch) encoder_out = model.encoder.forward(coords, padding_mask, confidence, return_all_hiddens=False) # remove beginning and end (bos and eos tokens) return encoder_out['encoder_out'][0][1:-1, 0]
def rotate(v, R): """ Rotates a vector by a rotation matrix. Args: v: 3D vector, tensor of shape (length x batch_size x channels x 3) R: rotation matrix, tensor of shape (length x batch_size x 3 x 3)
Returns: Rotated version of v by rotation matrix R. """ R = R.unsqueeze(-3) v = v.unsqueeze(-1) return torch.sum(v * R, dim=-2)
def get_rotation_frames(coords): """ Returns a local rotation frame defined by N, CA, C positions.
Args: coords: coordinates, tensor of shape (batch_size x length x 3 x 3) where the third dimension is in order of N, CA, C
Returns: Local relative rotation frames in shape (batch_size x length x 3 x 3) """ v1 = coords[:, :, 2] - coords[:, :, 1] v2 = coords[:, :, 0] - coords[:, :, 1] e1 = normalize(v1, dim=-1) u2 = v2 - e1 * torch.sum(e1 * v2, dim=-1, keepdim=True) e2 = normalize(u2, dim=-1) e3 = torch.cross(e1, e2, dim=-1) R = torch.stack([e1, e2, e3], dim=-2) return R
def nan_to_num(ts, val=0.0): """ Replaces nans in tensor with a fixed value. """ val = torch.tensor(val, dtype=ts.dtype, device=ts.device) return torch.where(~torch.isfinite(ts), val, ts)
def rbf(values, v_min, v_max, n_bins=16): """ Returns RBF encodings in a new dimension at the end. """ rbf_centers = torch.linspace(v_min, v_max, n_bins, device=values.device) rbf_centers = rbf_centers.view([1] * len(values.shape) + [-1]) rbf_std = (v_max - v_min) / n_bins v_expand = torch.unsqueeze(values, -1) z = (values.unsqueeze(-1) - rbf_centers) / rbf_std return torch.exp(-z ** 2)
def norm(tensor, dim, eps=1e-8, keepdim=False): """ Returns L2 norm along a dimension. """ return torch.sqrt( torch.sum(torch.square(tensor), dim=dim, keepdim=keepdim) + eps)
def normalize(tensor, dim=-1): """ Normalizes a tensor along a dimension after removing nans. """ return nan_to_num( torch.div(tensor, norm(tensor, dim=dim, keepdim=True)) )
class CoordBatchConverter(BatchConverter): def __call__(self, raw_batch: Sequence[Tuple[Sequence, str]], device=None): """ Args: raw_batch: List of tuples (coords, confidence, seq) In each tuple, coords: list of floats, shape L x 3 x 3 confidence: list of floats, shape L; or scalar float; or None seq: string of length L Returns: coords: Tensor of shape batch_size x L x 3 x 3 confidence: Tensor of shape batch_size x L strs: list of strings tokens: LongTensor of shape batch_size x L padding_mask: ByteTensor of shape batch_size x L """ self.alphabet.cls_idx = self.alphabet.get_idx("<cath>") batch = [] for coords, confidence, seq in raw_batch: if confidence is None: confidence = 1. if isinstance(confidence, float) or isinstance(confidence, int): confidence = [float(confidence)] * len(coords) if seq is None: seq = 'X' * len(coords) batch.append(((coords, confidence), seq))
coords_and_confidence, strs, tokens = super().__call__(batch)
# pad beginning and end of each protein due to legacy reasons coords = [ F.pad(torch.tensor(cd), (0, 0, 0, 0, 1, 1), value=np.inf) for cd, _ in coords_and_confidence ] confidence = [ F.pad(torch.tensor(cf), (1, 1), value=-1.) for _, cf in coords_and_confidence ] coords = self.collate_dense_tensors(coords, pad_v=np.nan) confidence = self.collate_dense_tensors(confidence, pad_v=-1.) if device is not None: coords = coords.to(device) confidence = confidence.to(device) tokens = tokens.to(device) padding_mask = torch.isnan(coords[:,:,0,0]) coord_mask = torch.isfinite(coords.sum(-2).sum(-1)) confidence = confidence * coord_mask + (-1.) * padding_mask return coords, confidence, strs, tokens, padding_mask
def from_lists(self, coords_list, confidence_list=None, seq_list=None, device=None): """ Args: coords_list: list of length batch_size, each item is a list of floats in shape L x 3 x 3 to describe a backbone confidence_list: one of - None, default to highest confidence - list of length batch_size, each item is a scalar - list of length batch_size, each item is a list of floats of length L to describe the confidence scores for the backbone with values between 0. and 1. seq_list: either None or a list of strings Returns: coords: Tensor of shape batch_size x L x 3 x 3 confidence: Tensor of shape batch_size x L strs: list of strings tokens: LongTensor of shape batch_size x L padding_mask: ByteTensor of shape batch_size x L """ batch_size = len(coords_list) if confidence_list is None: confidence_list = [None] * batch_size if seq_list is None: seq_list = [None] * batch_size raw_batch = zip(coords_list, confidence_list, seq_list) return self.__call__(raw_batch, device)
@staticmethod def collate_dense_tensors(samples, pad_v): """ Takes a list of tensors with the following dimensions: [(d_11, ..., d_1K), (d_21, ..., d_2K), ..., (d_N1, ..., d_NK)] and stack + pads them into a single tensor of: (N, max_i=1,N { d_i1 }, ..., max_i=1,N {diK}) """ if len(samples) == 0: return torch.Tensor() if len(set(x.dim() for x in samples)) != 1: raise RuntimeError( f"Samples has varying dimensions: {[x.dim() for x in samples]}" ) (device,) = tuple(set(x.device for x in samples)) # assumes all on same device max_shape = [max(lst) for lst in zip(*[x.shape for x in samples])] result = torch.empty( len(samples), *max_shape, dtype=samples[0].dtype, device=device ) result.fill_(pad_v) for i in range(len(samples)): result_i = result[i] t = samples[i] result_i[tuple(slice(0, k) for k in t.shape)] = t return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import math
import torchimport torch.nn as nnimport torch.nn.functional as F
from ..modules import ( TransformerLayer, LearnedPositionalEmbedding, SinusoidalPositionalEmbedding, RobertaLMHead, ESM1bLayerNorm, ContactPredictionHead,)
class ProteinBertModel(nn.Module): @classmethod def add_args(cls, parser): parser.add_argument( "--num_layers", default=36, type=int, metavar="N", help="number of layers" ) parser.add_argument( "--embed_dim", default=1280, type=int, metavar="N", help="embedding dimension" ) parser.add_argument( "--logit_bias", action="store_true", help="whether to apply bias to logits" ) parser.add_argument( "--ffn_embed_dim", default=5120, type=int, metavar="N", help="embedding dimension for FFN", ) parser.add_argument( "--attention_heads", default=20, type=int, metavar="N", help="number of attention heads", )
def __init__(self, args, alphabet): super().__init__() self.args = args self.alphabet_size = len(alphabet) self.padding_idx = alphabet.padding_idx self.mask_idx = alphabet.mask_idx self.cls_idx = alphabet.cls_idx self.eos_idx = alphabet.eos_idx self.prepend_bos = alphabet.prepend_bos self.append_eos = alphabet.append_eos self.emb_layer_norm_before = getattr(self.args, "emb_layer_norm_before", False) if self.args.arch == "roberta_large": self.model_version = "ESM-1b" self._init_submodules_esm1b() else: self.model_version = "ESM-1" self._init_submodules_esm1()
def _init_submodules_common(self): self.embed_tokens = nn.Embedding( self.alphabet_size, self.args.embed_dim, padding_idx=self.padding_idx ) self.layers = nn.ModuleList( [ TransformerLayer( self.args.embed_dim, self.args.ffn_embed_dim, self.args.attention_heads, add_bias_kv=(self.model_version != "ESM-1b"), use_esm1b_layer_norm=(self.model_version == "ESM-1b"), ) for _ in range(self.args.layers) ] )
self.contact_head = ContactPredictionHead( self.args.layers * self.args.attention_heads, self.prepend_bos, self.append_eos, eos_idx=self.eos_idx, )
def _init_submodules_esm1b(self): self._init_submodules_common() self.embed_scale = 1 self.embed_positions = LearnedPositionalEmbedding( self.args.max_positions, self.args.embed_dim, self.padding_idx ) self.emb_layer_norm_before = ( ESM1bLayerNorm(self.args.embed_dim) if self.emb_layer_norm_before else None ) self.emb_layer_norm_after = ESM1bLayerNorm(self.args.embed_dim) self.lm_head = RobertaLMHead( embed_dim=self.args.embed_dim, output_dim=self.alphabet_size, weight=self.embed_tokens.weight, )
def _init_submodules_esm1(self): self._init_submodules_common() self.embed_scale = math.sqrt(self.args.embed_dim) self.embed_positions = SinusoidalPositionalEmbedding(self.args.embed_dim, self.padding_idx) self.embed_out = nn.Parameter(torch.zeros((self.alphabet_size, self.args.embed_dim))) self.embed_out_bias = None if self.args.final_bias: self.embed_out_bias = nn.Parameter(torch.zeros(self.alphabet_size))
def forward(self, tokens, repr_layers=[], need_head_weights=False, return_contacts=False): if return_contacts: need_head_weights = True
assert tokens.ndim == 2 padding_mask = tokens.eq(self.padding_idx) # B, T
x = self.embed_scale * self.embed_tokens(tokens)
if getattr(self.args, "token_dropout", False): x.masked_fill_((tokens == self.mask_idx).unsqueeze(-1), 0.0) # x: B x T x C mask_ratio_train = 0.15 * 0.8 src_lengths = (~padding_mask).sum(-1) mask_ratio_observed = (tokens == self.mask_idx).sum(-1).float() / src_lengths x = x * (1 - mask_ratio_train) / (1 - mask_ratio_observed)[:, None, None]
x = x + self.embed_positions(tokens)
if self.model_version == "ESM-1b": if self.emb_layer_norm_before: x = self.emb_layer_norm_before(x) if padding_mask is not None: x = x * (1 - padding_mask.unsqueeze(-1).type_as(x))
repr_layers = set(repr_layers) hidden_representations = {} if 0 in repr_layers: hidden_representations[0] = x
if need_head_weights: attn_weights = []
# (B, T, E) => (T, B, E) x = x.transpose(0, 1)
if not padding_mask.any(): padding_mask = None
for layer_idx, layer in enumerate(self.layers): x, attn = layer( x, self_attn_padding_mask=padding_mask, need_head_weights=need_head_weights ) if (layer_idx + 1) in repr_layers: hidden_representations[layer_idx + 1] = x.transpose(0, 1) if need_head_weights: # (H, B, T, T) => (B, H, T, T) attn_weights.append(attn.transpose(1, 0))
if self.model_version == "ESM-1b": x = self.emb_layer_norm_after(x) x = x.transpose(0, 1) # (T, B, E) => (B, T, E)
# last hidden representation should have layer norm applied if (layer_idx + 1) in repr_layers: hidden_representations[layer_idx + 1] = x x = self.lm_head(x) else: x = F.linear(x, self.embed_out, bias=self.embed_out_bias) x = x.transpose(0, 1) # (T, B, E) => (B, T, E)
result = {"logits": x, "representations": hidden_representations} if need_head_weights: # attentions: B x L x H x T x T attentions = torch.stack(attn_weights, 1) if self.model_version == "ESM-1": # ESM-1 models have an additional null-token for attention, which we remove attentions = attentions[..., :-1] if padding_mask is not None: attention_mask = 1 - padding_mask.type_as(attentions) attention_mask = attention_mask.unsqueeze(1) * attention_mask.unsqueeze(2) attentions = attentions * attention_mask[:, None, None, :, :] result["attentions"] = attentions if return_contacts: contacts = self.contact_head(tokens, attentions) result["contacts"] = contacts
return result
def predict_contacts(self, tokens): return self(tokens, return_contacts=True)["contacts"]
@property def num_layers(self): return self.args.layers123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
from typing import Unionimport torchimport torch.nn as nn
import esmfrom esm.modules import ContactPredictionHead, ESM1bLayerNorm, RobertaLMHead, TransformerLayer
class ESM2(nn.Module): def __init__( self, num_layers: int = 33, embed_dim: int = 1280, attention_heads: int = 20, alphabet: Union[esm.data.Alphabet, str] = "ESM-1b", token_dropout: bool = True, ): super().__init__() self.num_layers = num_layers self.embed_dim = embed_dim self.attention_heads = attention_heads if not isinstance(alphabet, esm.data.Alphabet): alphabet = esm.data.Alphabet.from_architecture(alphabet) self.alphabet = alphabet self.alphabet_size = len(alphabet) self.padding_idx = alphabet.padding_idx self.mask_idx = alphabet.mask_idx self.cls_idx = alphabet.cls_idx self.eos_idx = alphabet.eos_idx self.prepend_bos = alphabet.prepend_bos self.append_eos = alphabet.append_eos self.token_dropout = token_dropout
self._init_submodules()
def _init_submodules(self): self.embed_scale = 1 self.embed_tokens = nn.Embedding( self.alphabet_size, self.embed_dim, padding_idx=self.padding_idx, )
self.layers = nn.ModuleList( [ TransformerLayer( self.embed_dim, 4 * self.embed_dim, self.attention_heads, add_bias_kv=False, use_esm1b_layer_norm=True, use_rotary_embeddings=True, ) for _ in range(self.num_layers) ] )
self.contact_head = ContactPredictionHead( self.num_layers * self.attention_heads, self.prepend_bos, self.append_eos, eos_idx=self.eos_idx, ) self.emb_layer_norm_after = ESM1bLayerNorm(self.embed_dim)
self.lm_head = RobertaLMHead( embed_dim=self.embed_dim, output_dim=self.alphabet_size, weight=self.embed_tokens.weight, )
def forward(self, tokens, repr_layers=[], need_head_weights=False, return_contacts=False): if return_contacts: need_head_weights = True
assert tokens.ndim == 2 padding_mask = tokens.eq(self.padding_idx) # B, T
x = self.embed_scale * self.embed_tokens(tokens)
if self.token_dropout: x.masked_fill_((tokens == self.mask_idx).unsqueeze(-1), 0.0) # x: B x T x C mask_ratio_train = 0.15 * 0.8 src_lengths = (~padding_mask).sum(-1) mask_ratio_observed = (tokens == self.mask_idx).sum(-1).to(x.dtype) / src_lengths x = x * (1 - mask_ratio_train) / (1 - mask_ratio_observed)[:, None, None]
if padding_mask is not None: x = x * (1 - padding_mask.unsqueeze(-1).type_as(x))
repr_layers = set(repr_layers) hidden_representations = {} if 0 in repr_layers: hidden_representations[0] = x
if need_head_weights: attn_weights = []
# (B, T, E) => (T, B, E) x = x.transpose(0, 1)
if not padding_mask.any(): padding_mask = None
for layer_idx, layer in enumerate(self.layers): x, attn = layer( x, self_attn_padding_mask=padding_mask, need_head_weights=need_head_weights, ) if (layer_idx + 1) in repr_layers: hidden_representations[layer_idx + 1] = x.transpose(0, 1) if need_head_weights: # (H, B, T, T) => (B, H, T, T) attn_weights.append(attn.transpose(1, 0))
x = self.emb_layer_norm_after(x) x = x.transpose(0, 1) # (T, B, E) => (B, T, E)
# last hidden representation should have layer norm applied if (layer_idx + 1) in repr_layers: hidden_representations[layer_idx + 1] = x x = self.lm_head(x)
result = {"logits": x, "representations": hidden_representations} if need_head_weights: # attentions: B x L x H x T x T attentions = torch.stack(attn_weights, 1) if padding_mask is not None: attention_mask = 1 - padding_mask.type_as(attentions) attention_mask = attention_mask.unsqueeze(1) * attention_mask.unsqueeze(2) attentions = attentions * attention_mask[:, None, None, :, :] result["attentions"] = attentions if return_contacts: contacts = self.contact_head(tokens, attentions) result["contacts"] = contacts
return result
def predict_contacts(self, tokens): return self(tokens, return_contacts=True)["contacts"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import torchimport torch.nn as nn
from ..modules import ( AxialTransformerLayer, LearnedPositionalEmbedding, RobertaLMHead, ESM1bLayerNorm, ContactPredictionHead,)
from ..axial_attention import RowSelfAttention, ColumnSelfAttention
class MSATransformer(nn.Module): @classmethod def add_args(cls, parser): # fmt: off parser.add_argument( "--num_layers", default=12, type=int, metavar="N", help="number of layers" ) parser.add_argument( "--embed_dim", default=768, type=int, metavar="N", help="embedding dimension" ) parser.add_argument( "--logit_bias", action="store_true", help="whether to apply bias to logits" ) parser.add_argument( "--ffn_embed_dim", default=3072, type=int, metavar="N", help="embedding dimension for FFN", ) parser.add_argument( "--attention_heads", default=12, type=int, metavar="N", help="number of attention heads", ) parser.add_argument( "--dropout", default=0.1, type=float, help="Dropout to apply." ) parser.add_argument( "--attention_dropout", default=0.1, type=float, help="Dropout to apply." ) parser.add_argument( "--activation_dropout", default=0.1, type=float, help="Dropout to apply." ) parser.add_argument( "--max_tokens_per_msa", default=2 ** 14, type=int, help=( "Used during inference to batch attention computations in a single " "forward pass. This allows increased input sizes with less memory." ), ) # fmt: on
def __init__(self, args, alphabet): super().__init__() self.args = args self.alphabet_size = len(alphabet) self.padding_idx = alphabet.padding_idx self.mask_idx = alphabet.mask_idx self.cls_idx = alphabet.cls_idx self.eos_idx = alphabet.eos_idx self.prepend_bos = alphabet.prepend_bos self.append_eos = alphabet.append_eos
self.embed_tokens = nn.Embedding( self.alphabet_size, self.args.embed_dim, padding_idx=self.padding_idx )
if getattr(self.args, "embed_positions_msa", False): emb_dim = getattr(self.args, "embed_positions_msa_dim", self.args.embed_dim) self.msa_position_embedding = nn.Parameter( 0.01 * torch.randn(1, 1024, 1, emb_dim), requires_grad=True, ) else: self.register_parameter("msa_position_embedding", None)
self.dropout_module = nn.Dropout(self.args.dropout) self.layers = nn.ModuleList( [ AxialTransformerLayer( self.args.embed_dim, self.args.ffn_embed_dim, self.args.attention_heads, self.args.dropout, self.args.attention_dropout, self.args.activation_dropout, getattr(self.args, "max_tokens_per_msa", self.args.max_tokens), ) for _ in range(self.args.layers) ] )
self.contact_head = ContactPredictionHead( self.args.layers * self.args.attention_heads, self.prepend_bos, self.append_eos, eos_idx=self.eos_idx, ) self.embed_positions = LearnedPositionalEmbedding( self.args.max_positions, self.args.embed_dim, self.padding_idx, ) self.emb_layer_norm_before = ESM1bLayerNorm(self.args.embed_dim) self.emb_layer_norm_after = ESM1bLayerNorm(self.args.embed_dim) self.lm_head = RobertaLMHead( embed_dim=self.args.embed_dim, output_dim=self.alphabet_size, weight=self.embed_tokens.weight, )
def forward(self, tokens, repr_layers=[], need_head_weights=False, return_contacts=False): if return_contacts: need_head_weights = True
assert tokens.ndim == 3 batch_size, num_alignments, seqlen = tokens.size() padding_mask = tokens.eq(self.padding_idx) # B, R, C if not padding_mask.any(): padding_mask = None
x = self.embed_tokens(tokens) x += self.embed_positions(tokens.view(batch_size * num_alignments, seqlen)).view(x.size()) if self.msa_position_embedding is not None: if x.size(1) > 1024: raise RuntimeError( "Using model with MSA position embedding trained on maximum MSA " f"depth of 1024, but received {x.size(1)} alignments." ) x += self.msa_position_embedding[:, :num_alignments]
x = self.emb_layer_norm_before(x)
x = self.dropout_module(x)
if padding_mask is not None: x = x * (1 - padding_mask.unsqueeze(-1).type_as(x))
repr_layers = set(repr_layers) hidden_representations = {} if 0 in repr_layers: hidden_representations[0] = x
if need_head_weights: row_attn_weights = [] col_attn_weights = []
# B x R x C x D -> R x C x B x D x = x.permute(1, 2, 0, 3)
for layer_idx, layer in enumerate(self.layers): x = layer( x, self_attn_padding_mask=padding_mask, need_head_weights=need_head_weights, ) if need_head_weights: x, col_attn, row_attn = x # H x C x B x R x R -> B x H x C x R x R col_attn_weights.append(col_attn.permute(2, 0, 1, 3, 4)) # H x B x C x C -> B x H x C x C row_attn_weights.append(row_attn.permute(1, 0, 2, 3)) if (layer_idx + 1) in repr_layers: hidden_representations[layer_idx + 1] = x.permute(2, 0, 1, 3)
x = self.emb_layer_norm_after(x) x = x.permute(2, 0, 1, 3) # R x C x B x D -> B x R x C x D
# last hidden representation should have layer norm applied if (layer_idx + 1) in repr_layers: hidden_representations[layer_idx + 1] = x x = self.lm_head(x)
result = {"logits": x, "representations": hidden_representations} if need_head_weights: # col_attentions: B x L x H x C x R x R col_attentions = torch.stack(col_attn_weights, 1) # row_attentions: B x L x H x C x C row_attentions = torch.stack(row_attn_weights, 1) result["col_attentions"] = col_attentions result["row_attentions"] = row_attentions if return_contacts: contacts = self.contact_head(tokens, row_attentions) result["contacts"] = contacts
return result
def predict_contacts(self, tokens): return self(tokens, return_contacts=True)["contacts"]
@property def num_layers(self): return self.args.layers
def max_tokens_per_msa_(self, value: int) -> None: """The MSA Transformer automatically batches attention computations when gradients are disabled to allow you to pass in larger MSAs at test time than you can fit in GPU memory. By default this occurs when more than 2^14 tokens are passed in the input MSA. You can set this value to infinity to disable this behavior. """ for module in self.modules(): if isinstance(module, (RowSelfAttention, ColumnSelfAttention)): module.max_tokens_per_msa = value123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import mathfrom typing import Optional
import torchimport torch.nn as nnimport torch.nn.functional as F
from .multihead_attention import MultiheadAttention # noqafrom .axial_attention import ColumnSelfAttention, RowSelfAttention
def gelu(x): """Implementation of the gelu activation function.
For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) """ return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
def symmetrize(x): "Make layer symmetric in final two dimensions, used for contact prediction." return x + x.transpose(-1, -2)
def apc(x): "Perform average product correct, used for contact prediction." a1 = x.sum(-1, keepdims=True) a2 = x.sum(-2, keepdims=True) a12 = x.sum((-1, -2), keepdims=True)
avg = a1 * a2 avg.div_(a12) # in-place to reduce memory normalized = x - avg return normalized
class ESM1LayerNorm(nn.Module): def __init__(self, hidden_size, eps=1e-12, affine=True): """Construct a layernorm layer in the TF style (eps inside the sqrt).""" super().__init__() self.hidden_size = (hidden_size,) if isinstance(hidden_size, int) else tuple(hidden_size) self.eps = eps self.affine = bool(affine) if self.affine: self.weight = nn.Parameter(torch.ones(hidden_size)) self.bias = nn.Parameter(torch.zeros(hidden_size)) else: self.weight, self.bias = None, None
def forward(self, x): dims = tuple(-(i + 1) for i in range(len(self.hidden_size))) means = x.mean(dims, keepdim=True) x_zeromean = x - means variances = x_zeromean.pow(2).mean(dims, keepdim=True) x = x_zeromean / torch.sqrt(variances + self.eps) if self.affine: x = (self.weight * x) + self.bias return x
try: from apex.normalization import FusedLayerNorm as _FusedLayerNorm
class ESM1bLayerNorm(_FusedLayerNorm): @torch.jit.unused def forward(self, x): if not x.is_cuda: return super().forward(x) else: with torch.cuda.device(x.device): return super().forward(x)
except ImportError: from torch.nn import LayerNorm as ESM1bLayerNorm
class TransformerLayer(nn.Module): """Transformer layer block."""
def __init__( self, embed_dim, ffn_embed_dim, attention_heads, add_bias_kv=True, use_esm1b_layer_norm=False, use_rotary_embeddings: bool = False, ): super().__init__() self.embed_dim = embed_dim self.ffn_embed_dim = ffn_embed_dim self.attention_heads = attention_heads self.use_rotary_embeddings = use_rotary_embeddings self._init_submodules(add_bias_kv, use_esm1b_layer_norm)
def _init_submodules(self, add_bias_kv, use_esm1b_layer_norm): BertLayerNorm = ESM1bLayerNorm if use_esm1b_layer_norm else ESM1LayerNorm
self.self_attn = MultiheadAttention( self.embed_dim, self.attention_heads, add_bias_kv=add_bias_kv, add_zero_attn=False, use_rotary_embeddings=self.use_rotary_embeddings, ) self.self_attn_layer_norm = BertLayerNorm(self.embed_dim)
self.fc1 = nn.Linear(self.embed_dim, self.ffn_embed_dim) self.fc2 = nn.Linear(self.ffn_embed_dim, self.embed_dim)
self.final_layer_norm = BertLayerNorm(self.embed_dim)
def forward( self, x, self_attn_mask=None, self_attn_padding_mask=None, need_head_weights=False ): residual = x x = self.self_attn_layer_norm(x) x, attn = self.self_attn( query=x, key=x, value=x, key_padding_mask=self_attn_padding_mask, need_weights=True, need_head_weights=need_head_weights, attn_mask=self_attn_mask, ) x = residual + x
residual = x x = self.final_layer_norm(x) x = gelu(self.fc1(x)) x = self.fc2(x) x = residual + x
return x, attn
class AxialTransformerLayer(nn.Module): """Implements an Axial MSA Transformer block."""
def __init__( self, embedding_dim: int = 768, ffn_embedding_dim: int = 3072, num_attention_heads: int = 8, dropout: float = 0.1, attention_dropout: float = 0.1, activation_dropout: float = 0.1, max_tokens_per_msa: int = 2**14, ) -> None: super().__init__()
# Initialize parameters self.embedding_dim = embedding_dim self.dropout_prob = dropout
row_self_attention = RowSelfAttention( embedding_dim, num_attention_heads, dropout=dropout, max_tokens_per_msa=max_tokens_per_msa, )
column_self_attention = ColumnSelfAttention( embedding_dim, num_attention_heads, dropout=dropout, max_tokens_per_msa=max_tokens_per_msa, )
feed_forward_layer = FeedForwardNetwork( embedding_dim, ffn_embedding_dim, activation_dropout=activation_dropout, max_tokens_per_msa=max_tokens_per_msa, )
self.row_self_attention = self.build_residual(row_self_attention) self.column_self_attention = self.build_residual(column_self_attention) self.feed_forward_layer = self.build_residual(feed_forward_layer)
def build_residual(self, layer: nn.Module): return NormalizedResidualBlock( layer, self.embedding_dim, self.dropout_prob, )
def forward( self, x: torch.Tensor, self_attn_mask: Optional[torch.Tensor] = None, self_attn_padding_mask: Optional[torch.Tensor] = None, need_head_weights: bool = False, ): """ LayerNorm is applied either before or after the self-attention/ffn modules similar to the original Transformer implementation. """ x, row_attn = self.row_self_attention( x, self_attn_mask=self_attn_mask, self_attn_padding_mask=self_attn_padding_mask, ) x, column_attn = self.column_self_attention( x, self_attn_mask=self_attn_mask, self_attn_padding_mask=self_attn_padding_mask, ) x = self.feed_forward_layer(x) if need_head_weights: return x, column_attn, row_attn else: return x
class LearnedPositionalEmbedding(nn.Embedding): """ This module learns positional embeddings up to a fixed maximum size. Padding ids are ignored by either offsetting based on padding_idx or by setting padding_idx to None and ensuring that the appropriate position ids are passed to the forward function. """
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int): if padding_idx is not None: num_embeddings_ = num_embeddings + padding_idx + 1 else: num_embeddings_ = num_embeddings super().__init__(num_embeddings_, embedding_dim, padding_idx) self.max_positions = num_embeddings
def forward(self, input: torch.Tensor): """Input is expected to be of size [bsz x seqlen].""" if input.size(1) > self.max_positions: raise ValueError( f"Sequence length {input.size(1)} above maximum " f" sequence length of {self.max_positions}" ) mask = input.ne(self.padding_idx).int() positions = (torch.cumsum(mask, dim=1).type_as(mask) * mask).long() + self.padding_idx return F.embedding( positions, self.weight, self.padding_idx, self.max_norm, self.norm_type, self.scale_grad_by_freq, self.sparse, )
class SinusoidalPositionalEmbedding(nn.Module): def __init__(self, embed_dim, padding_idx, learned=False): super().__init__() self.embed_dim = embed_dim self.padding_idx = padding_idx self.register_buffer("_float_tensor", torch.FloatTensor(1)) self.weights = None
def forward(self, x): bsz, seq_len = x.shape max_pos = self.padding_idx + 1 + seq_len if self.weights is None or max_pos > self.weights.size(0): self.weights = self.get_embedding(max_pos) self.weights = self.weights.type_as(self._float_tensor)
positions = self.make_positions(x) return self.weights.index_select(0, positions.view(-1)).view(bsz, seq_len, -1).detach()
def make_positions(self, x): mask = x.ne(self.padding_idx) range_buf = torch.arange(x.size(1), device=x.device).expand_as(x) + self.padding_idx + 1 positions = range_buf.expand_as(x) return positions * mask.long() + self.padding_idx * (1 - mask.long())
def get_embedding(self, num_embeddings): half_dim = self.embed_dim // 2 emb = math.log(10000) / (half_dim - 1) emb = torch.exp(torch.arange(half_dim, dtype=torch.float) * -emb) emb = torch.arange(num_embeddings, dtype=torch.float).unsqueeze(1) * emb.unsqueeze(0) emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1) if self.embed_dim % 2 == 1: # zero pad emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1) if self.padding_idx is not None: emb[self.padding_idx, :] = 0 return emb
class RobertaLMHead(nn.Module): """Head for masked language modeling."""
def __init__(self, embed_dim, output_dim, weight): super().__init__() self.dense = nn.Linear(embed_dim, embed_dim) self.layer_norm = ESM1bLayerNorm(embed_dim) self.weight = weight self.bias = nn.Parameter(torch.zeros(output_dim))
def forward(self, features): x = self.dense(features) x = gelu(x) x = self.layer_norm(x) # project back to size of vocabulary with bias x = F.linear(x, self.weight) + self.bias return x
class ContactPredictionHead(nn.Module): """Performs symmetrization, apc, and computes a logistic regression on the output features"""
def __init__( self, in_features: int, prepend_bos: bool, append_eos: bool, bias=True, eos_idx: Optional[int] = None, ): super().__init__() self.in_features = in_features self.prepend_bos = prepend_bos self.append_eos = append_eos if append_eos and eos_idx is None: raise ValueError("Using an alphabet with eos token, but no eos token was passed in.") self.eos_idx = eos_idx self.regression = nn.Linear(in_features, 1, bias) self.activation = nn.Sigmoid()
def forward(self, tokens, attentions): # remove eos token attentions if self.append_eos: eos_mask = tokens.ne(self.eos_idx).to(attentions) eos_mask = eos_mask.unsqueeze(1) * eos_mask.unsqueeze(2) attentions = attentions * eos_mask[:, None, None, :, :] attentions = attentions[..., :-1, :-1] # remove cls token attentions if self.prepend_bos: attentions = attentions[..., 1:, 1:] batch_size, layers, heads, seqlen, _ = attentions.size() attentions = attentions.view(batch_size, layers * heads, seqlen, seqlen)
# features: B x C x T x T attentions = attentions.to( self.regression.weight.device ) # attentions always float32, may need to convert to float16 attentions = apc(symmetrize(attentions)) attentions = attentions.permute(0, 2, 3, 1) return self.activation(self.regression(attentions).squeeze(3))
class NormalizedResidualBlock(nn.Module): def __init__( self, layer: nn.Module, embedding_dim: int, dropout: float = 0.1, ): super().__init__() self.embedding_dim = embedding_dim
self.layer = layer self.dropout_module = nn.Dropout( dropout, ) self.layer_norm = ESM1bLayerNorm(self.embedding_dim)
def forward(self, x, *args, **kwargs): residual = x x = self.layer_norm(x) outputs = self.layer(x, *args, **kwargs) if isinstance(outputs, tuple): x, *out = outputs else: x = outputs out = None
x = self.dropout_module(x) x = residual + x
if out is not None: return (x,) + tuple(out) else: return x
class FeedForwardNetwork(nn.Module): def __init__( self, embedding_dim: int, ffn_embedding_dim: int, activation_dropout: float = 0.1, max_tokens_per_msa: int = 2**14, ): super().__init__() self.embedding_dim = embedding_dim self.ffn_embedding_dim = ffn_embedding_dim self.max_tokens_per_msa = max_tokens_per_msa self.activation_fn = nn.GELU() self.activation_dropout_module = nn.Dropout( activation_dropout, ) self.fc1 = nn.Linear(embedding_dim, ffn_embedding_dim) self.fc2 = nn.Linear(ffn_embedding_dim, embedding_dim)
def forward(self, x): x = self.activation_fn(self.fc1(x)) x = self.activation_dropout_module(x) x = self.fc2(x) return x123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import mathfrom typing import Dict, Optional, Tuple
import torchimport torch.nn.functional as Ffrom torch import Tensor, nnfrom torch.nn import Parameterfrom esm.rotary_embedding import RotaryEmbedding
import uuid
def utils_softmax(x, dim: int, onnx_trace: bool = False): if onnx_trace: return F.softmax(x.float(), dim=dim) else: return F.softmax(x, dim=dim, dtype=torch.float32)
class FairseqIncrementalState(object): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.init_incremental_state()
def init_incremental_state(self): self._incremental_state_id = str(uuid.uuid4())
def _get_full_incremental_state_key(self, key: str) -> str: return "{}.{}".format(self._incremental_state_id, key)
def get_incremental_state( self, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]], key: str, ) -> Optional[Dict[str, Optional[Tensor]]]: """Helper for getting incremental state for an nn.Module.""" full_key = self._get_full_incremental_state_key(key) if incremental_state is None or full_key not in incremental_state: return None return incremental_state[full_key]
def set_incremental_state( self, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]], key: str, value: Dict[str, Optional[Tensor]], ) -> Optional[Dict[str, Dict[str, Optional[Tensor]]]]: """Helper for setting incremental state for an nn.Module.""" if incremental_state is not None: full_key = self._get_full_incremental_state_key(key) incremental_state[full_key] = value return incremental_state
def with_incremental_state(cls): cls.__bases__ = (FairseqIncrementalState,) + tuple( b for b in cls.__bases__ if b != FairseqIncrementalState ) return cls
@with_incremental_stateclass MultiheadAttention(nn.Module): """Multi-headed attention.
See "Attention Is All You Need" for more details. """
def __init__( self, embed_dim, num_heads, kdim=None, vdim=None, dropout=0.0, bias=True, add_bias_kv: bool = False, add_zero_attn: bool = False, self_attention: bool = False, encoder_decoder_attention: bool = False, use_rotary_embeddings: bool = False, ): super().__init__() self.embed_dim = embed_dim self.kdim = kdim if kdim is not None else embed_dim self.vdim = vdim if vdim is not None else embed_dim self.qkv_same_dim = self.kdim == embed_dim and self.vdim == embed_dim
self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads assert ( self.head_dim * num_heads == self.embed_dim ), "embed_dim must be divisible by num_heads" self.scaling = self.head_dim**-0.5
self.self_attention = self_attention self.encoder_decoder_attention = encoder_decoder_attention
assert not self.self_attention or self.qkv_same_dim, ( "Self-attention requires query, key and " "value to be of the same size" )
self.k_proj = nn.Linear(self.kdim, embed_dim, bias=bias) self.v_proj = nn.Linear(self.vdim, embed_dim, bias=bias) self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
if add_bias_kv: self.bias_k = Parameter(torch.Tensor(1, 1, embed_dim)) self.bias_v = Parameter(torch.Tensor(1, 1, embed_dim)) else: self.bias_k = self.bias_v = None
self.add_zero_attn = add_zero_attn
self.reset_parameters()
self.onnx_trace = False self.rot_emb = None if use_rotary_embeddings: self.rot_emb = RotaryEmbedding(dim=self.head_dim)
self.enable_torch_version = False if hasattr(F, "multi_head_attention_forward"): self.enable_torch_version = True else: self.enable_torch_version = False
def prepare_for_onnx_export_(self): self.onnx_trace = True
def reset_parameters(self): if self.qkv_same_dim: # Empirically observed the convergence to be much better with # the scaled initialization nn.init.xavier_uniform_(self.k_proj.weight, gain=1 / math.sqrt(2)) nn.init.xavier_uniform_(self.v_proj.weight, gain=1 / math.sqrt(2)) nn.init.xavier_uniform_(self.q_proj.weight, gain=1 / math.sqrt(2)) else: nn.init.xavier_uniform_(self.k_proj.weight) nn.init.xavier_uniform_(self.v_proj.weight) nn.init.xavier_uniform_(self.q_proj.weight)
nn.init.xavier_uniform_(self.out_proj.weight) if self.out_proj.bias is not None: nn.init.constant_(self.out_proj.bias, 0.0) if self.bias_k is not None: nn.init.xavier_normal_(self.bias_k) if self.bias_v is not None: nn.init.xavier_normal_(self.bias_v)
def forward( self, query, key: Optional[Tensor], value: Optional[Tensor], key_padding_mask: Optional[Tensor] = None, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, need_weights: bool = True, static_kv: bool = False, attn_mask: Optional[Tensor] = None, before_softmax: bool = False, need_head_weights: bool = False, ) -> Tuple[Tensor, Optional[Tensor]]: """Input shape: Time x Batch x Channel
Args: key_padding_mask (ByteTensor, optional): mask to exclude keys that are pads, of shape `(batch, src_len)`, where padding elements are indicated by 1s. need_weights (bool, optional): return the attention weights, averaged over heads (default: False). attn_mask (ByteTensor, optional): typically used to implement causal attention, where the mask prevents the attention from looking forward in time (default: None). before_softmax (bool, optional): return the raw attention weights and values before the attention softmax. need_head_weights (bool, optional): return the attention weights for each head. Implies *need_weights*. Default: return the average attention weights over all heads. """ if need_head_weights: need_weights = True
tgt_len, bsz, embed_dim = query.size() assert embed_dim == self.embed_dim assert list(query.size()) == [tgt_len, bsz, embed_dim]
if ( not self.rot_emb and self.enable_torch_version and not self.onnx_trace and incremental_state is None and not static_kv # A workaround for quantization to work. Otherwise JIT compilation # treats bias in linear module as method. and not torch.jit.is_scripting() and not need_head_weights ): assert key is not None and value is not None return F.multi_head_attention_forward( query, key, value, self.embed_dim, self.num_heads, torch.empty([0]), torch.cat((self.q_proj.bias, self.k_proj.bias, self.v_proj.bias)), self.bias_k, self.bias_v, self.add_zero_attn, self.dropout, self.out_proj.weight, self.out_proj.bias, self.training, key_padding_mask, need_weights, attn_mask, use_separate_proj_weight=True, q_proj_weight=self.q_proj.weight, k_proj_weight=self.k_proj.weight, v_proj_weight=self.v_proj.weight, ) if incremental_state is not None: saved_state = self._get_input_buffer(incremental_state) if saved_state is not None and "prev_key" in saved_state: # previous time steps are cached - no need to recompute # key and value if they are static if static_kv: assert self.encoder_decoder_attention and not self.self_attention key = value = None else: saved_state = None
if self.self_attention: q = self.q_proj(query) k = self.k_proj(query) v = self.v_proj(query) elif self.encoder_decoder_attention: # encoder-decoder attention q = self.q_proj(query) if key is None: assert value is None k = v = None else: k = self.k_proj(key) v = self.v_proj(key)
else: assert key is not None and value is not None q = self.q_proj(query) k = self.k_proj(key) v = self.v_proj(value) q *= self.scaling
if self.bias_k is not None: assert self.bias_v is not None k = torch.cat([k, self.bias_k.repeat(1, bsz, 1)]) v = torch.cat([v, self.bias_v.repeat(1, bsz, 1)]) if attn_mask is not None: attn_mask = torch.cat( [attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1 ) if key_padding_mask is not None: key_padding_mask = torch.cat( [ key_padding_mask, key_padding_mask.new_zeros(key_padding_mask.size(0), 1), ], dim=1, )
q = q.contiguous().view(tgt_len, bsz * self.num_heads, self.head_dim).transpose(0, 1) if k is not None: k = k.contiguous().view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1) if v is not None: v = v.contiguous().view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1)
if saved_state is not None: # saved states are stored with shape (bsz, num_heads, seq_len, head_dim) if "prev_key" in saved_state: _prev_key = saved_state["prev_key"] assert _prev_key is not None prev_key = _prev_key.view(bsz * self.num_heads, -1, self.head_dim) if static_kv: k = prev_key else: assert k is not None k = torch.cat([prev_key, k], dim=1) if "prev_value" in saved_state: _prev_value = saved_state["prev_value"] assert _prev_value is not None prev_value = _prev_value.view(bsz * self.num_heads, -1, self.head_dim) if static_kv: v = prev_value else: assert v is not None v = torch.cat([prev_value, v], dim=1) prev_key_padding_mask: Optional[Tensor] = None if "prev_key_padding_mask" in saved_state: prev_key_padding_mask = saved_state["prev_key_padding_mask"] assert k is not None and v is not None key_padding_mask = MultiheadAttention._append_prev_key_padding_mask( key_padding_mask=key_padding_mask, prev_key_padding_mask=prev_key_padding_mask, batch_size=bsz, src_len=k.size(1), static_kv=static_kv, )
saved_state["prev_key"] = k.view(bsz, self.num_heads, -1, self.head_dim) saved_state["prev_value"] = v.view(bsz, self.num_heads, -1, self.head_dim) saved_state["prev_key_padding_mask"] = key_padding_mask # In this branch incremental_state is never None assert incremental_state is not None incremental_state = self._set_input_buffer(incremental_state, saved_state) assert k is not None src_len = k.size(1)
# This is part of a workaround to get around fork/join parallelism # not supporting Optional types. if key_padding_mask is not None and key_padding_mask.dim() == 0: key_padding_mask = None
if key_padding_mask is not None: assert key_padding_mask.size(0) == bsz assert key_padding_mask.size(1) == src_len
if self.add_zero_attn: assert v is not None src_len += 1 k = torch.cat([k, k.new_zeros((k.size(0), 1) + k.size()[2:])], dim=1) v = torch.cat([v, v.new_zeros((v.size(0), 1) + v.size()[2:])], dim=1) if attn_mask is not None: attn_mask = torch.cat( [attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1 ) if key_padding_mask is not None: key_padding_mask = torch.cat( [ key_padding_mask, torch.zeros(key_padding_mask.size(0), 1).type_as(key_padding_mask), ], dim=1, )
if self.rot_emb: q, k = self.rot_emb(q, k)
attn_weights = torch.bmm(q, k.transpose(1, 2)) attn_weights = MultiheadAttention.apply_sparse_mask(attn_weights, tgt_len, src_len, bsz)
assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len, src_len]
if attn_mask is not None: attn_mask = attn_mask.unsqueeze(0) if self.onnx_trace: attn_mask = attn_mask.repeat(attn_weights.size(0), 1, 1) attn_weights += attn_mask
if key_padding_mask is not None: # don't attend to padding symbols attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) attn_weights = attn_weights.masked_fill( key_padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool), float("-inf") ) attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
if before_softmax: return attn_weights, v
attn_weights_float = utils_softmax(attn_weights, dim=-1, onnx_trace=self.onnx_trace) attn_weights = attn_weights_float.type_as(attn_weights) attn_probs = F.dropout( attn_weights_float.type_as(attn_weights), p=self.dropout, training=self.training, ) assert v is not None attn = torch.bmm(attn_probs, v) assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self.head_dim] if self.onnx_trace and attn.size(1) == 1: # when ONNX tracing a single decoder step (sequence length == 1) # the transpose is a no-op copy before view, thus unnecessary attn = attn.contiguous().view(tgt_len, bsz, embed_dim) else: attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim) attn = self.out_proj(attn) attn_weights: Optional[Tensor] = None if need_weights: attn_weights = attn_weights_float.view( bsz, self.num_heads, tgt_len, src_len ).type_as(attn).transpose(1, 0) if not need_head_weights: # average attention weights over heads attn_weights = attn_weights.mean(dim=0)
return attn, attn_weights
@staticmethod def _append_prev_key_padding_mask( key_padding_mask: Optional[Tensor], prev_key_padding_mask: Optional[Tensor], batch_size: int, src_len: int, static_kv: bool, ) -> Optional[Tensor]: # saved key padding masks have shape (bsz, seq_len) if prev_key_padding_mask is not None and static_kv: new_key_padding_mask = prev_key_padding_mask elif prev_key_padding_mask is not None and key_padding_mask is not None: new_key_padding_mask = torch.cat( [prev_key_padding_mask.float(), key_padding_mask.float()], dim=1 ) # During incremental decoding, as the padding token enters and # leaves the frame, there will be a time when prev or current # is None elif prev_key_padding_mask is not None: filler = torch.zeros( (batch_size, src_len - prev_key_padding_mask.size(1)), device=prev_key_padding_mask.device, ) new_key_padding_mask = torch.cat( [prev_key_padding_mask.float(), filler.float()], dim=1 ) elif key_padding_mask is not None: filler = torch.zeros( (batch_size, src_len - key_padding_mask.size(1)), device=key_padding_mask.device, ) new_key_padding_mask = torch.cat([filler.float(), key_padding_mask.float()], dim=1) else: new_key_padding_mask = prev_key_padding_mask return new_key_padding_mask
@torch.jit.export def reorder_incremental_state( self, incremental_state: Dict[str, Dict[str, Optional[Tensor]]], new_order: Tensor ): """Reorder buffered internal state (for incremental generation).""" input_buffer = self._get_input_buffer(incremental_state) if input_buffer is not None: for k in input_buffer.keys(): input_buffer_k = input_buffer[k] if input_buffer_k is not None: if self.encoder_decoder_attention and input_buffer_k.size(0) == new_order.size( 0 ): break input_buffer[k] = input_buffer_k.index_select(0, new_order) incremental_state = self._set_input_buffer(incremental_state, input_buffer) return incremental_state
def _get_input_buffer( self, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] ) -> Dict[str, Optional[Tensor]]: result = self.get_incremental_state(incremental_state, "attn_state") if result is not None: return result else: empty_result: Dict[str, Optional[Tensor]] = {} return empty_result
def _set_input_buffer( self, incremental_state: Dict[str, Dict[str, Optional[Tensor]]], buffer: Dict[str, Optional[Tensor]], ): return self.set_incremental_state(incremental_state, "attn_state", buffer)
def apply_sparse_mask(attn_weights, tgt_len: int, src_len: int, bsz: int): return attn_weights
def upgrade_state_dict_named(self, state_dict, name): prefix = name + "." if name != "" else "" items_to_add = {} keys_to_remove = [] for k in state_dict.keys(): if k.endswith(prefix + "in_proj_weight"): # in_proj_weight used to be q + k + v with same dimensions dim = int(state_dict[k].shape[0] / 3) items_to_add[prefix + "q_proj.weight"] = state_dict[k][:dim] items_to_add[prefix + "k_proj.weight"] = state_dict[k][dim : 2 * dim] items_to_add[prefix + "v_proj.weight"] = state_dict[k][2 * dim :]
keys_to_remove.append(k)
k_bias = prefix + "in_proj_bias" if k_bias in state_dict.keys(): dim = int(state_dict[k].shape[0] / 3) items_to_add[prefix + "q_proj.bias"] = state_dict[k_bias][:dim] items_to_add[prefix + "k_proj.bias"] = state_dict[k_bias][dim : 2 * dim] items_to_add[prefix + "v_proj.bias"] = state_dict[k_bias][2 * dim :]
keys_to_remove.append(prefix + "in_proj_bias")
for k in keys_to_remove: del state_dict[k]
for key, value in items_to_add.items(): state_dict[key] = value123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import reimport urllibimport warningsfrom argparse import Namespacefrom pathlib import Path
import torch
import esmfrom esm.model.esm2 import ESM2
def _has_regression_weights(model_name): """Return whether we expect / require regression weights; Right now that is all models except ESM-1v and ESM-IF""" return not ("esm1v" in model_name or "esm_if" in model_name)
def load_model_and_alphabet(model_name): if model_name.endswith(".pt"): # treat as filepath return load_model_and_alphabet_local(model_name) else: return load_model_and_alphabet_hub(model_name)
def load_hub_workaround(url): try: data = torch.hub.load_state_dict_from_url(url, progress=False, map_location="cpu") except RuntimeError: # Pytorch version issue - see https://github.com/pytorch/pytorch/issues/43106 fn = Path(url).name data = torch.load( f"{torch.hub.get_dir()}/checkpoints/{fn}", map_location="cpu", ) except urllib.error.HTTPError as e: raise Exception(f"Could not load {url}, check if you specified a correct model name?") return data
def load_regression_hub(model_name): url = f"https://dl.fbaipublicfiles.com/fair-esm/regression/{model_name}-contact-regression.pt" regression_data = load_hub_workaround(url) return regression_data
def _download_model_and_regression_data(model_name): url = f"https://dl.fbaipublicfiles.com/fair-esm/models/{model_name}.pt" model_data = load_hub_workaround(url) if _has_regression_weights(model_name): regression_data = load_regression_hub(model_name) else: regression_data = None return model_data, regression_data
def load_model_and_alphabet_hub(model_name): model_data, regression_data = _download_model_and_regression_data(model_name) return load_model_and_alphabet_core(model_name, model_data, regression_data)
def load_model_and_alphabet_local(model_location): """Load from local path. The regression weights need to be co-located""" model_location = Path(model_location) model_data = torch.load(str(model_location), map_location="cpu") model_name = model_location.stem if _has_regression_weights(model_name): regression_location = str(model_location.with_suffix("")) + "-contact-regression.pt" regression_data = torch.load(regression_location, map_location="cpu") else: regression_data = None return load_model_and_alphabet_core(model_name, model_data, regression_data)
def has_emb_layer_norm_before(model_state): """Determine whether layer norm needs to be applied before the encoder""" return any(k.startswith("emb_layer_norm_before") for k, param in model_state.items())
def _load_model_and_alphabet_core_v1(model_data): import esm # since esm.inverse_folding is imported below, you actually have to re-import esm here
alphabet = esm.Alphabet.from_architecture(model_data["args"].arch)
if model_data["args"].arch == "roberta_large": # upgrade state dict pra = lambda s: "".join(s.split("encoder_")[1:] if "encoder" in s else s) prs1 = lambda s: "".join(s.split("encoder.")[1:] if "encoder" in s else s) prs2 = lambda s: "".join( s.split("sentence_encoder.")[1:] if "sentence_encoder" in s else s ) model_args = {pra(arg[0]): arg[1] for arg in vars(model_data["args"]).items()} model_state = {prs1(prs2(arg[0])): arg[1] for arg in model_data["model"].items()} model_state["embed_tokens.weight"][alphabet.mask_idx].zero_() # For token drop model_args["emb_layer_norm_before"] = has_emb_layer_norm_before(model_state) model_type = esm.ProteinBertModel
elif model_data["args"].arch == "protein_bert_base":
# upgrade state dict pra = lambda s: "".join(s.split("decoder_")[1:] if "decoder" in s else s) prs = lambda s: "".join(s.split("decoder.")[1:] if "decoder" in s else s) model_args = {pra(arg[0]): arg[1] for arg in vars(model_data["args"]).items()} model_state = {prs(arg[0]): arg[1] for arg in model_data["model"].items()} model_type = esm.ProteinBertModel elif model_data["args"].arch == "msa_transformer":
# upgrade state dict pra = lambda s: "".join(s.split("encoder_")[1:] if "encoder" in s else s) prs1 = lambda s: "".join(s.split("encoder.")[1:] if "encoder" in s else s) prs2 = lambda s: "".join( s.split("sentence_encoder.")[1:] if "sentence_encoder" in s else s ) prs3 = lambda s: s.replace("row", "column") if "row" in s else s.replace("column", "row") model_args = {pra(arg[0]): arg[1] for arg in vars(model_data["args"]).items()} model_state = {prs1(prs2(prs3(arg[0]))): arg[1] for arg in model_data["model"].items()} if model_args.get("embed_positions_msa", False): emb_dim = model_state["msa_position_embedding"].size(-1) model_args["embed_positions_msa_dim"] = emb_dim # initial release, bug: emb_dim==1
model_type = esm.MSATransformer
elif "invariant_gvp" in model_data["args"].arch: import esm.inverse_folding
model_type = esm.inverse_folding.gvp_transformer.GVPTransformerModel model_args = vars(model_data["args"]) # convert Namespace -> dict
def update_name(s): # Map the module names in checkpoints trained with internal code to # the updated module names in open source code s = s.replace("W_v", "embed_graph.embed_node") s = s.replace("W_e", "embed_graph.embed_edge") s = s.replace("embed_scores.0", "embed_confidence") s = s.replace("embed_score.", "embed_graph.embed_confidence.") s = s.replace("seq_logits_projection.", "") s = s.replace("embed_ingraham_features", "embed_dihedrals") s = s.replace("embed_gvp_in_local_frame.0", "embed_gvp_output") s = s.replace("embed_features_in_local_frame.0", "embed_gvp_input_features") return s
model_state = { update_name(sname): svalue for sname, svalue in model_data["model"].items() if "version" not in sname }
else: raise ValueError("Unknown architecture selected")
model = model_type( Namespace(**model_args), alphabet, )
return model, alphabet, model_state
def _load_model_and_alphabet_core_v2(model_data): def upgrade_state_dict(state_dict): """Removes prefixes 'model.encoder.sentence_encoder.' and 'model.encoder.'.""" prefixes = ["encoder.sentence_encoder.", "encoder."] pattern = re.compile("^" + "|".join(prefixes)) state_dict = {pattern.sub("", name): param for name, param in state_dict.items()} return state_dict
cfg = model_data["cfg"]["model"] state_dict = model_data["model"] state_dict = upgrade_state_dict(state_dict) alphabet = esm.data.Alphabet.from_architecture("ESM-1b") model = ESM2( num_layers=cfg.encoder_layers, embed_dim=cfg.encoder_embed_dim, attention_heads=cfg.encoder_attention_heads, alphabet=alphabet, token_dropout=cfg.token_dropout, ) return model, alphabet, state_dict
def load_model_and_alphabet_core(model_name, model_data, regression_data=None): if regression_data is not None: model_data["model"].update(regression_data["model"])
if model_name.startswith("esm2"): model, alphabet, model_state = _load_model_and_alphabet_core_v2(model_data) else: model, alphabet, model_state = _load_model_and_alphabet_core_v1(model_data)
expected_keys = set(model.state_dict().keys()) found_keys = set(model_state.keys())
if regression_data is None: expected_missing = {"contact_head.regression.weight", "contact_head.regression.bias"} error_msgs = [] missing = (expected_keys - found_keys) - expected_missing if missing: error_msgs.append(f"Missing key(s) in state_dict: {missing}.") unexpected = found_keys - expected_keys if unexpected: error_msgs.append(f"Unexpected key(s) in state_dict: {unexpected}.")
if error_msgs: raise RuntimeError( "Error(s) in loading state_dict for {}:\n\t{}".format( model.__class__.__name__, "\n\t".join(error_msgs) ) ) if expected_missing - found_keys: warnings.warn( "Regression weights not found, predicting contacts will not produce correct results." )
model.load_state_dict(model_state, strict=regression_data is not None)
return model, alphabet
def esm1_t34_670M_UR50S(): """34 layer transformer model with 670M params, trained on Uniref50 Sparse.
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm1_t34_670M_UR50S")
def esm1_t34_670M_UR50D(): """34 layer transformer model with 670M params, trained on Uniref50 Dense.
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm1_t34_670M_UR50D")
def esm1_t34_670M_UR100(): """34 layer transformer model with 670M params, trained on Uniref100.
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm1_t34_670M_UR100")
def esm1_t12_85M_UR50S(): """12 layer transformer model with 85M params, trained on Uniref50 Sparse.
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm1_t12_85M_UR50S")
def esm1_t6_43M_UR50S(): """6 layer transformer model with 43M params, trained on Uniref50 Sparse.
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm1_t6_43M_UR50S")
def esm1b_t33_650M_UR50S(): """33 layer transformer model with 650M params, trained on Uniref50 Sparse. This is our best performing model, which will be described in a future publication.
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm1b_t33_650M_UR50S")
def esm_msa1_t12_100M_UR50S(): warnings.warn( "This model had a minor bug in the positional embeddings, " "please use ESM-MSA-1b: esm.pretrained.esm_msa1b_t12_100M_UR50S()", ) return load_model_and_alphabet_hub("esm_msa1_t12_100M_UR50S")
def esm_msa1b_t12_100M_UR50S(): return load_model_and_alphabet_hub("esm_msa1b_t12_100M_UR50S")
def esm1v_t33_650M_UR90S(): """33 layer transformer model with 650M params, trained on Uniref90. This is model 1 of a 5 model ensemble.
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm1v_t33_650M_UR90S_1")
def esm1v_t33_650M_UR90S_1(): """33 layer transformer model with 650M params, trained on Uniref90. This is model 1 of a 5 model ensemble.
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm1v_t33_650M_UR90S_1")
def esm1v_t33_650M_UR90S_2(): """33 layer transformer model with 650M params, trained on Uniref90. This is model 2 of a 5 model ensemble.
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm1v_t33_650M_UR90S_2")
def esm1v_t33_650M_UR90S_3(): """33 layer transformer model with 650M params, trained on Uniref90. This is model 3 of a 5 model ensemble.
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm1v_t33_650M_UR90S_3")
def esm1v_t33_650M_UR90S_4(): """33 layer transformer model with 650M params, trained on Uniref90. This is model 4 of a 5 model ensemble.
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm1v_t33_650M_UR90S_4")
def esm1v_t33_650M_UR90S_5(): """33 layer transformer model with 650M params, trained on Uniref90. This is model 5 of a 5 model ensemble.
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm1v_t33_650M_UR90S_5")
def esm_if1_gvp4_t16_142M_UR50(): """Inverse folding model with 142M params, with 4 GVP-GNN layers, 8 Transformer encoder layers, and 8 Transformer decoder layers, trained on CATH structures and 12 million alphafold2 predicted structures from UniRef50 sequences.
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm_if1_gvp4_t16_142M_UR50")
def esm2_t6_8M_UR50D(): """6 layer ESM-2 model with 8M params, trained on UniRef50.
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm2_t6_8M_UR50D")
def esm2_t12_35M_UR50D(): """12 layer ESM-2 model with 35M params, trained on UniRef50.
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm2_t12_35M_UR50D")
def esm2_t30_150M_UR50D(): """30 layer ESM-2 model with 150M params, trained on UniRef50.
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm2_t30_150M_UR50D")
def esm2_t33_650M_UR50D(): """33 layer ESM-2 model with 650M params, trained on UniRef50.
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm2_t33_650M_UR50D")
def esm2_t36_3B_UR50D(): """36 layer ESM-2 model with 3B params, trained on UniRef50.
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm2_t36_3B_UR50D")
def esm2_t48_15B_UR50D(): """48 layer ESM-2 model with 15B params, trained on UniRef50. If you have OOM while loading this model, please refer to README on how to employ FSDP and ZeRO CPU offloading
Returns a tuple of (Model, Alphabet). """ return load_model_and_alphabet_hub("esm2_t48_15B_UR50D")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
from typing import Tuple
import torch
def rotate_half(x): x1, x2 = x.chunk(2, dim=-1) return torch.cat((-x2, x1), dim=-1)
def apply_rotary_pos_emb(x, cos, sin): cos = cos[:, : x.shape[-2], :] sin = sin[:, : x.shape[-2], :]
return (x * cos) + (rotate_half(x) * sin)
class RotaryEmbedding(torch.nn.Module): """ The rotary position embeddings from RoFormer_ (Su et. al). A crucial insight from the method is that the query and keys are transformed by rotation matrices which depend on the relative positions. Other implementations are available in the Rotary Transformer repo_ and in GPT-NeoX_, GPT-NeoX was an inspiration .. _RoFormer: https://arxiv.org/abs/2104.09864 .. _repo: https://github.com/ZhuiyiTechnology/roformer .. _GPT-NeoX: https://github.com/EleutherAI/gpt-neox .. warning: Please note that this embedding is not registered on purpose, as it is transformative (it does not create the embedding dimension) and will likely be picked up (imported) on a ad-hoc basis """
def __init__(self, dim: int, *_, **__): super().__init__() # Generate and save the inverse frequency buffer (non trainable) inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim)) self.register_buffer("inv_freq", inv_freq)
self._seq_len_cached = None self._cos_cached = None self._sin_cached = None
def _update_cos_sin_tables(self, x, seq_dimension=1): seq_len = x.shape[seq_dimension]
# Reset the tables if the sequence length has changed, # or if we're on a new device (possibly due to tracing for instance) if seq_len != self._seq_len_cached or self._cos_cached.device != x.device: self._seq_len_cached = seq_len t = torch.arange(x.shape[seq_dimension], device=x.device).type_as(self.inv_freq) freqs = torch.einsum("i,j->ij", t, self.inv_freq) emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
self._cos_cached = emb.cos()[None, :, :] self._sin_cached = emb.sin()[None, :, :]
return self._cos_cached, self._sin_cached
def forward(self, q: torch.Tensor, k: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: self._cos_cached, self._sin_cached = self._update_cos_sin_tables(k, seq_dimension=-2)
return ( apply_rotary_pos_emb(q, self._cos_cached, self._sin_cached), apply_rotary_pos_emb(k, self._cos_cached, self._sin_cached), )123456# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
version = "1.0.2"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142#!/usr/bin/env python3 -u# Copyright (c) Facebook, Inc. and its affiliates.## This source code is licensed under the MIT license found in the# LICENSE file in the root directory of this source tree.
import argparseimport pathlibimport sys print("using", sys.executable)
sys.path.insert( 0,"/home/user/.local/lib/python3.8/site-packages")sys.path.insert( 0,"/home/user/app/esm/")import os
import torch
from esm import Alphabet, FastaBatchedDataset, ProteinBertModel, pretrained, MSATransformer
def create_parser(): parser = argparse.ArgumentParser( description="Extract per-token representations and model outputs for sequences in a FASTA file" # noqa )
parser.add_argument( "model_location", type=str, help="PyTorch model file OR name of pretrained model to download (see README for models)", ) parser.add_argument( "fasta_file", type=pathlib.Path, help="FASTA file on which to extract representations", ) parser.add_argument( "output_dir", type=pathlib.Path, help="output directory for extracted representations", )
parser.add_argument("--toks_per_batch", type=int, default=4096, help="maximum batch size") parser.add_argument( "--repr_layers", type=int, default=[-1], nargs="+", help="layers indices from which to extract representations (0 to num_layers, inclusive)", ) parser.add_argument( "--include", type=str, nargs="+", choices=["mean", "per_tok", "bos", "contacts"], help="specify which representations to return", required=True, ) parser.add_argument( "--truncation_seq_length", type=int, default=1022, help="truncate sequences longer than the given value", )
parser.add_argument("--nogpu", action="store_true", help="Do not use GPU even if available") return parser
def main(args): model, alphabet = pretrained.load_model_and_alphabet(args.model_location) model.eval() if isinstance(model, MSATransformer): raise ValueError( "This script currently does not handle models with MSA input (MSA Transformer)." ) if torch.cuda.is_available() and not args.nogpu: model = model.cuda() print("Transferred model to GPU")
dataset = FastaBatchedDataset.from_file(args.fasta_file) batches = dataset.get_batch_indices(args.toks_per_batch, extra_toks_per_seq=1) data_loader = torch.utils.data.DataLoader( dataset, collate_fn=alphabet.get_batch_converter(args.truncation_seq_length), batch_sampler=batches ) print(f"Read {args.fasta_file} with {len(dataset)} sequences")
args.output_dir.mkdir(parents=True, exist_ok=True) return_contacts = "contacts" in args.include
assert all(-(model.num_layers + 1) <= i <= model.num_layers for i in args.repr_layers) repr_layers = [(i + model.num_layers + 1) % (model.num_layers + 1) for i in args.repr_layers]
with torch.no_grad(): for batch_idx, (labels, strs, toks) in enumerate(data_loader): print( f"Processing {batch_idx + 1} of {len(batches)} batches ({toks.size(0)} sequences)" ) if torch.cuda.is_available() and not args.nogpu: toks = toks.to(device="cuda", non_blocking=True)
out = model(toks, repr_layers=repr_layers, return_contacts=return_contacts)
logits = out["logits"].to(device="cpu") representations = { layer: t.to(device="cpu") for layer, t in out["representations"].items() } if return_contacts: contacts = out["contacts"].to(device="cpu")
for i, label in enumerate(labels): args.output_file = args.output_dir / f"{label}.pt" args.output_file.parent.mkdir(parents=True, exist_ok=True) result = {"label": label} # Call clone on tensors to ensure tensors are not views into a larger representation # See https://github.com/pytorch/pytorch/issues/1995 if "per_tok" in args.include: result["representations"] = { layer: t[i, 1 : len(strs[i]) + 1].clone() for layer, t in representations.items() } if "mean" in args.include: result["mean_representations"] = { layer: t[i, 1 : len(strs[i]) + 1].mean(0).clone() for layer, t in representations.items() } if "bos" in args.include: result["bos_representations"] = { layer: t[i, 0].clone() for layer, t in representations.items() } if return_contacts: result["contacts"] = contacts[i, : len(strs[i]), : len(strs[i])].clone()
torch.save( result, args.output_file, )
if __name__ == "__main__": parser = create_parser() args = parser.parse_args() main(args).gitattributesAdded+23
.gitignoreAdded+164
LICENSEAdded+21
README.mdAdded+158
app.pyAdded+610
baselines/baseline_evaluation.pyAdded+219
baselines/baseline_gnina.pyAdded+175
baselines/baseline_run_tankbind_parallel.shAdded+5
baselines/baseline_tankbind_evaluation.pyAdded+239
baselines/baseline_tankbind_runtime.pyAdded+342
confidence/confidence_train.pyAdded+319
confidence/dataset.pyAdded+272
data/protein_ligand_example_csv.csvAdded+2
data/splits/timesplit_no_lig_overlap_trainAdded+16379
data/splits/timesplit_no_lig_overlap_valAdded+968
data/splits/timesplit_testAdded+363
data/splits/timesplit_test_no_rec_overlapAdded+144
datasets/__init__.pyAdded
datasets/conformer_matching.pyAdded+196
datasets/esm_embedding_preparation.pyAdded+88
datasets/esm_embeddings_to_pt.pyAdded+17
datasets/pdbbind.pyAdded+705
datasets/pdbbind_lm_embedding_preparation.pyAdded+94
datasets/process_mols.pyAdded+550
environment.ymlAdded+102
esm/LICENSEAdded+21
esm/esm/__init__.pyAdded+12
esm/esm/axial_attention.pyAdded+239
esm/esm/constants.pyAdded+10
esm/esm/data.pyAdded+493
esm/esm/inverse_folding/__init__.pyAdded+8
esm/esm/inverse_folding/features.pyAdded+352
esm/esm/inverse_folding/gvp_encoder.pyAdded+56
esm/esm/inverse_folding/gvp_modules.pyAdded+473
esm/esm/inverse_folding/gvp_transformer.pyAdded+137
esm/esm/inverse_folding/gvp_transformer_encoder.pyAdded+184
esm/esm/inverse_folding/gvp_utils.pyAdded+68
esm/esm/inverse_folding/multichain_util.pyAdded+151
esm/esm/inverse_folding/transformer_decoder.pyAdded+228
esm/esm/inverse_folding/transformer_layer.pyAdded+304
esm/esm/inverse_folding/util.pyAdded+320
esm/esm/model/esm1.pyAdded+200
esm/esm/model/esm2.pyAdded+147
esm/esm/model/msa_transformer.pyAdded+238
esm/esm/modules.pyAdded+418
esm/esm/multihead_attention.pyAdded+508
esm/esm/pretrained.pyAdded+397
esm/esm/rotary_embedding.pyAdded+69
esm/esm/version.pyAdded+6
esm/scripts/extract.pyAdded+142