pan-li commited on
Commit
bcc9868
·
verified ·
1 Parent(s): 4817a5c

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -57,3 +57,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
60
+ md5_to_str.fasta filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,3 +1,62 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dataset Card for Fold Prediction Dataset for RAGProtein
2
+
3
+ ### Dataset Summary
4
+
5
+ Fold class prediction is a scientific classification task that assigns protein sequences to one of 1,195 known folds. The primary application of this task lies in the identification of novel remote homologs among proteins of interest, such as emerging antibiotic-resistant genes and industrial enzymes. The study of protein fold holds great significance in fields like proteomics and structural biology, as it facilitates the analysis of folding patterns, leading to the discovery of remote homologies and advancements in disease research.
6
+
7
+ ## Dataset Structure
8
+
9
+ ### Data Instances
10
+ For each instance, there is a string representing the protein sequence and an integer label indicating which know fold a protein sequence belongs to. See the [fold prediction dataset viewer](https://huggingface.co/datasets/Bo1015/fold_prediction/viewer) to explore more examples.
11
+
12
+ ```
13
+ {'seq':'MEHVIDNFDNIDKCLKCGKPIKVVKLKYIKKKIENIPNSHLINFKYCSKCKRENVIENL'
14
+ 'label':6,
15
+ 'msa': 'MEHVIDNFDNIDKCLKCGKPIKVVKLKYIKKKIENIPNSHLINFKYCSKCKRENVIENL|MEHVIDNFDNIDKCLKCGKPIKVVKLKYIKKKIENIPNSHLINFKYCSKCKRENVIENL...',
16
+ 'str_emb': [seq_len, 384]
17
+ }
18
+ ```
19
+
20
+ The average for the `seq` and the `label` are provided below:
21
+
22
+ | Feature | Mean Count |
23
+ | ---------- | ---------------- |
24
+ | seq | 168 |
25
+
26
+ ### Data Fields
27
+
28
+ - `seq`: a string containing the protein sequence.
29
+ - `label`: an integer label indicating which know fold a protein sequence belongs to.
30
+ - `msa`: "|" seperated MSA sequences
31
+ - `str_emb`: AIDO.StructureTokenizer generated structure embedding from AF2 predicted structures
32
+
33
+ ### Data Splits
34
+
35
+ The fold prediction dataset has 3 splits: _train_, _valid_ and _test_. Below are the statistics of the dataset.
36
+
37
+ | Dataset Split | Number of Instances in Split |
38
+ | ------------- | ------------------------------------------- |
39
+ | Train | 12,312 |
40
+ |Valid | 736|
41
+ | Test | 3,244 |
42
+
43
+ ### Source Data
44
+
45
+ #### Initial Data Collection and Normalization
46
+ The dataset employed for this task is based on [SCOP 1.75](https://scop.mrc-lmb.cam.ac.uk/), a release from 2009.
47
+
48
+ ### Processed data collection
49
+
50
+ Single sequence data are collected from this paper:
51
+
52
+ ```
53
+ @misc{chen2024xtrimopglm,
54
+ title={xTrimoPGLM: unified 100B-scale pre-trained transformer for deciphering the language of protein},
55
+ author={Chen, Bo and Cheng, Xingyi and Li, Pan and Geng, Yangli-ao and Gong, Jing and Li, Shen and Bei, Zhilei and Tan, Xu and Wang, Boyan and Zeng, Xin and others},
56
+ year={2024},
57
+ eprint={2401.06199},
58
+ archivePrefix={arXiv},
59
+ primaryClass={cs.CL},
60
+ note={arXiv preprint arXiv:2401.06199}
61
+ }
62
+ ```
codebook.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:52139fb587368235751a0464fd3be7a6beb0fff2e96a0164012f858702a9bcf8
3
+ size 787617
data/test-00000-of-00001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4d2b7b16e1a1233b5731c8ff563cf22a56f9d75d8234bcb00bf9c1e66b2ccf49
3
+ size 575690
data/train-00000-of-00001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a4d00acfc8eeb08ca27fc617afa6cdd8e56aea2b196663d67d8744025772fc11
3
+ size 2177604
data/valid-00000-of-00001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f29bfbd098f445e6ce5f62c0b3e525a1fef3535df3f781e88302c06b5099f80
3
+ size 133240
fold_prediction-rag.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #-*- coding:utf-8 -*-
2
+
3
+ # import sys, os, shutil, re, logging, subprocess, string, io, argparse, bisect, concurrent, gzip, zipfile, tarfile, json, pickle, time, datetime, random, math, copy, itertools, functools, collections, multiprocessing, threading, queue, signal, inspect, warnings, distutils.spawn
4
+ import sys
5
+ import os
6
+ import pickle
7
+ import re
8
+ import torch
9
+ import random
10
+ import gzip
11
+ from os.path import exists, join, getsize, isfile, isdir, abspath, basename
12
+ from typing import Dict, Union, Optional, List, Tuple, Mapping
13
+ import numpy as np
14
+ import pandas as pd
15
+ from tqdm.auto import trange, tqdm
16
+ from concurrent.futures import ThreadPoolExecutor, as_completed
17
+ from typing import Dict, Union, Optional, List, Tuple, Mapping
18
+ import datasets
19
+
20
+ def get_md5(aa_str):
21
+ """
22
+ Calculate MD5 values for protein sequence
23
+ """
24
+ import hashlib
25
+ assert isinstance(aa_str, str), aa_str
26
+
27
+ aa_str = aa_str.upper()
28
+ return hashlib.md5(aa_str.encode('utf-8')).hexdigest()
29
+
30
+ def load_fasta(seqFn, rem_tVersion=False, load_annotation=False, full_line_as_id=False):
31
+ """
32
+ seqFn -- Fasta file or input handle (with readline implementation)
33
+ rem_tVersion -- Remove version information. ENST000000022311.2 => ENST000000022311
34
+ load_annotation -- Load sequence annotation
35
+ full_line_as_id -- Use the full head line (starts with >) as sequence ID. Can not be specified simutanouly with load_annotation
36
+
37
+ Return:
38
+ {tid1: seq1, ...} if load_annotation==False
39
+ {tid1: seq1, ...},{tid1: annot1, ...} if load_annotation==True
40
+ """
41
+ if load_annotation and full_line_as_id:
42
+ raise RuntimeError("Error: load_annotation and full_line_as_id can not be specified simutanouly")
43
+ if rem_tVersion and full_line_as_id:
44
+ raise RuntimeError("Error: rem_tVersion and full_line_as_id can not be specified simutanouly")
45
+
46
+ fasta = {}
47
+ annotation = {}
48
+ cur_tid = ''
49
+ cur_seq = ''
50
+
51
+ if isinstance(seqFn, str):
52
+ IN = open(seqFn)
53
+ elif hasattr(seqFn, 'readline'):
54
+ IN = seqFn
55
+ else:
56
+ raise RuntimeError(f"Expected seqFn: {type(seqFn)}")
57
+ for line in IN:
58
+ if line[0] == '>':
59
+ if cur_tid != '':
60
+ fasta[cur_tid] = re.sub(r"\s", "", cur_seq)
61
+ cur_seq = ''
62
+ data = line[1:-1].split(None, 1)
63
+ cur_tid = line[1:-1] if full_line_as_id else data[0]
64
+ annotation[cur_tid] = data[1] if len(data)==2 else ""
65
+ if rem_tVersion and '.' in cur_tid:
66
+ cur_tid = ".".join(cur_tid.split(".")[:-1])
67
+ elif cur_tid != '':
68
+ cur_seq += line.rstrip()
69
+
70
+ if isinstance(seqFn, str):
71
+ IN.close()
72
+
73
+ if cur_seq != '':
74
+ fasta[cur_tid] = re.sub(r"\s", "", cur_seq)
75
+
76
+ if load_annotation:
77
+ return fasta, annotation
78
+ else:
79
+ return fasta
80
+
81
+ def load_msa_txt(file_or_stream, load_id=False, load_annot=False, sort=False):
82
+ """
83
+ Read msa txt file
84
+
85
+ Parmeters
86
+ --------------
87
+ file_or_stream: file or stream to read (with read method)
88
+ load_id: read identity and return
89
+
90
+ Return
91
+ --------------
92
+ msa: list of msa sequences, the first sequence in msa is the query sequence
93
+ id_arr: Identity of msa sequences
94
+ annotations: Annotations of msa sequences
95
+ """
96
+ msa = []
97
+ id_arr = []
98
+ annotations = []
99
+
100
+ if hasattr(file_or_stream, 'read'):
101
+ lines = file_or_stream.read().strip().split('\n')
102
+ elif file_or_stream.endswith('.gz'):
103
+ with gzip.open(file_or_stream) as IN:
104
+ lines = IN.read().decode().strip().split('\n')
105
+ else:
106
+ with open(file_or_stream) as IN:
107
+ lines = IN.read().strip().split('\n')
108
+ # lines = open(file_or_stream).read().strip().split('\n')
109
+
110
+ for idx,line in enumerate(lines):
111
+ data = line.strip().split()
112
+ if idx == 0:
113
+ assert len(data) == 1, f"Expect 1 element for the 1st line, but got {data} in {file_or_stream}"
114
+ q_seq = data[0]
115
+ else:
116
+ if len(data) >= 2:
117
+ id_arr.append( float(data[1]) )
118
+ else:
119
+ assert len(q_seq) == len(data[0])
120
+ id_ = round(np.mean([ r1==r2 for r1,r2 in zip(q_seq, data[0]) ]), 3)
121
+ id_arr.append(id_)
122
+ msa.append( data[0] )
123
+ if len(data) >= 3:
124
+ annot = " ".join(data[2:])
125
+ annotations.append( annot )
126
+ else:
127
+ annotations.append(None)
128
+
129
+ id_arr = np.array(id_arr, dtype=np.float64)
130
+ if sort:
131
+ id_order = np.argsort(id_arr)[::-1]
132
+ msa = [ msa[i] for i in id_order ]
133
+ id_arr = id_arr[id_order]
134
+ annotations = [ annotations[i] for i in id_order ]
135
+ msa = [q_seq] + msa
136
+
137
+ outputs = [ msa ]
138
+ if load_id:
139
+ outputs.append( id_arr )
140
+ if load_annot:
141
+ outputs.append( annotations )
142
+ if len(outputs) == 1:
143
+ return outputs[0]
144
+ return outputs
145
+
146
+ # Find for instance the citation on arxiv or on the dataset repo/website
147
+ _CITATION = """
148
+ """
149
+
150
+ # You can copy an official description
151
+ _DESCRIPTION = """
152
+ """
153
+
154
+ _HOMEPAGE = "xxxxx"
155
+
156
+ _LICENSE = "xxxxx"
157
+
158
+ class DownStreamConfig(datasets.BuilderConfig):
159
+ """BuilderConfig for downstream taks dataset."""
160
+
161
+ def __init__(self, *args, **kwargs):
162
+ """BuilderConfig downstream tasks dataset.
163
+ Args:
164
+ **kwargs: keyword arguments forwarded to super.
165
+ """
166
+ super().__init__(*args, name=f"downstream", **kwargs)
167
+
168
+ class DownStreamTasks(datasets.GeneratorBasedBuilder):
169
+ VERSION = datasets.Version("1.1.0")
170
+ BUILDER_CONFIG_CLASS = DownStreamConfig
171
+ BUILDER_CONFIGS = [ DownStreamConfig() ]
172
+ DEFAULT_CONFIG_NAME = None
173
+
174
+ def _info(self):
175
+ features = datasets.Features(
176
+ {
177
+ "seq": datasets.Value("string"),
178
+ "label": datasets.Value("int32"),
179
+ "msa": datasets.Value("string"),
180
+ "str_emb": datasets.Array2D(shape=(None, 384), dtype='float32'),
181
+ }
182
+ )
183
+ return datasets.DatasetInfo(
184
+ # This is the description that will appear on the datasets page.
185
+ description=_DESCRIPTION,
186
+ # This defines the different columns of the dataset and their types
187
+ features=features,
188
+ # Homepage of the dataset for documentation
189
+ homepage=_HOMEPAGE,
190
+ # License for the dataset if available
191
+ license=_LICENSE,
192
+ # Citation for the dataset
193
+ citation=_CITATION,
194
+ )
195
+
196
+ def _split_generators(
197
+ self, dl_manager: datasets.DownloadManager
198
+ ) -> List[datasets.SplitGenerator]:
199
+ # breakpoint()
200
+ train_parquet_file = dl_manager.download(f"data/train-00000-of-00001.parquet")
201
+ valid_parquet_file = dl_manager.download(f"data/valid-00000-of-00001.parquet")
202
+ test_parquet_file = dl_manager.download(f"data/test-00000-of-00001.parquet")
203
+ msa_path = dl_manager.download_and_extract(f"msa.tar")
204
+ str_file = dl_manager.download(f"md5_to_str.fasta")
205
+ codebook_file = dl_manager.download(f"codebook.pt")
206
+
207
+ assert os.path.exists(join(msa_path, 'msa'))
208
+ msa_path = join(msa_path, 'msa')
209
+
210
+ return [
211
+ datasets.SplitGenerator(
212
+ name=datasets.Split.TRAIN,
213
+ gen_kwargs={
214
+ "parquet_file": train_parquet_file,
215
+ "msa_path": msa_path,
216
+ "str_file": str_file,
217
+ "codebook_file": codebook_file
218
+ }
219
+ ),
220
+ datasets.SplitGenerator(
221
+ name=datasets.Split.VALIDATION,
222
+ gen_kwargs={
223
+ "parquet_file": valid_parquet_file,
224
+ "msa_path": msa_path,
225
+ "str_file": str_file,
226
+ "codebook_file": codebook_file
227
+ }
228
+ ),
229
+ datasets.SplitGenerator(
230
+ name=datasets.Split.TEST,
231
+ gen_kwargs={
232
+ "parquet_file": test_parquet_file,
233
+ "msa_path": msa_path,
234
+ "str_file": str_file,
235
+ "codebook_file": codebook_file
236
+ }
237
+ ),
238
+ ]
239
+
240
+ # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
241
+ def _generate_examples(self, parquet_file, msa_path, str_file, codebook_file):
242
+
243
+ dataset = datasets.Dataset.from_parquet(parquet_file)
244
+ md5_to_str = load_fasta(str_file)
245
+ codebook = torch.load(codebook_file, 'cpu', weights_only=True).numpy()
246
+
247
+ for key, item in enumerate(dataset):
248
+ seq = item['seq']
249
+ label = item['label']
250
+ md5_val = get_md5(seq)
251
+ if md5_val not in md5_to_str or md5_to_str[md5_val] == "":
252
+ str_emb = np.zeros([len(seq), 384], dtype=np.float32)
253
+ else:
254
+ str_toks = np.array([ int(x) for x in md5_to_str[md5_val].split('-')])
255
+ str_emb = codebook[str_toks]
256
+
257
+ msa = load_msa_txt(join(msa_path, md5_val+'.txt.gz'))
258
+ assert len(msa[0]) == len(seq), f"Error: {len(msa[0])} != {len(seq)}"
259
+ assert len(msa[0]) == str_emb.shape[0], f"Error: {len(msa[0])} != {str_emb.shape[0]}"
260
+ # breakpoint()
261
+ yield key, {
262
+ "seq": seq,
263
+ "label": label,
264
+ "msa": "|".join(msa),
265
+ "str_emb": str_emb
266
+ }
md5_to_str.fasta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2bd6843a0c18415f270860f37394e25aa158ef78f20d61642c21fccaf20f4970
3
+ size 10808271
msa.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:340f8472a51949226429af393bb4990b1c3567ec79b4539b1bb9ac94ffdecec8
3
+ size 3123640320