{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# data check\nfrom collections import Counter\n\n# transformer\nimport torch\nfrom transformers import BertModel, BertTokenizer\nimport datasets\n\n# analysis\nfrom sklearn.cluster import KMeans\nfrom sklearn.mixture import GaussianMixture\nfrom sklearn.cluster import AgglomerativeClustering\nfrom umap import UMAP\nfrom sklearn.preprocessing import MinMaxScaler\n\n# visualization\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport time\n\n# use biopython to extract protein properties\nfrom Bio.SeqUtils.ProtParam import ProteinAnalysis\n\n# util\nfrom tqdm import tqdm\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-04-25T11:50:45.987797Z","iopub.execute_input":"2023-04-25T11:50:45.988419Z","iopub.status.idle":"2023-04-25T11:50:46.001026Z","shell.execute_reply.started":"2023-04-25T11:50:45.988381Z","shell.execute_reply":"2023-04-25T11:50:45.999652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load model","metadata":{}},{"cell_type":"code","source":"%%time\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\ntokenizer = BertTokenizer.from_pretrained(\"Rostlab/prot_bert\", do_lower_case=False )\nmodel = BertModel.from_pretrained(\"Rostlab/prot_bert\").to(device)","metadata":{"execution":{"iopub.status.busy":"2023-04-25T11:33:28.990507Z","iopub.execute_input":"2023-04-25T11:33:28.991675Z","iopub.status.idle":"2023-04-25T11:34:28.546255Z","shell.execute_reply.started":"2023-04-25T11:33:28.991616Z","shell.execute_reply":"2023-04-25T11:34:28.544998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Start looking on the CAFA5 data","metadata":{}},{"cell_type":"code","source":"from Bio import SeqIO\ntrain_fn = '/kaggle/input/cafa-5-protein-function-prediction/Train/train_sequences.fasta'\ntest_fn = '/kaggle/input/cafa-5-protein-function-prediction/Test (Targets)/testsuperset.fasta'\n\nsequences = SeqIO.parse(train_fn, \"fasta\")\ntrain_l = [len(seq) for seq in sequences ] \nprint(pd.Series(train_l).describe() )\nsequences = SeqIO.parse(test_fn, \"fasta\")\ntest_l = [len(seq) for seq in sequences ] \nprint(pd.Series(test_l).describe() )\n","metadata":{"execution":{"iopub.status.busy":"2023-04-25T11:41:24.722222Z","iopub.execute_input":"2023-04-25T11:41:24.723178Z","iopub.status.idle":"2023-04-25T11:41:28.385336Z","shell.execute_reply.started":"2023-04-25T11:41:24.723142Z","shell.execute_reply":"2023-04-25T11:41:28.383893Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(10,4))\nplt.subplot(121)\nplt.title('Train set')\nplt.hist(train_l, bins=50)\nplt.yscale('log')\nplt.subplot(122)\nplt.title('Test set')\nplt.hist(test_l, bins=50)\nplt.yscale('log')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-04-25T11:42:35.384178Z","iopub.execute_input":"2023-04-25T11:42:35.384867Z","iopub.status.idle":"2023-04-25T11:42:37.511274Z","shell.execute_reply.started":"2023-04-25T11:42:35.384831Z","shell.execute_reply":"2023-04-25T11:42:37.509721Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"clip_first_n_symbols=1200","metadata":{"execution":{"iopub.status.busy":"2023-04-25T11:51:16.344836Z","iopub.execute_input":"2023-04-25T11:51:16.345814Z","iopub.status.idle":"2023-04-25T11:51:16.350883Z","shell.execute_reply.started":"2023-04-25T11:51:16.345761Z","shell.execute_reply":"2023-04-25T11:51:16.349599Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Emdedding for many proteins","metadata":{}},{"cell_type":"code","source":"sequences = SeqIO.parse(train_fn, \"fasta\")\nemb_list=[]\nid_list=[]\nt00 = time.time()\nfor seq in tqdm(sequences):\n    t0 = time.time()\n    sequence_example = seq[:clip_first_n_symbols]\n    sequence_example = ' '.join(list(sequence_example))\n\n    encoded_input = tokenizer(sequence_example, return_tensors='pt').to(device)\n    output = model(**encoded_input)   \n    id_list.append(seq.id)\n    emb_list.append(output['last_hidden_state'][:,0][0].detach().cpu().numpy())\n    \nprint('Time:',time.time()-t00)\n    \nnp.save('train_ids.npy',np.array(id_list))\nnp.save('train_embeddings.npy',np.array(emb_list))    \n","metadata":{"execution":{"iopub.status.busy":"2023-04-25T11:52:54.355078Z","iopub.execute_input":"2023-04-25T11:52:54.355805Z","iopub.status.idle":"2023-04-25T11:56:10.7063Z","shell.execute_reply.started":"2023-04-25T11:52:54.355768Z","shell.execute_reply":"2023-04-25T11:56:10.704254Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sequences = SeqIO.parse(test_fn, \"fasta\")\nemb_list=[]\nid_list=[]\nt00 = time.time()\nfor seq in tqdm(sequences):\n    t0 = time.time()\n    sequence_example = seq[:clip_first_n_symbols]\n    sequence_example = ' '.join(list(sequence_example))\n\n    encoded_input = tokenizer(sequence_example, return_tensors='pt').to(device)\n    output = model(**encoded_input)   \n    id_list.append(seq.id)\n    emb_list.append(output['last_hidden_state'][:,0][0].detach().cpu().numpy())\n    \nprint('Time:',time.time()-t00)\n\nnp.save('test_ids.npy',np.array(id_list))\nnp.save('test_embeddings.npy',np.array(emb_list))","metadata":{"execution":{"iopub.status.busy":"2023-04-22T18:58:00.081946Z","iopub.execute_input":"2023-04-22T18:58:00.082343Z","iopub.status.idle":"2023-04-22T18:58:00.123842Z","shell.execute_reply.started":"2023-04-22T18:58:00.082305Z","shell.execute_reply":"2023-04-22T18:58:00.122898Z"},"trusted":true},"execution_count":null,"outputs":[]}]}