IDP-Pathogenicity-Model / scripts /build_clinvar_mito_dataset.py.py
HarriziSaad's picture
Upload 14 files
f07511a verified
# -*- coding: utf-8 -*-
"""Untitled17.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1GwdSjrwh3f6QCzOa8KHr_XkWy0KmZvdV
"""
import pandas as pd
import numpy as np
import gzip
import re
from pathlib import Path
from tqdm import tqdm
PATHS = {
'data_raw': BASE_PATH / 'data' / 'raw',
'data_processed': BASE_PATH / 'data' / 'processed',
'checkpoints': BASE_PATH / 'models' / 'checkpoints',
}
for path in PATHS.values():
path.mkdir(parents=True, exist_ok=True)
AA_3TO1 = {
'Ala': 'A', 'Arg': 'R', 'Asn': 'N', 'Asp': 'D', 'Cys': 'C',
'Glu': 'E', 'Gln': 'Q', 'Gly': 'G', 'His': 'H', 'Ile': 'I',
'Leu': 'L', 'Lys': 'K', 'Met': 'M', 'Phe': 'F', 'Pro': 'P',
'Ser': 'S', 'Thr': 'T', 'Trp': 'W', 'Tyr': 'Y', 'Val': 'V'
}
clinvar_file = Path("/content/drive/MyDrive/clinvar/variation_summary.txt.gz")
if clinvar_file.exists():
print(f" Fichier: {clinvar_file}")
with gzip.open(clinvar_file, "rt") as f:
df_clinvar_raw = pd.read_csv(f, sep="\t", low_memory=False)
print(f" Lignes totales: {len(df_clinvar_raw):,}")
print(f" Colonnes: {df_clinvar_raw.columns.tolist()[:10]}...")
df_clinvar = df_clinvar_raw[
df_clinvar_raw["GeneSymbol"].notna() &
df_clinvar_raw["ProteinChange"].notna() &
df_clinvar_raw["ClinicalSignificance"].str.contains("Pathogenic|Benign", case=False, na=False)
].copy()
print(f" Après filtre basique: {len(df_clinvar):,}")
MITO_KEYWORDS = [
"mitochondrial", "Leigh", "MELAS", "MERRF", "NARP", "LHON",
"optic atrophy", "OXPHOS", "complex I", "complex II", "complex III",
"complex IV", "complex V", "cardiomyopathy", "encephalopathy",
"myopathy", "aminoacyl-tRNA", "respiratory chain"
]
pattern = "|".join(MITO_KEYWORDS)
MITO_GENES = [
'OPA1', 'MFN1', 'MFN2', 'DNM1L', 'AFG3L2', 'SPG7',
'SURF1', 'SCO1', 'SCO2', 'COX10', 'COX15', 'COX6B1',
'NDUFAF1', 'NDUFAF2', 'NDUFAF3', 'NDUFAF4', 'NDUFAF5', 'NDUFAF6',
'NUBPL', 'ACAD9', 'TIMMDC1', 'FOXRED1',
'CHCHD10', 'CHCHD2', 'TIMM50', 'DNAJC19', 'AGK',
'HARS2', 'IARS2', 'LARS2', 'MARS2', 'RARS2', 'VARS2', 'YARS2',
'DARS2', 'SARS2', 'TARS2', 'AARS2', 'EARS2', 'FARS2', 'NARS2', 'PARS2',
'POLG', 'POLG2', 'TWNK', 'RRM2B', 'MPV17', 'DGUOK', 'TK2',
'SUCLA2', 'SUCLG1', 'FBXL4', 'SLC25A4', 'SLC25A3',
'RMND1', 'GTPBP3', 'MTO1', 'TRMU', 'TSFM', 'GFM1', 'C12orf65',
'LRPPRC', 'TACO1', 'MTFMT', 'ELAC2',
'BCS1L', 'TTC19', 'UQCRQ', 'UQCRB', 'UQCRC2',
'COA5', 'COA6', 'COA7', 'PET100', 'PET117',
'TMEM70', 'ATP5F1A', 'ATP5F1D', 'ATP5F1E',
]
df_mito = df_clinvar[
df_clinvar["PhenotypeList"].str.contains(pattern, case=False, na=False) |
df_clinvar["GeneSymbol"].str.upper().isin([g.upper() for g in MITO_GENES])
].copy()
print(f" Variants mitochondriaux: {len(df_mito):,}")
else:
print(" non trouvé")
print(" → Téléchargez depuis: https://ftp.ncbi.nlm.nih.gov/pub/clinvar/tab_delimited/")
df_mito = pd.DataFrame()
records = []
if len(df_mito) > 0:
for _, row in tqdm(df_mito.iterrows(), total=len(df_mito), desc="Parsing"):
protein_change = str(row.get("ProteinChange", ""))
match = re.search(r'p\.([A-Z])(\d+)([A-Z])', protein_change)
if not match:
match = re.search(r'p\.([A-Z][a-z]{2})(\d+)([A-Z][a-z]{2})', protein_change)
if match:
wt_3, pos, mut_3 = match.groups()
wt = AA_3TO1.get(wt_3)
mut = AA_3TO1.get(mut_3)
if wt and mut:
match = type('Match', (), {'groups': lambda: (wt, pos, mut)})()
else:
match = None
if not match:
continue
wt, pos, mut = match.groups()
clin_sig = str(row.get("ClinicalSignificance", "")).lower()
if "pathogenic" in clin_sig and "benign" not in clin_sig:
label = 1
elif "benign" in clin_sig and "pathogenic" not in clin_sig:
label = 0
else:
continue
review = str(row.get("ReviewStatus", ""))
records.append({
"gene_symbol": str(row["GeneSymbol"]).upper(),
"position": int(pos) - 1,
"wt_aa": wt,
"mut_aa": mut,
"label": label,
"source": "ClinVar_local",
"review_status": review,
"clinical_significance": row.get("ClinicalSignificance", ""),
"phenotype": str(row.get("PhenotypeList", ""))[:100],
})
df_clinvar_parsed = pd.DataFrame(records)
print(f"\n ✓ Variants parsés: {len(df_clinvar_parsed)}")
if len(df_clinvar_parsed) > 0:
print(f"\n Labels:")
print(df_clinvar_parsed["label"].value_counts())
print(f"\n Top 15 gènes:")
print(df_clinvar_parsed["gene_symbol"].value_counts().head(15))
print(f"\n Review status:")
print(df_clinvar_parsed["review_status"].value_counts().head(5))
uniprot_file = PATHS['data_raw'] / 'uniprot_mito_extended.parquet'
proteins_file = PATHS['data_processed'] / 'proteins_targeted.parquet'
seq_dict = {}
gene_to_acc = {}
acc_to_info = {}
if uniprot_file.exists():
df_uniprot = pd.read_parquet(uniprot_file)
for _, row in df_uniprot.iterrows():
acc = row['accession']
seq = row['sequence']
gene = str(row['gene_name']).upper() if row['gene_name'] else ''
seq_dict[acc] = seq
acc_to_info[acc] = {
'cysteine_fraction': row.get('cysteine_fraction', seq.count('C')/len(seq) if seq else 0),
'mito_region': row.get('mito_region', 'Unknown'),
}
if gene:
gene_to_acc[gene] = acc
gene_to_acc[gene.replace('-', '')] = acc
print(f" Protéines UniProt: {len(df_uniprot)}")
if proteins_file.exists():
df_proteins = pd.read_parquet(proteins_file)
for _, row in df_proteins.iterrows():
acc = row['accession']
seq = row['sequence']
gene = row['gene_symbol'].upper()
if acc not in seq_dict:
seq_dict[acc] = seq
gene_to_acc[gene] = acc
print(f" Protéines : {len(df_proteins)}")
print(f" séquences: {len(seq_dict)}")
print(f" Gènes : {len(gene_to_acc)}")
validated = []
not_found_genes = set()
seq_mismatch = 0
for _, row in tqdm(df_clinvar_parsed.iterrows(), total=len(df_clinvar_parsed), desc="Validation"):
gene = row['gene_symbol']
acc = gene_to_acc.get(gene)
if not acc:
for variant in [gene.replace('-', ''), gene.split('-')[0], gene.split('_')[0]]:
if variant in gene_to_acc:
acc = gene_to_acc[variant]
break
if not acc:
not_found_genes.add(gene)
continue
seq = seq_dict.get(acc, '')
if not seq:
continue
pos = row['position']
wt = row['wt_aa']
mut = row['mut_aa']
if 0 <= pos < len(seq):
if seq[pos] == wt:
info = acc_to_info.get(acc, {})
validated.append({
'uniprot_acc': acc,
'gene_symbol': gene,
'position': pos,
'wt_aa': wt,
'mut_aa': mut,
'label': row['label'],
'source': row['source'],
'review_status': row.get('review_status', ''),
'clinical_significance': row.get('clinical_significance', ''),
'phenotype': row.get('phenotype', ''),
'cysteine_fraction': info.get('cysteine_fraction', 0),
'mito_region': info.get('mito_region', 'Unknown'),
})
else:
seq_mismatch += 1
df_validated = pd.DataFrame(validated)
if len(df_validated) > 0:
print(f"\n Labels validés:")
print(df_validated["label"].value_counts())
benign_file = PATHS['data_processed'] / 'mutations_master.parquet'
if benign_file.exists():
df_benign_existing = pd.read_parquet(benign_file)
print(f" Socle bénin existant: {len(df_benign_existing)}")
# Préparer pour fusion
df_benign_existing = df_benign_existing.copy()
df_benign_existing['label'] = 0
df_benign_existing['source'] = df_benign_existing.get('label_source', 'gnomAD_UniProt')
else:
df_benign_existing = pd.DataFrame()
datasets = []
if len(df_validated) > 0:
datasets.append(df_validated)
print(f" + ClinVar: {len(df_validated)}")
if len(df_benign_existing) > 0:
cols = ['uniprot_acc', 'position', 'wt_aa', 'mut_aa', 'label', 'source']
cols_exist = [c for c in cols if c in df_benign_existing.columns]
df_benign_clean = df_benign_existing[cols_exist].copy()
if 'gene_symbol' not in df_benign_clean.columns and 'gene_symbol' in df_benign_existing.columns:
df_benign_clean['gene_symbol'] = df_benign_existing['gene_symbol']
datasets.append(df_benign_clean)
print(f" + Bénins existants: {len(df_benign_clean)}")
if datasets:
df_final = pd.concat(datasets, ignore_index=True)
df_final['mutation_key'] = (
df_final['uniprot_acc'].astype(str) + '_' +
df_final['position'].astype(str) + '_' +
df_final['mut_aa'].astype(str)
)
df_final['priority'] = df_final['source'].apply(lambda x: 0 if 'ClinVar' in str(x) else 1)
df_final = df_final.sort_values('priority')
df_final = df_final.drop_duplicates(subset='mutation_key', keep='first')
df_final = df_final.drop(columns=['priority', 'mutation_key'])
print(f"\n ✓ Dataset final: {len(df_final)}")
else:
df_final = pd.DataFrame()
print(" Aucun dataset à fusionner")
if len(df_final) > 0:
df_final['n_terminal'] = df_final['position'] < 50
df_final['cysteine_gained'] = df_final['mut_aa'] == 'C'
df_final['cysteine_lost'] = df_final['wt_aa'] == 'C'
df_final['mutation_id'] = df_final['wt_aa'] + (df_final['position'] + 1).astype(str) + df_final['mut_aa']
df_final['ros_axis'] = (
df_final['cysteine_lost'] |
df_final['cysteine_gained'] |
(df_final.get('cysteine_fraction', 0) > 0.03) |
(df_final.get('mito_region', '') == 'IMS')
)
df_final['import_axis'] = df_final['n_terminal']
df_final.to_parquet(PATHS['data_processed'] / 'mutations_dataset_final.parquet')
df_final.to_csv(PATHS['data_processed'] / 'mutations_dataset_final.tsv', sep='\t', index=False)
if len(df_clinvar_parsed) > 0:
df_clinvar_parsed.to_parquet(PATHS['data_raw'] / 'clinvar_mito_parsed.parquet')