Download scripts/prepare_alphafolddb_dataset.py from LiteFold/AlphaFoldDB: direct link, hf CLI and curl.
- Browser
- Download file 8.76 kB
-
https://huggingface.co/datasets/LiteFold/AlphaFoldDB/resolve/main/scripts/prepare_alphafolddb_dataset.py
- Command line
-
hf download hf://datasets/LiteFold/AlphaFoldDB/scripts/prepare_alphafolddb_dataset.py
-
curl -L -o prepare_alphafolddb_dataset.py https://huggingface.co/datasets/LiteFold/AlphaFoldDB/resolve/main/scripts/prepare_alphafolddb_dataset.py
8.76 kB
| #!/usr/bin/env python3 | |
| """Build viewer-friendly Parquet splits for LiteFold/AlphaFoldDB.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import re | |
| import shutil | |
| from pathlib import Path | |
| import duckdb | |
| import pandas as pd | |
| import pyarrow.parquet as pq | |
| CSV_COLUMNS_SQL = ( | |
| "{" | |
| "'uniprot_accession':'VARCHAR'," | |
| "'first_residue_index':'BIGINT'," | |
| "'last_residue_index':'BIGINT'," | |
| "'alphafold_id':'VARCHAR'," | |
| "'latest_version':'BIGINT'" | |
| "}" | |
| ) | |
| def sql_string(path: Path) -> str: | |
| return "'" + path.as_posix().replace("'", "''") + "'" | |
| def entry_source_sql(accession_csv: Path) -> str: | |
| source = ( | |
| f"read_csv({sql_string(accession_csv)}, " | |
| f"header=false, columns={CSV_COLUMNS_SQL}, sample_size=100000, " | |
| f"strict_mode=false, parallel=false)" | |
| ) | |
| return f""" | |
| SELECT | |
| uniprot_accession, | |
| alphafold_id, | |
| latest_version, | |
| first_residue_index, | |
| last_residue_index, | |
| sequence_length, | |
| fragment_number, | |
| coalesce(fragment_number > 1, false) AS is_fragmented_prediction, | |
| split_bucket | |
| FROM ( | |
| SELECT | |
| uniprot_accession, | |
| alphafold_id, | |
| latest_version::UTINYINT AS latest_version, | |
| first_residue_index::INTEGER AS first_residue_index, | |
| last_residue_index::INTEGER AS last_residue_index, | |
| (last_residue_index - first_residue_index + 1)::INTEGER AS sequence_length, | |
| try_cast(nullif(regexp_extract(alphafold_id, '-F([0-9]+)$', 1), '') AS INTEGER) AS fragment_number, | |
| (hash(uniprot_accession) % 10)::UTINYINT AS split_bucket | |
| FROM {source} | |
| ) | |
| """ | |
| def copy_split( | |
| con: duckdb.DuckDBPyConnection, | |
| base_sql: str, | |
| split: str, | |
| condition: str, | |
| split_dir: Path, | |
| target_file_size: str, | |
| row_group_size: int, | |
| ) -> None: | |
| split_dir.mkdir(parents=True, exist_ok=True) | |
| copy_sql = f""" | |
| COPY ( | |
| SELECT * | |
| FROM ({base_sql}) | |
| WHERE {condition} | |
| ) | |
| TO {sql_string(split_dir)} | |
| ( | |
| FORMAT PARQUET, | |
| COMPRESSION ZSTD, | |
| ROW_GROUP_SIZE {row_group_size}, | |
| FILE_SIZE_BYTES {sql_string(Path(target_file_size))} | |
| ) | |
| """ | |
| con.execute(copy_sql) | |
| files = sorted( | |
| split_dir.glob("data_*.parquet"), | |
| key=lambda path: int(re.search(r"data_(\d+)\.parquet$", path.name).group(1)), | |
| ) | |
| total = len(files) | |
| for index, path in enumerate(files): | |
| path.rename(split_dir / f"{split}-{index:05d}-of-{total:05d}.parquet") | |
| def write_archive_metadata(raw_dir: Path, out_dir: Path) -> dict: | |
| metadata_path = raw_dir / "download_metadata.json" | |
| if not metadata_path.exists(): | |
| return {} | |
| records = json.loads(metadata_path.read_text(encoding="utf-8")) | |
| df = pd.DataFrame.from_records(records) | |
| if df.empty: | |
| return {} | |
| for column in [ | |
| "archive_name", | |
| "species", | |
| "common_name", | |
| "reference_proteome", | |
| "label", | |
| "type", | |
| ]: | |
| if column not in df.columns: | |
| df[column] = None | |
| if "latin_common_name" not in df.columns: | |
| df["latin_common_name"] = None | |
| df["archive_path"] = "latest/" + df["archive_name"] | |
| df["size_gb"] = df["size_bytes"].astype("float64") / 1_000_000_000 | |
| ordered_columns = [ | |
| "archive_name", | |
| "archive_path", | |
| "type", | |
| "species", | |
| "common_name", | |
| "latin_common_name", | |
| "reference_proteome", | |
| "label", | |
| "num_predicted_structures", | |
| "size_bytes", | |
| "size_gb", | |
| ] | |
| df = df[ordered_columns] | |
| metadata_dir = out_dir / "metadata" | |
| metadata_dir.mkdir(parents=True, exist_ok=True) | |
| df.to_parquet(metadata_dir / "archive_metadata.parquet", index=False, compression="zstd") | |
| return { | |
| "archive_rows": int(len(df)), | |
| "archive_types": df["type"].value_counts(dropna=False).to_dict(), | |
| "archive_predicted_structures": int(df["num_predicted_structures"].sum()), | |
| "archive_size_bytes": int(df["size_bytes"].sum()), | |
| } | |
| def parquet_row_count(paths: list[Path]) -> int: | |
| return sum(pq.ParquetFile(path).metadata.num_rows for path in paths) | |
| def build_dataset(raw_dir: Path, out_dir: Path, target_file_size: str, row_group_size: int) -> dict: | |
| accession_csv = raw_dir / "accession_ids.csv" | |
| if not accession_csv.exists(): | |
| raise FileNotFoundError(f"Missing {accession_csv}") | |
| data_dir = out_dir / "data" | |
| if data_dir.exists(): | |
| shutil.rmtree(data_dir) | |
| data_dir.mkdir(parents=True, exist_ok=True) | |
| con = duckdb.connect() | |
| con.execute("SET preserve_insertion_order=false") | |
| con.execute("PRAGMA disable_progress_bar") | |
| base_sql = entry_source_sql(accession_csv) | |
| copy_split( | |
| con, | |
| base_sql, | |
| "train", | |
| "split_bucket <> 0", | |
| data_dir / "train", | |
| target_file_size, | |
| row_group_size, | |
| ) | |
| copy_split( | |
| con, | |
| base_sql, | |
| "test", | |
| "split_bucket = 0", | |
| data_dir / "test", | |
| target_file_size, | |
| row_group_size, | |
| ) | |
| archive_summary = write_archive_metadata(raw_dir, out_dir) | |
| train_files = sorted((data_dir / "train").glob("*.parquet")) | |
| test_files = sorted((data_dir / "test").glob("*.parquet")) | |
| split_counts = { | |
| "train": parquet_row_count(train_files), | |
| "test": parquet_row_count(test_files), | |
| } | |
| parquet_glob = sql_string(data_dir / "*" / "*.parquet") | |
| stats_row = con.execute( | |
| f""" | |
| SELECT | |
| count(*)::UBIGINT AS total_rows, | |
| min(sequence_length)::INTEGER AS min_sequence_length, | |
| approx_quantile(sequence_length, 0.5)::INTEGER AS median_sequence_length, | |
| avg(sequence_length)::DOUBLE AS mean_sequence_length, | |
| max(sequence_length)::INTEGER AS max_sequence_length, | |
| sum(CASE WHEN is_fragmented_prediction THEN 1 ELSE 0 END)::UBIGINT AS fragmented_predictions, | |
| sum(CASE WHEN fragment_number IS NULL THEN 1 ELSE 0 END)::UBIGINT AS rows_without_fragment_number, | |
| min(latest_version)::UTINYINT AS min_latest_version, | |
| max(latest_version)::UTINYINT AS max_latest_version | |
| FROM read_parquet({parquet_glob}) | |
| """ | |
| ).fetchone() | |
| version_counts = { | |
| str(version): int(count) | |
| for version, count in con.execute( | |
| f""" | |
| SELECT latest_version, count(*) AS row_count | |
| FROM read_parquet({parquet_glob}) | |
| GROUP BY 1 | |
| ORDER BY 1 | |
| """ | |
| ).fetchall() | |
| } | |
| summary = { | |
| "source": "LiteFold/AlphaFoldDB", | |
| "table_source_file": "accession_ids.csv", | |
| "split_strategy": "deterministic hash(uniprot_accession) % 10; bucket 0 is test, buckets 1-9 are train", | |
| "splits": { | |
| "train": split_counts.get("train", 0), | |
| "test": split_counts.get("test", 0), | |
| }, | |
| "total_rows": int(stats_row[0]), | |
| "sequence_length": { | |
| "min": int(stats_row[1]), | |
| "median_approx": int(stats_row[2]), | |
| "mean": float(stats_row[3]), | |
| "max": int(stats_row[4]), | |
| }, | |
| "fragmented_predictions": int(stats_row[5]), | |
| "rows_without_fragment_number": int(stats_row[6]), | |
| "latest_version": { | |
| "min": int(stats_row[7]), | |
| "max": int(stats_row[8]), | |
| "counts": version_counts, | |
| }, | |
| "parquet_files": { | |
| "train": len(train_files), | |
| "test": len(test_files), | |
| }, | |
| "columns": [ | |
| "uniprot_accession", | |
| "alphafold_id", | |
| "latest_version", | |
| "first_residue_index", | |
| "last_residue_index", | |
| "sequence_length", | |
| "fragment_number", | |
| "is_fragmented_prediction", | |
| "split_bucket", | |
| ], | |
| "archive_metadata": archive_summary, | |
| } | |
| (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("--raw-dir", type=Path, default=Path("LiteFold_AlphaFoldDB_raw")) | |
| parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_AlphaFoldDB_processed")) | |
| parser.add_argument("--target-file-size", default="256MB") | |
| parser.add_argument("--row-group-size", type=int, default=1_000_000) | |
| args = parser.parse_args() | |
| summary = build_dataset(args.raw_dir, args.out_dir, args.target_file_size, args.row_group_size) | |
| print(json.dumps(summary, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |