anindya64 commited on
Commit
ed1616a
·
verified ·
1 Parent(s): 79354b4

Replace nested FireProtDB rows with flat Parquet train/test table

Browse files
README.md CHANGED
@@ -13,72 +13,148 @@ tags:
13
  - stability
14
  - mutation
15
  - fireprotdb
16
- - jsonl
 
 
 
 
 
 
 
 
 
 
 
17
  ---
18
 
19
  # FireProtDB
20
 
21
- FireProtDB protein stability mutation dataset, normalized to newline-delimited JSON with row-level provenance.
22
 
23
- Processed and uploaded by the [MegaData](https://github.com/) post-download pipeline
24
- (internal repo). Original source: <https://loschmidt.chemi.muni.cz/fireprotdb/>.
25
 
26
- ## Statistics
27
 
28
- | | |
29
- |---|---|
30
- | Table files | 1 |
31
- | Total rows | 5,465,660 |
32
- | Total bytes | 8.48 GiB (9,105,270,725) |
 
 
 
 
 
33
 
34
- ## Tables
35
 
36
- | Table | Rows | Bytes |
37
- |---|---:|---:|
38
- | `labeled_fireprotdb_fireprotdb_search_all.jsonl.jsonl` | 5,465,660 | 8.48 GiB |
39
 
40
- ## Layout
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  ```
43
- .
44
- ├── _MANIFEST.json # aggregate manifest (per-table counts)
45
- └── tables/<source_slug>.jsonl # normalized rows (one JSON object per line)
 
 
 
 
46
  ```
47
 
48
- Each line in a `tables/*.jsonl` file is a JSON object with at least
49
- `dataset_id`, `row` (the raw upstream row), `row_index`, and `source_file`
50
- fields, so every row carries its upstream provenance.
51
 
52
- ## Loading
 
53
 
54
- ```bash
55
- hf download LiteFold/FireProtDB --repo-type dataset --local-dir ./fireprotdb
56
  ```
57
 
58
- Programmatic streaming:
59
 
60
  ```python
61
- import json
62
- from pathlib import Path
63
- from huggingface_hub import snapshot_download
64
-
65
- local = snapshot_download(repo_id="LiteFold/FireProtDB", repo_type="dataset")
66
- for jsonl in sorted(Path(local, "tables").glob("*.jsonl")):
67
- with jsonl.open() as f:
68
- for line in f:
69
- row = json.loads(line)
70
- ... # row["row"] is the upstream record
71
  ```
72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  ## License
74
 
75
- CC BY 4.0 (FireProtDB).
76
 
77
  ## Citation
78
 
79
- > Stourac J, et al. FireProtDB: database of manually curated protein stability data. Nucleic Acids Research, 49(D1):D319-D324, 2021.
80
-
81
- ## Provenance
82
 
83
- Built from the local manifest entry `fireprotdb` of `manifests/atlas_download_plan.json`.
84
- Pipeline source: `megadata-post normalize --dataset fireprotdb --tables-only`.
 
13
  - stability
14
  - mutation
15
  - fireprotdb
16
+ - protein-engineering
17
+ - train-test-split
18
+ - parquet
19
+ configs:
20
+ - config_name: default
21
+ data_files:
22
+ - split: train
23
+ path:
24
+ - data/train-*.parquet
25
+ - split: test
26
+ path:
27
+ - data/test-*.parquet
28
  ---
29
 
30
  # FireProtDB
31
 
32
+ This is a flat, Dataset Viewer-friendly version of LiteFold/FireProtDB. The previous repository layout stored each row as a deeply nested `row` object, which made schema inference fail in the Hugging Face Dataset Viewer. This version keeps one row per upstream FireProtDB sequence or mutant experiment and exposes the main protein, mutation, structure, experiment, measurement, annotation, and publication fields as scalar columns.
33
 
34
+ Variable upstream lists are summarized into pipe-delimited columns such as `measurement_types`, `annotation_types`, `uniprot_accessions`, `interpro_accessions`, and `pdb_ids`. The original annotation, measurement, and feature lists are also retained as JSON strings in `annotations_json`, `measurements_json`, and `features_json`.
 
35
 
36
+ ## Dataset Summary
37
 
38
+ | Metric | Value |
39
+ |---|---:|
40
+ | Rows | 5,465,660 |
41
+ | Columns | 99 |
42
+ | Source table bytes | 8,466,920,603 |
43
+ | Mutant rows | 5,453,252 |
44
+ | Sequence rows | 12,408 |
45
+ | Substitution events | 5,543,778 |
46
+ | Deletion events | 54,296 |
47
+ | Insertion events | 50,613 |
48
 
49
+ ## Splits
50
 
51
+ Splits are deterministic by source row id:
 
 
52
 
53
+ `sha256("fireprotdb:{row_index}") % 10`
54
 
55
+ Bucket `0` is `test`; buckets `1` through `9` are `train`.
56
+
57
+ | Split | Rows |
58
+ |---|---:|
59
+ | `train` | 4,919,161 |
60
+ | `test` | 546,499 |
61
+
62
+ ## Source Datasets
63
+
64
+ | Experiment dataset | Rows |
65
+ |---|---:|
66
+ | Domainome DDG | 4,071,188 |
67
+ | MegaScale | 775,235 |
68
+ | Domainome FITNESS | 591,671 |
69
+ | ProTherm | 27,406 |
70
+ | COZYME | 160 |
71
+
72
+ ## Common Measurement Columns
73
+
74
+ The table includes scalar columns for common FireProtDB measurements:
75
+
76
+ `tm`, `dtm`, `dg`, `dg_text`, `ddg`, `dh`, `dcp`, `dhvh`, `cm`, `m_value`, `trypsin_ml`, `chymotrypsin_ml`, `stabilizing`, `stabilizing_text`, `domainome_fitness`, `domainome_fitness_std`, `domainome_ddg`, `domainome_ddg_std`, `reversibility`, and `state`.
77
+
78
+ If a row has multiple measurements of the same type, the scalar column stores the first value and `measurements_json` retains the full upstream measurement list.
79
+
80
+ ## Loading With `datasets`
81
+
82
+ ```python
83
+ from datasets import load_dataset
84
+
85
+ ds = load_dataset("LiteFold/FireProtDB")
86
+ train = ds["train"]
87
+ test = ds["test"]
88
+
89
+ print(train[0]["protein_name"], train[0]["mutations"], train[0]["tm"])
90
  ```
91
+
92
+ Load a split directly:
93
+
94
+ ```python
95
+ from datasets import load_dataset
96
+
97
+ train = load_dataset("LiteFold/FireProtDB", split="train")
98
  ```
99
 
100
+ Filter for rows with DDG measurements:
 
 
101
 
102
+ ```python
103
+ from datasets import load_dataset
104
 
105
+ train = load_dataset("LiteFold/FireProtDB", split="train")
106
+ ddg_rows = train.filter(lambda row: row["ddg"] is not None)
107
  ```
108
 
109
+ Stream rows without downloading the full table first:
110
 
111
  ```python
112
+ from datasets import load_dataset
113
+
114
+ rows = load_dataset("LiteFold/FireProtDB", split="train", streaming=True)
115
+ for row in rows:
116
+ print(row["row_id"], row["experiment_dataset"], row["measurement_types"])
117
+ break
 
 
 
 
118
  ```
119
 
120
+ ## Column Groups
121
+
122
+ Provenance:
123
+ `row_id`, `dataset_id`, `source_dataset`, `source_file`, `source_table`, `source_sha`, `row_index`, `split`, `subject_type`.
124
+
125
+ Protein and sequence:
126
+ `entry_id`, `sequence_id`, `target_sequence_id`, `source_sequence_length`, `target_sequence_length`, `protein_id`, `protein_name`, `organism`, `isoform`, `protein_ids`, `protein_names`, `organisms`, `isoforms`, `uniprot_accessions`, `interpro_accessions`, `ec_numbers`, `megascale_ids`, `other_references`.
127
+
128
+ Mutation and features:
129
+ `mutations`, `substitutions`, `deletions`, `insertions`, `mutation_count`, `substitution_count`, `deletion_count`, `insertion_count`, `first_position`, `first_source_aa`, `first_target_aa`, `conservation`, `feature_types`, `features_json`.
130
+
131
+ Structure:
132
+ `pdb_ids`, `afdb_ids`, `structure_ids`, `structure_methods`, `structure_resolution_min`, `residue_positions`, `residue_chain_names`, `residue_secondary_structures`, `residue_in_pocket_any`, `residue_in_tunnel_any`, `residue_asa_mean`, `residue_bfactor_mean`.
133
+
134
+ Experiment and measurements:
135
+ `experiment_id`, `experiment_dataset`, `ph`, `measure`, `method`, `buffer`, `buffer_conc`, `exp_temperature`, `ion`, `ion_conc`, `pdb_chain_mutation`, measurement columns, `measurement_types`, `measurement_datasets`, `annotation_types`, `annotations_json`, `measurements_json`.
136
+
137
+ Publication:
138
+ `publication_id`, `publication_type`, `publication_title`, `publication_year`, `publication_doi`, `publication_pmid`, `publication_journal`, `publication_url`, `publication_author_count`, `publication_authors`.
139
+
140
+ ## Files
141
+
142
+ - `data/train-*.parquet`: train split.
143
+ - `data/test-*.parquet`: test split.
144
+ - `_MANIFEST.json`: source provenance, split counts, and output schema.
145
+ - `dataset_summary.json`: processing summary and source/measurement counts.
146
+ - `scripts/prepare_fireprotdb_dataset.py`: script used to generate the flat table.
147
+
148
+ ## Source
149
+
150
+ Derived from LiteFold/FireProtDB, originally sourced from FireProtDB.
151
+
152
  ## License
153
 
154
+ CC BY 4.0.
155
 
156
  ## Citation
157
 
158
+ If you use this dataset, cite FireProtDB:
 
 
159
 
160
+ Stourac J, et al. FireProtDB: database of manually curated protein stability data. Nucleic Acids Research, 49(D1):D319-D324, 2021.
 
_MANIFEST.json CHANGED
@@ -1,17 +1,131 @@
1
  {
2
- "category": "labeled",
3
  "dataset_id": "fireprotdb",
4
- "format": "jsonl table rows with provenance",
5
- "tables": [
6
- {
7
- "bytes": 8466920603,
8
- "category": "labeled",
9
- "dataset_id": "fireprotdb",
10
- "output_file": "data/processed/labeled/fireprotdb/tables/labeled_fireprotdb_fireprotdb_search_all.jsonl.jsonl",
11
- "rows": 5465660,
12
- "source_file": "labeled/fireprotdb/fireprotdb_search_all.jsonl",
13
- "status": "ok"
14
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  ],
16
- "total_rows": 5465660
17
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  {
 
2
  "dataset_id": "fireprotdb",
3
+ "source_repo": "LiteFold/FireProtDB",
4
+ "source_sha": "79354b4f8754e21c3eb41aaf3dd63ba34ae750cd",
5
+ "source_table": "tables/labeled_fireprotdb_fireprotdb_search_all.jsonl.jsonl",
6
+ "format": "flat parquet table rows",
7
+ "total_rows": 5465660,
8
+ "split_counts": {
9
+ "test": 546499,
10
+ "train": 4919161
11
+ },
12
+ "split_strategy": "deterministic sha256('fireprotdb:{row_index}') % 10; bucket 0 is test, buckets 1-9 are train",
13
+ "columns": [
14
+ "row_id",
15
+ "dataset_id",
16
+ "source_dataset",
17
+ "source_file",
18
+ "source_table",
19
+ "source_sha",
20
+ "row_index",
21
+ "split",
22
+ "subject_type",
23
+ "entry_id",
24
+ "sequence_id",
25
+ "target_sequence_id",
26
+ "source_sequence_length",
27
+ "target_sequence_length",
28
+ "protein_id",
29
+ "protein_name",
30
+ "organism",
31
+ "isoform",
32
+ "protein_ids",
33
+ "protein_names",
34
+ "organisms",
35
+ "isoforms",
36
+ "uniprot_accessions",
37
+ "interpro_accessions",
38
+ "ec_numbers",
39
+ "megascale_ids",
40
+ "other_references",
41
+ "mutations",
42
+ "substitutions",
43
+ "deletions",
44
+ "insertions",
45
+ "mutation_count",
46
+ "substitution_count",
47
+ "deletion_count",
48
+ "insertion_count",
49
+ "first_position",
50
+ "first_source_aa",
51
+ "first_target_aa",
52
+ "conservation",
53
+ "feature_types",
54
+ "pdb_ids",
55
+ "afdb_ids",
56
+ "structure_ids",
57
+ "structure_methods",
58
+ "structure_resolution_min",
59
+ "residue_positions",
60
+ "residue_chain_names",
61
+ "residue_secondary_structures",
62
+ "residue_in_pocket_any",
63
+ "residue_in_tunnel_any",
64
+ "residue_asa_mean",
65
+ "residue_bfactor_mean",
66
+ "experiment_id",
67
+ "experiment_dataset",
68
+ "ph",
69
+ "measure",
70
+ "method",
71
+ "buffer",
72
+ "buffer_conc",
73
+ "exp_temperature",
74
+ "ion",
75
+ "ion_conc",
76
+ "pdb_chain_mutation",
77
+ "tm",
78
+ "dtm",
79
+ "dg",
80
+ "dg_text",
81
+ "ddg",
82
+ "dh",
83
+ "dcp",
84
+ "dhvh",
85
+ "cm",
86
+ "m_value",
87
+ "trypsin_ml",
88
+ "chymotrypsin_ml",
89
+ "stabilizing",
90
+ "stabilizing_text",
91
+ "domainome_fitness",
92
+ "domainome_fitness_std",
93
+ "domainome_ddg",
94
+ "domainome_ddg_std",
95
+ "reversibility",
96
+ "state",
97
+ "measurement_types",
98
+ "measurement_datasets",
99
+ "annotation_types",
100
+ "publication_id",
101
+ "publication_type",
102
+ "publication_title",
103
+ "publication_year",
104
+ "publication_doi",
105
+ "publication_pmid",
106
+ "publication_journal",
107
+ "publication_url",
108
+ "publication_author_count",
109
+ "publication_authors",
110
+ "annotations_json",
111
+ "measurements_json",
112
+ "features_json"
113
  ],
114
+ "source_manifest": {
115
+ "category": "labeled",
116
+ "dataset_id": "fireprotdb",
117
+ "format": "jsonl table rows with provenance",
118
+ "tables": [
119
+ {
120
+ "bytes": 8466920603,
121
+ "category": "labeled",
122
+ "dataset_id": "fireprotdb",
123
+ "output_file": "data/processed/labeled/fireprotdb/tables/labeled_fireprotdb_fireprotdb_search_all.jsonl.jsonl",
124
+ "rows": 5465660,
125
+ "source_file": "labeled/fireprotdb/fireprotdb_search_all.jsonl",
126
+ "status": "ok"
127
+ }
128
+ ],
129
+ "total_rows": 5465660
130
+ }
131
+ }
tables/labeled_fireprotdb_fireprotdb_search_all.jsonl.jsonl → data/test-00000-of-00001.parquet RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:93e3a0cba25344711fd3cd90e48031edf91651fc8e1b009c5f171fce894dfedc
3
- size 9105270725
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1888126fe69ee587d9cee5a16fe971c151b91aa14e693d172deab33da7ac492c
3
+ size 38378731
data/train-00000-of-00001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e5b9eb818cf9f4675c30f7d2c24ae7e2aa33e611bf6fb51a8934fbf263e02c1
3
+ size 265529606
dataset_summary.json ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source": "LiteFold/FireProtDB",
3
+ "source_sha": "79354b4f8754e21c3eb41aaf3dd63ba34ae750cd",
4
+ "source_table": "tables/labeled_fireprotdb_fireprotdb_search_all.jsonl.jsonl",
5
+ "source_table_rows": 5465660,
6
+ "source_table_bytes": 8466920603,
7
+ "viewer_table_scope": "flat FireProtDB experiment/mutation rows",
8
+ "data_format": "parquet",
9
+ "rows": 5465660,
10
+ "splits": {
11
+ "test": 546499,
12
+ "train": 4919161
13
+ },
14
+ "subject_type_counts": {
15
+ "mutant": 5453252,
16
+ "sequence": 12408
17
+ },
18
+ "experiment_dataset_counts": {
19
+ "Domainome DDG": 4071188,
20
+ "MegaScale": 775235,
21
+ "Domainome FITNESS": 591671,
22
+ "ProTherm": 27406,
23
+ "COZYME": 160
24
+ },
25
+ "measurement_type_counts": {
26
+ "DOMAINOME_DDG": 4071188,
27
+ "DOMAINOME_DDG_STD": 4071188,
28
+ "DG": 780672,
29
+ "TRYPSIN_ML": 769050,
30
+ "CHYMOTRYPSIN_ML": 768452,
31
+ "DDG": 613208,
32
+ "DOMAINOME_FITNESS": 591671,
33
+ "DOMAINOME_FITNESS_STD": 591671,
34
+ "STABILIZING": 580091,
35
+ "REVERSIBILITY": 26618,
36
+ "TM": 13640,
37
+ "CM": 7134,
38
+ "M": 6910,
39
+ "DTM": 5995,
40
+ "STATE": 5362,
41
+ "DHVH": 4866,
42
+ "DH": 4632,
43
+ "DCP": 2923
44
+ },
45
+ "annotation_type_counts": {
46
+ "METHOD": 27552,
47
+ "PH": 27499,
48
+ "MEASURE": 27351,
49
+ "BUFFER": 27139,
50
+ "BUFFER_CONC": 25232,
51
+ "_PDB_CHAIN_MUTATION": 17064,
52
+ "EXP_TEMPERATURE": 13590,
53
+ "ION": 11599,
54
+ "ION_CONC": 11528
55
+ },
56
+ "feature_type_counts": {
57
+ "CONSERVATION": 5141973,
58
+ "BINDING_SITE": 17238,
59
+ "ACTIVE_SITE": 240
60
+ },
61
+ "mutation_event_counts": {
62
+ "deletions": 54296,
63
+ "insertions": 50613,
64
+ "substitutions": 5543778
65
+ },
66
+ "columns": [
67
+ "row_id",
68
+ "dataset_id",
69
+ "source_dataset",
70
+ "source_file",
71
+ "source_table",
72
+ "source_sha",
73
+ "row_index",
74
+ "split",
75
+ "subject_type",
76
+ "entry_id",
77
+ "sequence_id",
78
+ "target_sequence_id",
79
+ "source_sequence_length",
80
+ "target_sequence_length",
81
+ "protein_id",
82
+ "protein_name",
83
+ "organism",
84
+ "isoform",
85
+ "protein_ids",
86
+ "protein_names",
87
+ "organisms",
88
+ "isoforms",
89
+ "uniprot_accessions",
90
+ "interpro_accessions",
91
+ "ec_numbers",
92
+ "megascale_ids",
93
+ "other_references",
94
+ "mutations",
95
+ "substitutions",
96
+ "deletions",
97
+ "insertions",
98
+ "mutation_count",
99
+ "substitution_count",
100
+ "deletion_count",
101
+ "insertion_count",
102
+ "first_position",
103
+ "first_source_aa",
104
+ "first_target_aa",
105
+ "conservation",
106
+ "feature_types",
107
+ "pdb_ids",
108
+ "afdb_ids",
109
+ "structure_ids",
110
+ "structure_methods",
111
+ "structure_resolution_min",
112
+ "residue_positions",
113
+ "residue_chain_names",
114
+ "residue_secondary_structures",
115
+ "residue_in_pocket_any",
116
+ "residue_in_tunnel_any",
117
+ "residue_asa_mean",
118
+ "residue_bfactor_mean",
119
+ "experiment_id",
120
+ "experiment_dataset",
121
+ "ph",
122
+ "measure",
123
+ "method",
124
+ "buffer",
125
+ "buffer_conc",
126
+ "exp_temperature",
127
+ "ion",
128
+ "ion_conc",
129
+ "pdb_chain_mutation",
130
+ "tm",
131
+ "dtm",
132
+ "dg",
133
+ "dg_text",
134
+ "ddg",
135
+ "dh",
136
+ "dcp",
137
+ "dhvh",
138
+ "cm",
139
+ "m_value",
140
+ "trypsin_ml",
141
+ "chymotrypsin_ml",
142
+ "stabilizing",
143
+ "stabilizing_text",
144
+ "domainome_fitness",
145
+ "domainome_fitness_std",
146
+ "domainome_ddg",
147
+ "domainome_ddg_std",
148
+ "reversibility",
149
+ "state",
150
+ "measurement_types",
151
+ "measurement_datasets",
152
+ "annotation_types",
153
+ "publication_id",
154
+ "publication_type",
155
+ "publication_title",
156
+ "publication_year",
157
+ "publication_doi",
158
+ "publication_pmid",
159
+ "publication_journal",
160
+ "publication_url",
161
+ "publication_author_count",
162
+ "publication_authors",
163
+ "annotations_json",
164
+ "measurements_json",
165
+ "features_json"
166
+ ],
167
+ "files": {
168
+ "train": "data/train-00000-of-00001.parquet",
169
+ "test": "data/test-00000-of-00001.parquet"
170
+ }
171
+ }
scripts/prepare_fireprotdb_dataset.py ADDED
@@ -0,0 +1,656 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build a flat, viewer-friendly FireProtDB table."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import hashlib
8
+ import json
9
+ import math
10
+ import os
11
+ import shutil
12
+ import sys
13
+ from collections import Counter
14
+ from pathlib import Path
15
+ from typing import Any, Iterable
16
+
17
+ import pyarrow as pa
18
+ import pyarrow.parquet as pq
19
+ from huggingface_hub import HfApi, HfFileSystem, hf_hub_download
20
+
21
+ try:
22
+ import orjson
23
+ except ImportError: # pragma: no cover - optional speedup
24
+ orjson = None
25
+
26
+
27
+ SOURCE_TABLE = "tables/labeled_fireprotdb_fireprotdb_search_all.jsonl.jsonl"
28
+ COMMON_MEASUREMENTS = {
29
+ "TM": "tm",
30
+ "DTM": "dtm",
31
+ "DG": "dg",
32
+ "DDG": "ddg",
33
+ "DH": "dh",
34
+ "DCP": "dcp",
35
+ "DHVH": "dhvh",
36
+ "CM": "cm",
37
+ "M": "m_value",
38
+ "TRYPSIN_ML": "trypsin_ml",
39
+ "CHYMOTRYPSIN_ML": "chymotrypsin_ml",
40
+ "STABILIZING": "stabilizing",
41
+ "DOMAINOME_FITNESS": "domainome_fitness",
42
+ "DOMAINOME_FITNESS_STD": "domainome_fitness_std",
43
+ "DOMAINOME_DDG": "domainome_ddg",
44
+ "DOMAINOME_DDG_STD": "domainome_ddg_std",
45
+ }
46
+
47
+
48
+ SCHEMA = pa.schema(
49
+ [
50
+ pa.field("row_id", pa.string()),
51
+ pa.field("dataset_id", pa.string()),
52
+ pa.field("source_dataset", pa.string()),
53
+ pa.field("source_file", pa.string()),
54
+ pa.field("source_table", pa.string()),
55
+ pa.field("source_sha", pa.string()),
56
+ pa.field("row_index", pa.int64()),
57
+ pa.field("split", pa.string()),
58
+ pa.field("subject_type", pa.string()),
59
+ pa.field("entry_id", pa.int64()),
60
+ pa.field("sequence_id", pa.int64()),
61
+ pa.field("target_sequence_id", pa.int64()),
62
+ pa.field("source_sequence_length", pa.int64()),
63
+ pa.field("target_sequence_length", pa.int64()),
64
+ pa.field("protein_id", pa.int64()),
65
+ pa.field("protein_name", pa.string()),
66
+ pa.field("organism", pa.string()),
67
+ pa.field("isoform", pa.int64()),
68
+ pa.field("protein_ids", pa.string()),
69
+ pa.field("protein_names", pa.string()),
70
+ pa.field("organisms", pa.string()),
71
+ pa.field("isoforms", pa.string()),
72
+ pa.field("uniprot_accessions", pa.string()),
73
+ pa.field("interpro_accessions", pa.string()),
74
+ pa.field("ec_numbers", pa.string()),
75
+ pa.field("megascale_ids", pa.string()),
76
+ pa.field("other_references", pa.string()),
77
+ pa.field("mutations", pa.string()),
78
+ pa.field("substitutions", pa.string()),
79
+ pa.field("deletions", pa.string()),
80
+ pa.field("insertions", pa.string()),
81
+ pa.field("mutation_count", pa.int64()),
82
+ pa.field("substitution_count", pa.int64()),
83
+ pa.field("deletion_count", pa.int64()),
84
+ pa.field("insertion_count", pa.int64()),
85
+ pa.field("first_position", pa.int64()),
86
+ pa.field("first_source_aa", pa.string()),
87
+ pa.field("first_target_aa", pa.string()),
88
+ pa.field("conservation", pa.float64()),
89
+ pa.field("feature_types", pa.string()),
90
+ pa.field("pdb_ids", pa.string()),
91
+ pa.field("afdb_ids", pa.string()),
92
+ pa.field("structure_ids", pa.string()),
93
+ pa.field("structure_methods", pa.string()),
94
+ pa.field("structure_resolution_min", pa.float64()),
95
+ pa.field("residue_positions", pa.string()),
96
+ pa.field("residue_chain_names", pa.string()),
97
+ pa.field("residue_secondary_structures", pa.string()),
98
+ pa.field("residue_in_pocket_any", pa.bool_()),
99
+ pa.field("residue_in_tunnel_any", pa.bool_()),
100
+ pa.field("residue_asa_mean", pa.float64()),
101
+ pa.field("residue_bfactor_mean", pa.float64()),
102
+ pa.field("experiment_id", pa.int64()),
103
+ pa.field("experiment_dataset", pa.string()),
104
+ pa.field("ph", pa.float64()),
105
+ pa.field("measure", pa.string()),
106
+ pa.field("method", pa.string()),
107
+ pa.field("buffer", pa.string()),
108
+ pa.field("buffer_conc", pa.string()),
109
+ pa.field("exp_temperature", pa.float64()),
110
+ pa.field("ion", pa.string()),
111
+ pa.field("ion_conc", pa.string()),
112
+ pa.field("pdb_chain_mutation", pa.string()),
113
+ pa.field("tm", pa.float64()),
114
+ pa.field("dtm", pa.float64()),
115
+ pa.field("dg", pa.float64()),
116
+ pa.field("dg_text", pa.string()),
117
+ pa.field("ddg", pa.float64()),
118
+ pa.field("dh", pa.float64()),
119
+ pa.field("dcp", pa.float64()),
120
+ pa.field("dhvh", pa.float64()),
121
+ pa.field("cm", pa.float64()),
122
+ pa.field("m_value", pa.float64()),
123
+ pa.field("trypsin_ml", pa.float64()),
124
+ pa.field("chymotrypsin_ml", pa.float64()),
125
+ pa.field("stabilizing", pa.float64()),
126
+ pa.field("stabilizing_text", pa.string()),
127
+ pa.field("domainome_fitness", pa.float64()),
128
+ pa.field("domainome_fitness_std", pa.float64()),
129
+ pa.field("domainome_ddg", pa.float64()),
130
+ pa.field("domainome_ddg_std", pa.float64()),
131
+ pa.field("reversibility", pa.string()),
132
+ pa.field("state", pa.string()),
133
+ pa.field("measurement_types", pa.string()),
134
+ pa.field("measurement_datasets", pa.string()),
135
+ pa.field("annotation_types", pa.string()),
136
+ pa.field("publication_id", pa.string()),
137
+ pa.field("publication_type", pa.string()),
138
+ pa.field("publication_title", pa.string()),
139
+ pa.field("publication_year", pa.int64()),
140
+ pa.field("publication_doi", pa.string()),
141
+ pa.field("publication_pmid", pa.string()),
142
+ pa.field("publication_journal", pa.string()),
143
+ pa.field("publication_url", pa.string()),
144
+ pa.field("publication_author_count", pa.int64()),
145
+ pa.field("publication_authors", pa.string()),
146
+ pa.field("annotations_json", pa.string()),
147
+ pa.field("measurements_json", pa.string()),
148
+ pa.field("features_json", pa.string()),
149
+ ]
150
+ )
151
+
152
+
153
+ STRING_DEFAULTS = {field.name for field in SCHEMA if pa.types.is_string(field.type)}
154
+ INT_DEFAULTS = {field.name for field in SCHEMA if pa.types.is_int64(field.type)}
155
+ BOOL_DEFAULTS = {field.name for field in SCHEMA if pa.types.is_boolean(field.type)}
156
+
157
+
158
+ def load_token() -> str | None:
159
+ for key in ("HF_TOKEN", "HUGGINGFACE_HUB_TOKEN"):
160
+ value = os.environ.get(key)
161
+ if value:
162
+ return value
163
+ env_path = Path(".env")
164
+ if env_path.exists():
165
+ for line in env_path.read_text().splitlines():
166
+ stripped = line.strip()
167
+ if not stripped or stripped.startswith("#") or "=" not in stripped:
168
+ continue
169
+ key, value = stripped.split("=", 1)
170
+ if key.strip() in {"HF_TOKEN", "HUGGINGFACE_HUB_TOKEN"}:
171
+ value = value.strip().strip('"').strip("'")
172
+ if value:
173
+ return value
174
+ return None
175
+
176
+
177
+ def stable_bucket(value: str, buckets: int = 10) -> int:
178
+ digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:16]
179
+ return int(digest, 16) % buckets
180
+
181
+
182
+ def as_int(value: Any) -> int:
183
+ if value is None or value == "":
184
+ return -1
185
+ try:
186
+ return int(value)
187
+ except (TypeError, ValueError):
188
+ return -1
189
+
190
+
191
+ def as_float(value: Any) -> float | None:
192
+ if value is None or value == "":
193
+ return None
194
+ try:
195
+ numeric = float(value)
196
+ except (TypeError, ValueError):
197
+ return None
198
+ if math.isnan(numeric) or math.isinf(numeric):
199
+ return None
200
+ return numeric
201
+
202
+
203
+ def as_str(value: Any) -> str:
204
+ if value is None:
205
+ return ""
206
+ return str(value)
207
+
208
+
209
+ def compact_json(value: Any) -> str:
210
+ if not value:
211
+ return ""
212
+ if orjson is not None:
213
+ return orjson.dumps(value, option=orjson.OPT_SORT_KEYS).decode("utf-8")
214
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
215
+
216
+
217
+ def load_json_line(line: str) -> dict[str, Any]:
218
+ if orjson is not None:
219
+ return orjson.loads(line)
220
+ return json.loads(line)
221
+
222
+
223
+ def join_unique(values: Iterable[Any], sep: str = "|") -> str:
224
+ seen = set()
225
+ out = []
226
+ for value in values:
227
+ if value is None or value == "":
228
+ continue
229
+ text = str(value)
230
+ if text not in seen:
231
+ seen.add(text)
232
+ out.append(text)
233
+ return sep.join(out)
234
+
235
+
236
+ def first_value(values: list[Any]) -> Any:
237
+ return values[0] if values else None
238
+
239
+
240
+ def extract_subject(row: dict[str, Any]) -> tuple[str, dict[str, Any], dict[str, Any], dict[str, Any] | None]:
241
+ mutant = row.get("mutant")
242
+ if mutant:
243
+ return "mutant", mutant, mutant.get("sourceSequence") or {}, mutant.get("targetSequence")
244
+ sequence = row.get("sequence") or {}
245
+ return "sequence", sequence, sequence, None
246
+
247
+
248
+ def reference_groups(protein_links: list[dict[str, Any]]) -> dict[str, list[str]]:
249
+ grouped: dict[str, list[str]] = {
250
+ "UNIPROTKB": [],
251
+ "INTERPRO": [],
252
+ "EC_NUMBER": [],
253
+ "MEGASCALE": [],
254
+ "OTHER": [],
255
+ }
256
+ for link in protein_links:
257
+ protein = link.get("protein") or {}
258
+ for ref in protein.get("references") or []:
259
+ ref_type = as_str(ref.get("type"))
260
+ accession = as_str(ref.get("accession"))
261
+ if not accession:
262
+ continue
263
+ if ref_type in grouped:
264
+ grouped[ref_type].append(accession)
265
+ else:
266
+ grouped["OTHER"].append(f"{ref_type}:{accession}" if ref_type else accession)
267
+ return grouped
268
+
269
+
270
+ def mutation_strings(subject_type: str, subject: dict[str, Any]) -> dict[str, Any]:
271
+ if subject_type != "mutant":
272
+ return {
273
+ "mutations": "",
274
+ "substitutions": "",
275
+ "deletions": "",
276
+ "insertions": "",
277
+ "mutation_count": 0,
278
+ "substitution_count": 0,
279
+ "deletion_count": 0,
280
+ "insertion_count": 0,
281
+ "first_position": -1,
282
+ "first_source_aa": "",
283
+ "first_target_aa": "",
284
+ }
285
+
286
+ substitutions = subject.get("substitutions") or []
287
+ deletions = subject.get("deletions") or []
288
+ insertions = subject.get("insertions") or []
289
+
290
+ sub_strings = [
291
+ f"{as_str(item.get('sourceAa'))}{as_int(item.get('position'))}{as_str(item.get('targetAa'))}"
292
+ for item in substitutions
293
+ ]
294
+ del_strings = [f"del{as_str(item.get('aminoAcids'))}{as_int(item.get('position'))}" for item in deletions]
295
+ ins_strings = [f"ins{as_str(item.get('aminoAcids'))}{as_int(item.get('position'))}" for item in insertions]
296
+ all_mutations = sub_strings + del_strings + ins_strings
297
+
298
+ first_position = -1
299
+ first_source_aa = ""
300
+ first_target_aa = ""
301
+ if substitutions:
302
+ first = substitutions[0]
303
+ first_position = as_int(first.get("position"))
304
+ first_source_aa = as_str(first.get("sourceAa"))
305
+ first_target_aa = as_str(first.get("targetAa"))
306
+ elif deletions:
307
+ first = deletions[0]
308
+ first_position = as_int(first.get("position"))
309
+ first_source_aa = as_str(first.get("aminoAcids"))
310
+ first_target_aa = "-"
311
+ elif insertions:
312
+ first = insertions[0]
313
+ first_position = as_int(first.get("position"))
314
+ first_source_aa = "-"
315
+ first_target_aa = as_str(first.get("aminoAcids"))
316
+
317
+ return {
318
+ "mutations": join_unique(all_mutations),
319
+ "substitutions": join_unique(sub_strings),
320
+ "deletions": join_unique(del_strings),
321
+ "insertions": join_unique(ins_strings),
322
+ "mutation_count": len(all_mutations),
323
+ "substitution_count": len(substitutions),
324
+ "deletion_count": len(deletions),
325
+ "insertion_count": len(insertions),
326
+ "first_position": first_position,
327
+ "first_source_aa": first_source_aa,
328
+ "first_target_aa": first_target_aa,
329
+ }
330
+
331
+
332
+ def feature_values(features: list[dict[str, Any]]) -> dict[str, Any]:
333
+ conservation = None
334
+ types = []
335
+ for feature in features:
336
+ feature_type = as_str(feature.get("type"))
337
+ types.append(feature_type)
338
+ if feature_type == "CONSERVATION" and conservation is None:
339
+ conservation = as_float(feature.get("numValue"))
340
+ return {
341
+ "conservation": conservation,
342
+ "feature_types": join_unique(types),
343
+ "features_json": compact_json(features),
344
+ }
345
+
346
+
347
+ def structure_values(structures: list[dict[str, Any]]) -> dict[str, Any]:
348
+ residues = []
349
+ for structure in structures:
350
+ residues.extend(structure.get("residues") or [])
351
+ asa_values = [as_float(residue.get("asa")) for residue in residues]
352
+ bfactor_values = [as_float(residue.get("bFactor")) for residue in residues]
353
+ asa_values = [value for value in asa_values if value is not None]
354
+ bfactor_values = [value for value in bfactor_values if value is not None]
355
+ resolutions = [as_float(structure.get("resolution")) for structure in structures]
356
+ resolutions = [value for value in resolutions if value is not None]
357
+ afdb_ids = []
358
+ for structure in structures:
359
+ afdb = structure.get("afdb")
360
+ if isinstance(afdb, dict):
361
+ afdb_ids.append(afdb.get("accession") or afdb.get("id"))
362
+ else:
363
+ afdb_ids.append(afdb)
364
+ return {
365
+ "pdb_ids": join_unique(structure.get("wwpdb") for structure in structures),
366
+ "afdb_ids": join_unique(afdb_ids),
367
+ "structure_ids": join_unique(structure.get("id") for structure in structures),
368
+ "structure_methods": join_unique(structure.get("method") for structure in structures),
369
+ "structure_resolution_min": min(resolutions) if resolutions else None,
370
+ "residue_positions": join_unique(residue.get("seqPosition") for residue in residues),
371
+ "residue_chain_names": join_unique(residue.get("chainName") for residue in residues),
372
+ "residue_secondary_structures": join_unique(residue.get("secondaryStructure") for residue in residues),
373
+ "residue_in_pocket_any": any(bool(residue.get("inPocket")) for residue in residues),
374
+ "residue_in_tunnel_any": any(bool(residue.get("inTunnel")) for residue in residues),
375
+ "residue_asa_mean": sum(asa_values) / len(asa_values) if asa_values else None,
376
+ "residue_bfactor_mean": sum(bfactor_values) / len(bfactor_values) if bfactor_values else None,
377
+ }
378
+
379
+
380
+ def annotation_map(annotations: list[dict[str, Any]]) -> dict[str, list[Any]]:
381
+ values: dict[str, list[Any]] = {}
382
+ for annotation in annotations:
383
+ annotation_type = as_str(annotation.get("type"))
384
+ if not annotation_type:
385
+ continue
386
+ value = annotation.get("strValue")
387
+ if value is None:
388
+ value = annotation.get("numValue")
389
+ values.setdefault(annotation_type, []).append(value)
390
+ return values
391
+
392
+
393
+ def measurement_map(measurements: list[dict[str, Any]]) -> tuple[dict[str, list[Any]], list[str]]:
394
+ values: dict[str, list[Any]] = {}
395
+ datasets = []
396
+ for measurement in measurements:
397
+ measurement_type = as_str(measurement.get("type"))
398
+ if not measurement_type:
399
+ continue
400
+ value = measurement.get("numValue")
401
+ if value is None:
402
+ value = measurement.get("strValue")
403
+ values.setdefault(measurement_type, []).append(value)
404
+ datasets.extend(measurement.get("datasets") or [])
405
+ return values, datasets
406
+
407
+
408
+ def flatten_record(obj: dict[str, Any], source_sha: str) -> dict[str, Any]:
409
+ row = obj.get("row") or {}
410
+ subject_type, subject, source_sequence, target_sequence = extract_subject(row)
411
+ protein_links = source_sequence.get("proteinLinks") or []
412
+ first_link = protein_links[0] if protein_links else {}
413
+ first_protein = first_link.get("protein") or {}
414
+ refs = reference_groups(protein_links)
415
+ experiment = subject.get("experiment") or {}
416
+ publication = experiment.get("publication") or {}
417
+ annotations = experiment.get("annotations") or []
418
+ measurements = experiment.get("measurements") or []
419
+ features = subject.get("features") or []
420
+ structures = subject.get("structures") or []
421
+ ann = annotation_map(annotations)
422
+ meas, measurement_datasets = measurement_map(measurements)
423
+
424
+ flat = {
425
+ "row_id": f"fireprotdb:{as_int(obj.get('row_index'))}",
426
+ "dataset_id": as_str(obj.get("dataset_id") or "fireprotdb"),
427
+ "source_dataset": "LiteFold/FireProtDB",
428
+ "source_file": as_str(obj.get("source_file")),
429
+ "source_table": SOURCE_TABLE,
430
+ "source_sha": source_sha,
431
+ "row_index": as_int(obj.get("row_index")),
432
+ "split": "test" if stable_bucket(f"fireprotdb:{as_int(obj.get('row_index'))}") == 0 else "train",
433
+ "subject_type": subject_type,
434
+ "entry_id": as_int(subject.get("id")),
435
+ "sequence_id": as_int(source_sequence.get("id")),
436
+ "target_sequence_id": as_int((target_sequence or {}).get("id")),
437
+ "source_sequence_length": as_int(source_sequence.get("length")),
438
+ "target_sequence_length": as_int((target_sequence or {}).get("length")),
439
+ "protein_id": as_int(first_protein.get("id")),
440
+ "protein_name": as_str(first_protein.get("name")),
441
+ "organism": as_str(first_protein.get("organism")),
442
+ "isoform": as_int(first_link.get("isoform")),
443
+ "protein_ids": join_unique((link.get("protein") or {}).get("id") for link in protein_links),
444
+ "protein_names": join_unique((link.get("protein") or {}).get("name") for link in protein_links),
445
+ "organisms": join_unique((link.get("protein") or {}).get("organism") for link in protein_links),
446
+ "isoforms": join_unique(link.get("isoform") for link in protein_links),
447
+ "uniprot_accessions": join_unique(refs["UNIPROTKB"]),
448
+ "interpro_accessions": join_unique(refs["INTERPRO"]),
449
+ "ec_numbers": join_unique(refs["EC_NUMBER"]),
450
+ "megascale_ids": join_unique(refs["MEGASCALE"]),
451
+ "other_references": join_unique(refs["OTHER"]),
452
+ "experiment_id": as_int(experiment.get("id")),
453
+ "experiment_dataset": as_str(experiment.get("dataset")),
454
+ "ph": as_float(first_value(ann.get("PH", []))),
455
+ "measure": join_unique(ann.get("MEASURE", [])),
456
+ "method": join_unique(ann.get("METHOD", [])),
457
+ "buffer": join_unique(ann.get("BUFFER", [])),
458
+ "buffer_conc": join_unique(ann.get("BUFFER_CONC", [])),
459
+ "exp_temperature": as_float(first_value(ann.get("EXP_TEMPERATURE", []))),
460
+ "ion": join_unique(ann.get("ION", [])),
461
+ "ion_conc": join_unique(ann.get("ION_CONC", [])),
462
+ "pdb_chain_mutation": join_unique(ann.get("_PDB_CHAIN_MUTATION", [])),
463
+ "dg_text": join_unique(value for value in meas.get("DG", []) if as_float(value) is None),
464
+ "stabilizing_text": join_unique(value for value in meas.get("STABILIZING", []) if as_float(value) is None),
465
+ "reversibility": join_unique(meas.get("REVERSIBILITY", [])),
466
+ "state": join_unique(meas.get("STATE", [])),
467
+ "measurement_types": join_unique(meas.keys()),
468
+ "measurement_datasets": join_unique(measurement_datasets),
469
+ "annotation_types": join_unique(ann.keys()),
470
+ "publication_id": as_str(publication.get("id")),
471
+ "publication_type": as_str(publication.get("type")),
472
+ "publication_title": as_str(publication.get("title")),
473
+ "publication_year": as_int(publication.get("year")),
474
+ "publication_doi": as_str(publication.get("doi")),
475
+ "publication_pmid": as_str(publication.get("pmid")),
476
+ "publication_journal": as_str(publication.get("journal")),
477
+ "publication_url": as_str(publication.get("url")),
478
+ "publication_author_count": len(publication.get("authors") or []),
479
+ "publication_authors": join_unique(author.get("name") for author in publication.get("authors") or []),
480
+ "annotations_json": compact_json(annotations),
481
+ "measurements_json": compact_json(measurements),
482
+ }
483
+ for measurement_type, column in COMMON_MEASUREMENTS.items():
484
+ flat[column] = as_float(first_value(meas.get(measurement_type, [])))
485
+ flat.update(mutation_strings(subject_type, subject))
486
+ flat.update(feature_values(features))
487
+ flat.update(structure_values(structures))
488
+ return normalize_flat(flat)
489
+
490
+
491
+ def normalize_flat(flat: dict[str, Any]) -> dict[str, Any]:
492
+ normalized = {}
493
+ for field in SCHEMA:
494
+ value = flat.get(field.name)
495
+ if value is None:
496
+ if field.name in STRING_DEFAULTS:
497
+ value = ""
498
+ elif field.name in INT_DEFAULTS:
499
+ value = -1
500
+ elif field.name in BOOL_DEFAULTS:
501
+ value = False
502
+ normalized[field.name] = value
503
+ return normalized
504
+
505
+
506
+ def write_chunk(writer: pq.ParquetWriter | None, path: Path, rows: list[dict[str, Any]]) -> pq.ParquetWriter | None:
507
+ if not rows:
508
+ return writer
509
+ table = pa.Table.from_pylist(rows, schema=SCHEMA)
510
+ if writer is None:
511
+ writer = pq.ParquetWriter(path, SCHEMA, compression="zstd", use_dictionary=True)
512
+ writer.write_table(table)
513
+ return writer
514
+
515
+
516
+ def iter_source(repo_id: str, token: str | None, input_file: Path | None) -> Iterable[str]:
517
+ if input_file:
518
+ with input_file.open("r", encoding="utf-8") as handle:
519
+ yield from handle
520
+ return
521
+ fs = HfFileSystem(token=token)
522
+ with fs.open(f"datasets/{repo_id}/{SOURCE_TABLE}", "rt") as handle:
523
+ yield from handle
524
+
525
+
526
+ def build_dataset(repo_id: str, raw_dir: Path, out_dir: Path, input_file: Path | None, chunk_size: int) -> dict[str, Any]:
527
+ token = load_token()
528
+ api = HfApi(token=token)
529
+ info = api.dataset_info(repo_id, files_metadata=True)
530
+ raw_dir.mkdir(parents=True, exist_ok=True)
531
+ manifest_path = Path(
532
+ hf_hub_download(repo_id=repo_id, repo_type="dataset", filename="_MANIFEST.json", local_dir=raw_dir, token=token)
533
+ )
534
+ manifest = json.loads(manifest_path.read_text())
535
+ if out_dir.exists():
536
+ shutil.rmtree(out_dir)
537
+ data_dir = out_dir / "data"
538
+ metadata_dir = out_dir / "metadata"
539
+ data_dir.mkdir(parents=True, exist_ok=True)
540
+ metadata_dir.mkdir(parents=True, exist_ok=True)
541
+
542
+ train_path = data_dir / "train-00000-of-00001.parquet"
543
+ test_path = data_dir / "test-00000-of-00001.parquet"
544
+ train_writer = None
545
+ test_writer = None
546
+ train_rows: list[dict[str, Any]] = []
547
+ test_rows: list[dict[str, Any]] = []
548
+
549
+ total_rows = 0
550
+ split_counts: Counter[str] = Counter()
551
+ subject_counts: Counter[str] = Counter()
552
+ experiment_dataset_counts: Counter[str] = Counter()
553
+ measurement_type_counts: Counter[str] = Counter()
554
+ annotation_type_counts: Counter[str] = Counter()
555
+ feature_type_counts: Counter[str] = Counter()
556
+ mutation_event_counts: Counter[str] = Counter()
557
+
558
+ try:
559
+ for line in iter_source(repo_id, token, input_file):
560
+ obj = load_json_line(line)
561
+ row = flatten_record(obj, info.sha)
562
+ total_rows += 1
563
+ split_counts[row["split"]] += 1
564
+ subject_counts[row["subject_type"]] += 1
565
+ if row["experiment_dataset"]:
566
+ experiment_dataset_counts[row["experiment_dataset"]] += 1
567
+ for item in row["measurement_types"].split("|"):
568
+ if item:
569
+ measurement_type_counts[item] += 1
570
+ for item in row["annotation_types"].split("|"):
571
+ if item:
572
+ annotation_type_counts[item] += 1
573
+ for item in row["feature_types"].split("|"):
574
+ if item:
575
+ feature_type_counts[item] += 1
576
+ mutation_event_counts["substitutions"] += row["substitution_count"]
577
+ mutation_event_counts["deletions"] += row["deletion_count"]
578
+ mutation_event_counts["insertions"] += row["insertion_count"]
579
+ if row["split"] == "test":
580
+ test_rows.append(row)
581
+ else:
582
+ train_rows.append(row)
583
+ if len(train_rows) >= chunk_size:
584
+ train_writer = write_chunk(train_writer, train_path, train_rows)
585
+ train_rows.clear()
586
+ if len(test_rows) >= chunk_size:
587
+ test_writer = write_chunk(test_writer, test_path, test_rows)
588
+ test_rows.clear()
589
+ if total_rows % 100000 == 0:
590
+ print(f"processed {total_rows:,} rows", file=sys.stderr, flush=True)
591
+ train_writer = write_chunk(train_writer, train_path, train_rows)
592
+ test_writer = write_chunk(test_writer, test_path, test_rows)
593
+ finally:
594
+ if train_writer is not None:
595
+ train_writer.close()
596
+ if test_writer is not None:
597
+ test_writer.close()
598
+
599
+ expected_rows = int(manifest.get("total_rows") or 0)
600
+ if expected_rows and total_rows != expected_rows:
601
+ raise RuntimeError(f"Expected {expected_rows} rows from manifest, wrote {total_rows}")
602
+
603
+ source_table_meta = manifest["tables"][0]
604
+ new_manifest = {
605
+ "dataset_id": "fireprotdb",
606
+ "source_repo": repo_id,
607
+ "source_sha": info.sha,
608
+ "source_table": SOURCE_TABLE,
609
+ "format": "flat parquet table rows",
610
+ "total_rows": total_rows,
611
+ "split_counts": dict(sorted(split_counts.items())),
612
+ "split_strategy": "deterministic sha256('fireprotdb:{row_index}') % 10; bucket 0 is test, buckets 1-9 are train",
613
+ "columns": [field.name for field in SCHEMA],
614
+ "source_manifest": manifest,
615
+ }
616
+ (out_dir / "_MANIFEST.json").write_text(json.dumps(new_manifest, indent=2) + "\n", encoding="utf-8")
617
+ summary = {
618
+ "source": repo_id,
619
+ "source_sha": info.sha,
620
+ "source_table": SOURCE_TABLE,
621
+ "source_table_rows": int(source_table_meta["rows"]),
622
+ "source_table_bytes": int(source_table_meta["bytes"]),
623
+ "viewer_table_scope": "flat FireProtDB experiment/mutation rows",
624
+ "data_format": "parquet",
625
+ "rows": total_rows,
626
+ "splits": dict(sorted(split_counts.items())),
627
+ "subject_type_counts": dict(sorted(subject_counts.items())),
628
+ "experiment_dataset_counts": dict(experiment_dataset_counts.most_common()),
629
+ "measurement_type_counts": dict(measurement_type_counts.most_common()),
630
+ "annotation_type_counts": dict(annotation_type_counts.most_common()),
631
+ "feature_type_counts": dict(feature_type_counts.most_common()),
632
+ "mutation_event_counts": dict(sorted(mutation_event_counts.items())),
633
+ "columns": [field.name for field in SCHEMA],
634
+ "files": {
635
+ "train": str(train_path.relative_to(out_dir)),
636
+ "test": str(test_path.relative_to(out_dir)),
637
+ },
638
+ }
639
+ (out_dir / "dataset_summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
640
+ return summary
641
+
642
+
643
+ def main() -> None:
644
+ parser = argparse.ArgumentParser()
645
+ parser.add_argument("--repo-id", default="LiteFold/FireProtDB")
646
+ parser.add_argument("--raw-dir", type=Path, default=Path("LiteFold_FireProtDB_raw"))
647
+ parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_FireProtDB_processed"))
648
+ parser.add_argument("--input-file", type=Path)
649
+ parser.add_argument("--chunk-size", type=int, default=50000)
650
+ args = parser.parse_args()
651
+ summary = build_dataset(args.repo_id, args.raw_dir, args.out_dir, args.input_file, args.chunk_size)
652
+ print(json.dumps(summary, indent=2))
653
+
654
+
655
+ if __name__ == "__main__":
656
+ main()