Add normalized Parquet train/test FLIP2 table
Browse filesFiles changed (11)
- README.md+66-72
- data/test-00000-of-00001.parquetAdded+3
- data/train-00000-of-00005.parquetAdded+3
- data/train-00001-of-00005.parquetAdded+3
- data/train-00002-of-00005.parquetAdded+3
- data/train-00003-of-00005.parquetAdded+3
- data/train-00004-of-00005.parquetAdded+3
- dataset_summary.jsonAdded+48
- metadata/column_mapping.parquetAdded+3
- metadata/source_tables.parquetAdded+3
- scripts/prepare_wrapped_jsonl_dataset.pyAdded+416
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899---license: otherpretty_name: FLIP v2size_categories:- 100K<n<1Mtask_categories:- otherlanguage:- entags:- biology- proteins- fitness- benchmark- flip- jsonl---# FLIP v2FLIP v2 benchmark splits for protein engineering tasks (amylase, hydrolase, etc.), normalized to newline-delimited JSON.Processed and uploaded by the [MegaData](https://github.com/) post-download pipeline(internal repo). Original source: <https://github.com/J-SNACKKB/FLIP>.## Statistics| | ||---|---|| Table files | 16 || Total rows | 890,356 || Total bytes | 440.98 MiB (462,398,539) |## Tables| Table | Rows | Bytes ||---|---:|---:|| `data_unpacked_labeled_flip2_amylase_by_mutation.csv.jsonl` | 3,706 | 2.18 MiB || `data_unpacked_labeled_flip2_amylase_close_to_far.csv.jsonl` | 3,706 | 2.18 MiB || `data_unpacked_labeled_flip2_amylase_far_to_close.csv.jsonl` | 3,706 | 2.18 MiB || `data_unpacked_labeled_flip2_amylase_one_to_many.csv.jsonl` | 3,706 | 2.18 MiB || `data_unpacked_labeled_flip2_hydro_low_to_high.csv.jsonl` | 24,935 | 6.02 MiB || `data_unpacked_labeled_flip2_hydro_three_to_many.csv.jsonl` | 24,935 | 6.06 MiB || `data_unpacked_labeled_flip2_hydro_to_P01053.csv.jsonl` | 24,935 | 5.98 MiB || `data_unpacked_labeled_flip2_hydro_to_P06241.csv.jsonl` | 24,935 | 5.97 MiB || `data_unpacked_labeled_flip2_hydro_to_P0A9X9.csv.jsonl` | 24,935 | 5.98 MiB || `data_unpacked_labeled_flip2_ired_two_to_many.csv.jsonl` | 8,586 | 3.95 MiB || `data_unpacked_labeled_flip2_nucb_two_to_many.csv.jsonl` | 55,759 | 16.85 MiB || `data_unpacked_labeled_flip2_pdz3_single_to_double.csv.jsonl` | 734 | 213.50 KiB || `data_unpacked_labeled_flip2_rhomax_by_wild_type.csv.jsonl` | 884 | 389.02 KiB || `data_unpacked_labeled_flip2_trpb_by_position.csv.jsonl` | 228,298 | 126.97 MiB || `data_unpacked_labeled_flip2_trpb_one_to_many.csv.jsonl` | 228,298 | 126.94 MiB || `data_unpacked_labeled_flip2_trpb_two_to_many.csv.jsonl` | 228,298 | 126.95 MiB |## Layout```.├── _MANIFEST.json # aggregate manifest (per-table counts)└── tables/<source_slug>.jsonl # normalized rows (one JSON object per line)```Each line in a `tables/*.jsonl` file is a JSON object with at least`dataset_id`, `row` (the raw upstream row), `row_index`, and `source_file`fields, so every row carries its upstream provenance.## Loading```bashhf download LiteFold/FLIP2 --repo-type dataset --local-dir ./flip2```Programmatic streaming:```pythonimport jsonfrom pathlib import Pathfrom huggingface_hub import snapshot_downloadlocal = snapshot_download(repo_id="LiteFold/FLIP2", repo_type="dataset")for jsonl in sorted(Path(local, "tables").glob("*.jsonl")):with jsonl.open() as f:for line in f:row = json.loads(line)... # row["row"] is the upstream record```## LicenseSee upstream FLIP repository for licensing.## Citation> Dallago C, et al. FLIP: Benchmark tasks in fitness landscape inference for proteins. NeurIPS Datasets and Benchmarks, 2021.## ProvenanceBuilt from the local manifest entry `flip2` of `manifests/atlas_download_plan.json`.Pipeline source: `megadata-post normalize --dataset flip2 --tables-only`.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293---pretty_name: FLIP2 Protein Benchmark Taskslicense: othertags:- biology- protein- benchmark- protein-engineering- flip- flip2- parquetconfigs:- config_name: defaultdata_files:- split: trainpath: data/train-*.parquet- split: testpath: data/test-*.parquet---# LiteFold/FLIP2This repository now includes a Dataset Viewer-friendly Parquet version of the LiteFold FLIP2 tables. The default `load_dataset()` configuration reads the normalized Parquet files in `data/`.The normalized table contains 890,356 rows from 16 source tables. The original wrapped JSONL source tables remain available in the repository under `tables/`.## Splits- `train`: 801,710 rows- `test`: 88,646 rowsRows are assigned with a deterministic hash split: `sha256(record_id) % 10`, where bucket `0` is test and buckets `1-9` are train.## ColumnsThe table includes common browsing and modeling columns:- `record_id`: stable SHA-256 row identifier- `dataset_id`, `source_file`, `source_table`, `source_row_index`: source provenance- `task_name`, `subtask_name`, `assay_name`: FLIP2 task metadata- `sequence`, `sequence_length`, `target`, `score_value`, `label`: normalized convenience fields- `split_bucket`: deterministic split bucketThe original FLIP2 fields are preserved as snake_case string columns: `raw_sequence`, `set`, `raw_target`, and `validation`. See `metadata/column_mapping.parquet` for the original field-name mapping and `metadata/source_tables.parquet` for per-table row counts.## Usage```pythonfrom datasets import load_datasetds = load_dataset("LiteFold/FLIP2")print(ds)print(ds["train"][0])```Load only the common columns:```pythonfrom datasets import load_datasetcols = ["record_id", "task_name", "subtask_name", "sequence", "score_value", "label"]train = load_dataset("LiteFold/FLIP2", split="train", columns=cols)```Filter to a task:```pythonfrom datasets import load_datasettrain = load_dataset("LiteFold/FLIP2", split="train")trpb = train.filter(lambda row: row["task_name"] == "trpb")```Metadata tables can be loaded directly:```pythonfrom datasets import load_datasetsource_tables = load_dataset("parquet",data_files="hf://datasets/LiteFold/FLIP2/metadata/source_tables.parquet",split="train",)column_mapping = load_dataset("parquet",data_files="hf://datasets/LiteFold/FLIP2/metadata/column_mapping.parquet",split="train",)```## RebuildThe normalization script used for this upload is included at `scripts/prepare_wrapped_jsonl_dataset.py`.
123version https://git-lfs.github.com/spec/v1oid sha256:c3e4201ca13592606e5811d1f104905785576d93f2e90823e0c36ff9a58902easize 6345516123version https://git-lfs.github.com/spec/v1oid sha256:e22bb1703d76bdab971e8befa11f3343ead1619020a3815fbf15c7229aa5830bsize 12373803123version https://git-lfs.github.com/spec/v1oid sha256:457cc347c6154b089cf9d0f5b5378f3239bab2ad3201ce227c131b267d11c851size 13782811123version https://git-lfs.github.com/spec/v1oid sha256:ec866a27afd26d807545390b4c8dc5c024c7ce5710f4f1f1e9c1dc59fd09ea2asize 13774715123version https://git-lfs.github.com/spec/v1oid sha256:ca71f92bf77e62428f2a3688222cbebf4b19a98cffe886f97d85530dc5aa3bf1size 13785411123version https://git-lfs.github.com/spec/v1oid sha256:dff9c5cebb1c9a7a6960a3f4eb5ca3061b0c625e876fdc178381fda9ab581e9csize 135341123456789101112131415161718192021222324252627282930313233343536373839404142434445464748{ "source": "LiteFold/FLIP2", "mode": "flip2", "source_table_rows": 16, "entry_rows": 890356, "raw_field_count": 4, "splits": { "train": 801710, "test": 88646 }, "split_strategy": "deterministic sha256(record_id) % 10; bucket 0 is test, buckets 1-9 are train", "table_group_counts": { "hydro": 5, "amylase": 4, "trpb": 3, "ired": 1, "nucb": 1, "pdz3": 1, "rhomax": 1 }, "columns": [ "record_id", "dataset_id", "source_file", "source_table", "source_row_index", "table_group", "task_name", "subtask_name", "entity_type", "assay_name", "sequence", "sequence_length", "mutation", "target", "score_value", "label", "split_bucket", "raw_sequence", "set", "raw_target", "validation" ], "metadata_tables": [ "metadata/source_tables.parquet", "metadata/column_mapping.parquet" ]}123version https://git-lfs.github.com/spec/v1oid sha256:589d18aa0209b05ca2bdffd222684ac99038e329973296f3da40ac454bdf9bd9size 1798123version https://git-lfs.github.com/spec/v1oid sha256:b93cdbb6a3e0d0c6d4ffa9c80fcace128d2f94a05be95ced59e8a8166ffcb8f7size 4464123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416#!/usr/bin/env python3"""Build viewer-friendly Parquet splits for LiteFold wrapped JSONL table repos."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport osimport reimport shutilfrom collections import Counterfrom pathlib import Pathfrom typing import Any, Iterable
import pyarrow as paimport pyarrow.parquet as pqimport pandas as pdfrom huggingface_hub import HfApi, hf_hub_download
BASE_COLUMNS = [ "record_id", "dataset_id", "source_file", "source_table", "source_row_index", "table_group", "task_name", "subtask_name", "entity_type", "assay_name", "sequence", "sequence_length", "mutation", "target", "score_value", "label", "split_bucket",]
def load_token() -> str | None: for key in ("HF_TOKEN", "HUGGINGFACE_HUB_TOKEN"): value = os.environ.get(key) if value: return value env_path = Path(".env") if env_path.exists(): for line in env_path.read_text().splitlines(): stripped = line.strip() if not stripped or stripped.startswith("#") or "=" not in stripped: continue key, value = stripped.split("=", 1) if key.strip() in {"HF_TOKEN", "HUGGINGFACE_HUB_TOKEN"}: value = value.strip().strip('"').strip("'") if value: return value return None
def stable_bucket(value: str, buckets: int = 10) -> int: digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:16] return int(digest, 16) % buckets
def normalize_name(name: str) -> str: normalized = re.sub(r"[^0-9A-Za-z]+", "_", name).strip("_").lower() if not normalized: normalized = "field" if normalized[0].isdigit(): normalized = f"x_{normalized}" return normalized
def unique_names(keys: Iterable[str]) -> dict[str, str]: mapping: dict[str, str] = {} used: Counter[str] = Counter() for key in sorted(keys): base = normalize_name(key) candidate = base if candidate in BASE_COLUMNS: candidate = f"raw_{candidate}" used[candidate] += 1 if used[candidate] > 1: candidate = f"{candidate}_{used[candidate]}" mapping[key] = candidate return mapping
def scalar_string(value: Any) -> str | None: if value is None or value == "": return None if isinstance(value, (dict, list)): return json.dumps(value, sort_keys=True, ensure_ascii=False) return str(value)
def parse_float(value: Any) -> float | None: if value is None or value == "": return None try: return float(value) except (TypeError, ValueError): return None
def first_present(row: dict[str, Any], keys: list[str]) -> Any: for key in keys: value = row.get(key) if value is not None and value != "": return value return None
def table_path_from_manifest(output_file: str) -> str: prefix = "data/processed/" if output_file.startswith(prefix): parts = output_file.split("/tables/", 1) if len(parts) == 2: return "tables/" + parts[1] return output_file
def get_table_files(repo_id: str, mode: str, raw_dir: Path, token: str | None) -> tuple[list[str], list[dict[str, Any]]]: manifest_path = Path( hf_hub_download(repo_id=repo_id, repo_type="dataset", filename="_MANIFEST.json", local_dir=raw_dir, token=token) ) manifest = json.loads(manifest_path.read_text()) manifest_tables = manifest.get("tables") or [] if manifest_tables: table_paths = [table_path_from_manifest(item["output_file"]) for item in manifest_tables] else: api = HfApi(token=token) info = api.dataset_info(repo_id, files_metadata=True) table_paths = [s.rfilename for s in info.siblings or [] if s.rfilename.startswith("tables/")] manifest_tables = []
if mode == "cycpeptmpdb": table_paths = [ path for path in table_paths if path.endswith("_Peptide_All.csv.jsonl") or path.endswith("_Monomer_All.csv.jsonl") ] if mode == "proteingym": table_paths = [path for path in table_paths if ".ipynb_checkpoints" not in path] return sorted(set(table_paths)), manifest_tables
def classify(mode: str, source_file: str, source_table: str) -> dict[str, Any]: source_parts = Path(source_file).parts basename = Path(source_file).name.removesuffix(".csv") if mode == "proteingym": lower = source_file.lower() if "indels" in lower: table_group = "indels" elif "substitutions" in lower: table_group = "substitutions" elif "clinical" in lower: table_group = "clinical" else: table_group = "other" if "raw_dms" in lower: task_name = "DMS" elif "clinical" in lower: task_name = "clinical" else: task_name = None return { "table_group": table_group, "task_name": task_name, "subtask_name": None, "entity_type": "variant", "assay_name": basename, } if mode == "flip2": task_name = source_parts[-2] if len(source_parts) >= 2 else None return { "table_group": "benchmark", "task_name": task_name, "subtask_name": basename, "entity_type": "sequence", "assay_name": f"{task_name}/{basename}" if task_name else basename, } if mode == "cycpeptmpdb": entity_type = "peptide" if "Peptide" in basename else "monomer" if "Monomer" in basename else None return { "table_group": "all", "task_name": "CycPeptMPDB", "subtask_name": basename, "entity_type": entity_type, "assay_name": basename, } return {"table_group": None, "task_name": None, "subtask_name": None, "entity_type": None, "assay_name": basename}
def derived_values(mode: str, wrapper: dict[str, Any]) -> dict[str, Any]: row = wrapper.get("row") or {} source_file = wrapper.get("source_file") or "" source_table = wrapper.get("_source_table") or "" source_row_index = wrapper.get("row_index") record_seed = f"{source_file}|{source_row_index}|{json.dumps(row, sort_keys=True, ensure_ascii=False)}" record_id = hashlib.sha256(record_seed.encode("utf-8")).hexdigest() derived = { "record_id": record_id, "dataset_id": wrapper.get("dataset_id"), "source_file": source_file, "source_table": source_table, "source_row_index": int(source_row_index) if source_row_index is not None else None, "split_bucket": stable_bucket(record_id), } derived.update(classify(mode, source_file, source_table))
sequence = first_present( row, [ "mutated_sequence", "mutant_sequence", "sequence", "Sequence", "aa_seq", "aa_seq_full", "wildtype_sequence", "WT_sequence", ], ) target = first_present(row, ["target", "DMS_score", "fitness", "score", "Permeability", "deltaG", "dG_ML"]) score_value = None for key in ["target", "DMS_score", "fitness", "score", "Permeability", "deltaG", "dG_ML", "ddG_ML", "Caco2", "PAMPA", "MDCK", "RRCK"]: score_value = parse_float(row.get(key)) if score_value is not None: break mutation = first_present(row, ["mutant", "mutation", "mutations", "name", "mut_class", "ID", "id"]) label = first_present(row, ["DMS_score_bin", "label", "set", "validation", "class", "mut_type", "Molecule_Shape"])
derived.update( { "sequence": scalar_string(sequence), "sequence_length": len(str(sequence)) if sequence is not None else None, "mutation": scalar_string(mutation), "target": scalar_string(target), "score_value": score_value, "label": scalar_string(label), } ) return derived
def iter_wrappers(path: Path, source_table: str) -> Iterable[dict[str, Any]]: with path.open("r", encoding="utf-8", errors="replace") as handle: for line in handle: if not line.strip(): continue item = json.loads(line) item["_source_table"] = source_table yield item
def download_tables(repo_id: str, table_paths: list[str], raw_dir: Path, token: str | None) -> list[Path]: paths = [] for index, table_path in enumerate(table_paths, start=1): local = Path(hf_hub_download(repo_id=repo_id, repo_type="dataset", filename=table_path, local_dir=raw_dir, token=token)) paths.append(local) if index == 1 or index % 25 == 0 or index == len(table_paths): print(f"downloaded {index}/{len(table_paths)} {table_path}", flush=True) return paths
def write_split_shards( out_dir: Path, rows_iter: Iterable[dict[str, Any]], schema: pa.Schema, chunk_rows: int,) -> dict[str, int]: data_dir = out_dir / "data" data_dir.mkdir(parents=True, exist_ok=True) buffers: dict[str, list[dict[str, Any]]] = {"train": [], "test": []} counts = {"train": 0, "test": 0} shard_counts = {"train": 0, "test": 0}
def flush(split: str) -> None: if not buffers[split]: return shard = shard_counts[split] path = data_dir / f"{split}-{shard:05d}-of-XXXXX.parquet" table = pa.Table.from_pylist(buffers[split], schema=schema) pq.write_table(table, path, compression="zstd") counts[split] += len(buffers[split]) shard_counts[split] += 1 buffers[split].clear()
for row in rows_iter: split = "test" if row["split_bucket"] == 0 else "train" buffers[split].append(row) if len(buffers[split]) >= chunk_rows: flush(split) flush("train") flush("test")
for split in ["train", "test"]: total = shard_counts[split] for path in sorted(data_dir.glob(f"{split}-*-of-XXXXX.parquet")): new_name = path.name.replace("of-XXXXX", f"of-{total:05d}") path.rename(path.with_name(new_name)) return counts
def build_dataset(repo_id: str, mode: str, raw_dir: Path, out_dir: Path, chunk_rows: int) -> dict[str, Any]: token = load_token() raw_dir.mkdir(parents=True, exist_ok=True) table_paths, manifest_tables = get_table_files(repo_id, mode, raw_dir, token) local_paths = download_tables(repo_id, table_paths, raw_dir, token)
raw_keys: set[str] = set() table_stats: list[dict[str, Any]] = [] total_rows = 0 for source_table, local_path in zip(table_paths, local_paths): rows = 0 dataset_id = None source_file = None for wrapper in iter_wrappers(local_path, source_table): row = wrapper.get("row") or {} raw_keys.update(row.keys()) rows += 1 dataset_id = wrapper.get("dataset_id") source_file = wrapper.get("source_file") total_rows += rows table_stats.append( { "source_table": source_table, "source_file": source_file, "dataset_id": dataset_id, "rows": rows, "size_bytes": local_path.stat().st_size, } ) print(f"scanned {source_table}: {rows} rows", flush=True)
raw_mapping = unique_names(raw_keys) raw_columns = [raw_mapping[key] for key in sorted(raw_mapping)] schema_fields = [ pa.field("record_id", pa.string()), pa.field("dataset_id", pa.string()), pa.field("source_file", pa.string()), pa.field("source_table", pa.string()), pa.field("source_row_index", pa.int64()), pa.field("table_group", pa.string()), pa.field("task_name", pa.string()), pa.field("subtask_name", pa.string()), pa.field("entity_type", pa.string()), pa.field("assay_name", pa.string()), pa.field("sequence", pa.string()), pa.field("sequence_length", pa.int64()), pa.field("mutation", pa.string()), pa.field("target", pa.string()), pa.field("score_value", pa.float64()), pa.field("label", pa.string()), pa.field("split_bucket", pa.int64()), ] + [pa.field(column, pa.string()) for column in raw_columns] schema = pa.schema(schema_fields)
if out_dir.exists(): shutil.rmtree(out_dir) out_dir.mkdir(parents=True, exist_ok=True)
def row_iter() -> Iterable[dict[str, Any]]: emitted = 0 for source_table, local_path in zip(table_paths, local_paths): for wrapper in iter_wrappers(local_path, source_table): raw = wrapper.get("row") or {} row = {column: None for column in BASE_COLUMNS + raw_columns} row.update(derived_values(mode, wrapper)) for original_key, column in raw_mapping.items(): row[column] = scalar_string(raw.get(original_key)) emitted += 1 if emitted % 250000 == 0: print(f"prepared {emitted}/{total_rows} rows", flush=True) yield row
split_counts = write_split_shards(out_dir, row_iter(), schema, chunk_rows)
metadata_dir = out_dir / "metadata" metadata_dir.mkdir(parents=True, exist_ok=True) pd.DataFrame.from_records(table_stats).to_parquet(metadata_dir / "source_tables.parquet", index=False, compression="zstd") pd.DataFrame.from_records( [{"raw_key": key, "column": raw_mapping[key]} for key in sorted(raw_mapping)] ).to_parquet(metadata_dir / "column_mapping.parquet", index=False, compression="zstd")
summary = { "source": repo_id, "mode": mode, "source_table_rows": len(table_stats), "entry_rows": int(total_rows), "raw_field_count": len(raw_columns), "splits": split_counts, "split_strategy": "deterministic sha256(record_id) % 10; bucket 0 is test, buckets 1-9 are train", "table_group_counts": dict(Counter(item["source_file"].split("/")[-2] if item["source_file"] and "/" in item["source_file"] else "unknown" for item in table_stats).most_common()), "columns": BASE_COLUMNS + raw_columns, "metadata_tables": ["metadata/source_tables.parquet", "metadata/column_mapping.parquet"], } (out_dir / "dataset_summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") return summary
def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--repo-id", required=True) parser.add_argument("--mode", required=True, choices=["proteingym", "flip2", "cycpeptmpdb"]) parser.add_argument("--raw-dir", type=Path, required=True) parser.add_argument("--out-dir", type=Path, required=True) parser.add_argument("--chunk-rows", type=int, default=200000) args = parser.parse_args() summary = build_dataset(args.repo_id, args.mode, args.raw_dir, args.out_dir, args.chunk_rows) print(json.dumps(summary, indent=2))
if __name__ == "__main__": main()README.md+66-72
data/test-00000-of-00001.parquetAdded+3
data/train-00000-of-00005.parquetAdded+3
data/train-00001-of-00005.parquetAdded+3
data/train-00002-of-00005.parquetAdded+3
data/train-00003-of-00005.parquetAdded+3
data/train-00004-of-00005.parquetAdded+3
dataset_summary.jsonAdded+48
metadata/column_mapping.parquetAdded+3
metadata/source_tables.parquetAdded+3
scripts/prepare_wrapped_jsonl_dataset.pyAdded+416