|
|
|
|
|
""" |
|
|
Create disjoint splits from drug_rna_cds_sampled_11 dataset. |
|
|
|
|
|
Creates three datasets: |
|
|
1. drug_rna_cds_disjoint (fully disjoint if possible) |
|
|
2. drug_rna_cds_disjoint_rna (RNA-disjoint) |
|
|
3. drug_rna_cds_disjoint_compound (compound-disjoint) |
|
|
""" |
|
|
|
|
|
import pandas as pd |
|
|
import numpy as np |
|
|
from pathlib import Path |
|
|
from collections import defaultdict |
|
|
import argparse |
|
|
|
|
|
|
|
|
def analyze_disjoint_feasibility(df): |
|
|
"""Analyze if fully disjoint split is feasible.""" |
|
|
print("=" * 80) |
|
|
print("ANALYZING DISJOINT SPLIT FEASIBILITY") |
|
|
print("=" * 80) |
|
|
|
|
|
n_compounds = df['SMILES'].nunique() |
|
|
n_rnas = df['RNA_seq'].nunique() |
|
|
n_samples = len(df) |
|
|
|
|
|
print(f"\nDataset statistics:") |
|
|
print(f" Total samples: {n_samples:,}") |
|
|
print(f" Unique compounds: {n_compounds:,}") |
|
|
print(f" Unique RNAs: {n_rnas:,}") |
|
|
|
|
|
|
|
|
pairs = df.groupby(['SMILES', 'RNA_seq']).size().reset_index(name='count') |
|
|
print(f" Unique (compound, RNA) pairs: {len(pairs):,}") |
|
|
|
|
|
|
|
|
samples_per_compound = df.groupby('SMILES').size() |
|
|
samples_per_rna = df.groupby('RNA_seq').size() |
|
|
|
|
|
print(f"\n Samples per compound: mean={samples_per_compound.mean():.1f}, median={samples_per_compound.median():.1f}") |
|
|
print(f" Samples per RNA: mean={samples_per_rna.mean():.1f}, median={samples_per_rna.median():.1f}") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
min_samples_needed = int(0.15 * n_samples) |
|
|
|
|
|
print(f"\n Minimum samples needed for test (15%): {min_samples_needed:,}") |
|
|
|
|
|
|
|
|
n_compounds_test = int(0.15 * n_compounds) |
|
|
n_rnas_test = int(0.15 * n_rnas) |
|
|
|
|
|
print(f" If we allocate 15% of compounds: {n_compounds_test} compounds") |
|
|
print(f" If we allocate 15% of RNAs: {n_rnas_test} RNAs") |
|
|
print(f" Max possible samples (all pairs): {n_compounds_test * n_rnas_test:,}") |
|
|
|
|
|
|
|
|
compound_to_rnas = df.groupby('SMILES')['RNA_seq'].apply(set).to_dict() |
|
|
rna_to_compounds = df.groupby('RNA_seq')['SMILES'].apply(set).to_dict() |
|
|
|
|
|
|
|
|
avg_rnas_per_compound = df.groupby('SMILES')['RNA_seq'].nunique().mean() |
|
|
avg_compounds_per_rna = df.groupby('RNA_seq')['SMILES'].nunique().mean() |
|
|
|
|
|
print(f"\n Connectivity:") |
|
|
print(f" Avg RNAs per compound: {avg_rnas_per_compound:.1f}") |
|
|
print(f" Avg compounds per RNA: {avg_compounds_per_rna:.1f}") |
|
|
|
|
|
|
|
|
fully_disjoint_feasible = (n_compounds_test * n_rnas_test >= min_samples_needed) |
|
|
|
|
|
print(f"\n Fully disjoint split feasible: {'YES' if fully_disjoint_feasible else 'NO'}") |
|
|
|
|
|
return fully_disjoint_feasible |
|
|
|
|
|
|
|
|
def create_fully_disjoint_split(df, train_ratio=0.7, val_ratio=0.15, seed=42): |
|
|
"""Create fully disjoint split (compounds AND RNAs don't overlap).""" |
|
|
print("\n" + "=" * 80) |
|
|
print("CREATING FULLY DISJOINT SPLIT") |
|
|
print("=" * 80) |
|
|
|
|
|
np.random.seed(seed) |
|
|
|
|
|
|
|
|
compounds = df['SMILES'].unique() |
|
|
rnas = df['RNA_seq'].unique() |
|
|
|
|
|
|
|
|
np.random.shuffle(compounds) |
|
|
np.random.shuffle(rnas) |
|
|
|
|
|
|
|
|
n_compounds = len(compounds) |
|
|
n_train_comp = int(train_ratio * n_compounds) |
|
|
n_val_comp = int(val_ratio * n_compounds) |
|
|
|
|
|
train_compounds = set(compounds[:n_train_comp]) |
|
|
val_compounds = set(compounds[n_train_comp:n_train_comp + n_val_comp]) |
|
|
test_compounds = set(compounds[n_train_comp + n_val_comp:]) |
|
|
|
|
|
|
|
|
n_rnas = len(rnas) |
|
|
n_train_rna = int(train_ratio * n_rnas) |
|
|
n_val_rna = int(val_ratio * n_rnas) |
|
|
|
|
|
train_rnas = set(rnas[:n_train_rna]) |
|
|
val_rnas = set(rnas[n_train_rna:n_train_rna + n_val_rna]) |
|
|
test_rnas = set(rnas[n_train_rna + n_val_rna:]) |
|
|
|
|
|
|
|
|
train_df = df[(df['SMILES'].isin(train_compounds)) & (df['RNA_seq'].isin(train_rnas))].copy() |
|
|
val_df = df[(df['SMILES'].isin(val_compounds)) & (df['RNA_seq'].isin(val_rnas))].copy() |
|
|
test_df = df[(df['SMILES'].isin(test_compounds)) & (df['RNA_seq'].isin(test_rnas))].copy() |
|
|
|
|
|
print(f"\n Allocated:") |
|
|
print(f" Train: {len(train_compounds)} compounds, {len(train_rnas)} RNAs → {len(train_df)} samples") |
|
|
print(f" Val: {len(val_compounds)} compounds, {len(val_rnas)} RNAs → {len(val_df)} samples") |
|
|
print(f" Test: {len(test_compounds)} compounds, {len(test_rnas)} RNAs → {len(test_df)} samples") |
|
|
|
|
|
total_samples = len(train_df) + len(val_df) + len(test_df) |
|
|
print(f"\n Total samples retained: {total_samples:,} / {len(df):,} ({100*total_samples/len(df):.1f}%)") |
|
|
|
|
|
if total_samples < 0.5 * len(df): |
|
|
print(f"\n ⚠️ Warning: Lost {100*(1-total_samples/len(df)):.1f}% of samples") |
|
|
print(f" Fully disjoint split may not be practical for this dataset") |
|
|
return None |
|
|
|
|
|
return train_df, val_df, test_df |
|
|
|
|
|
|
|
|
def create_rna_disjoint_split(df, train_ratio=0.7, val_ratio=0.15, seed=42): |
|
|
"""Create RNA-disjoint split (RNAs don't overlap across splits).""" |
|
|
print("\n" + "=" * 80) |
|
|
print("CREATING RNA-DISJOINT SPLIT (Target: 70:15:15)") |
|
|
print("=" * 80) |
|
|
|
|
|
np.random.seed(seed) |
|
|
|
|
|
|
|
|
rna_counts = df.groupby('RNA_seq').size().reset_index(name='count') |
|
|
rna_counts = rna_counts.sample(frac=1, random_state=seed).reset_index(drop=True) |
|
|
|
|
|
|
|
|
total_samples = len(df) |
|
|
target_train = int(train_ratio * total_samples) |
|
|
target_val = int(val_ratio * total_samples) |
|
|
target_test = total_samples - target_train - target_val |
|
|
|
|
|
print(f"\n Target sample distribution:") |
|
|
print(f" Train: {target_train:,} ({train_ratio*100:.0f}%)") |
|
|
print(f" Val: {target_val:,} ({val_ratio*100:.0f}%)") |
|
|
print(f" Test: {target_test:,} ({(1-train_ratio-val_ratio)*100:.0f}%)") |
|
|
|
|
|
|
|
|
train_rnas = [] |
|
|
val_rnas = [] |
|
|
test_rnas = [] |
|
|
|
|
|
train_count = 0 |
|
|
val_count = 0 |
|
|
test_count = 0 |
|
|
|
|
|
for _, row in rna_counts.iterrows(): |
|
|
rna = row['RNA_seq'] |
|
|
count = row['count'] |
|
|
|
|
|
|
|
|
train_deficit = target_train - train_count |
|
|
val_deficit = target_val - val_count |
|
|
test_deficit = target_test - test_count |
|
|
|
|
|
if train_deficit >= val_deficit and train_deficit >= test_deficit: |
|
|
train_rnas.append(rna) |
|
|
train_count += count |
|
|
elif val_deficit >= test_deficit: |
|
|
val_rnas.append(rna) |
|
|
val_count += count |
|
|
else: |
|
|
test_rnas.append(rna) |
|
|
test_count += count |
|
|
|
|
|
train_rnas = set(train_rnas) |
|
|
val_rnas = set(val_rnas) |
|
|
test_rnas = set(test_rnas) |
|
|
|
|
|
|
|
|
train_df = df[df['RNA_seq'].isin(train_rnas)].copy() |
|
|
val_df = df[df['RNA_seq'].isin(val_rnas)].copy() |
|
|
test_df = df[df['RNA_seq'].isin(test_rnas)].copy() |
|
|
|
|
|
print(f"\n Split RNAs:") |
|
|
print(f" Train: {len(train_rnas)} RNAs ({len(train_df):,} samples, {100*len(train_df)/len(df):.1f}%)") |
|
|
print(f" Val: {len(val_rnas)} RNAs ({len(val_df):,} samples, {100*len(val_df)/len(df):.1f}%)") |
|
|
print(f" Test: {len(test_rnas)} RNAs ({len(test_df):,} samples, {100*len(test_df)/len(df):.1f}%)") |
|
|
|
|
|
|
|
|
assert len(train_rnas & val_rnas) == 0, "Train and val RNAs overlap!" |
|
|
assert len(train_rnas & test_rnas) == 0, "Train and test RNAs overlap!" |
|
|
assert len(val_rnas & test_rnas) == 0, "Val and test RNAs overlap!" |
|
|
|
|
|
print(f"\n ✓ RNA-disjoint verified: no RNA overlap across splits") |
|
|
|
|
|
|
|
|
train_compounds = set(train_df['SMILES'].unique()) |
|
|
val_compounds = set(val_df['SMILES'].unique()) |
|
|
test_compounds = set(test_df['SMILES'].unique()) |
|
|
|
|
|
overlap_train_val = len(train_compounds & val_compounds) |
|
|
overlap_train_test = len(train_compounds & test_compounds) |
|
|
|
|
|
print(f"\n Compound overlap (expected):") |
|
|
print(f" Train-Val: {overlap_train_val} compounds") |
|
|
print(f" Train-Test: {overlap_train_test} compounds") |
|
|
|
|
|
return train_df, val_df, test_df |
|
|
|
|
|
|
|
|
def create_compound_disjoint_split(df, train_ratio=0.7, val_ratio=0.15, seed=42): |
|
|
"""Create compound-disjoint split (compounds don't overlap across splits).""" |
|
|
print("\n" + "=" * 80) |
|
|
print("CREATING COMPOUND-DISJOINT SPLIT (Target: 70:15:15)") |
|
|
print("=" * 80) |
|
|
|
|
|
np.random.seed(seed) |
|
|
|
|
|
|
|
|
compound_counts = df.groupby('SMILES').size().reset_index(name='count') |
|
|
compound_counts = compound_counts.sample(frac=1, random_state=seed).reset_index(drop=True) |
|
|
|
|
|
|
|
|
total_samples = len(df) |
|
|
target_train = int(train_ratio * total_samples) |
|
|
target_val = int(val_ratio * total_samples) |
|
|
target_test = total_samples - target_train - target_val |
|
|
|
|
|
print(f"\n Target sample distribution:") |
|
|
print(f" Train: {target_train:,} ({train_ratio*100:.0f}%)") |
|
|
print(f" Val: {target_val:,} ({val_ratio*100:.0f}%)") |
|
|
print(f" Test: {target_test:,} ({(1-train_ratio-val_ratio)*100:.0f}%)") |
|
|
|
|
|
|
|
|
train_compounds = [] |
|
|
val_compounds = [] |
|
|
test_compounds = [] |
|
|
|
|
|
train_count = 0 |
|
|
val_count = 0 |
|
|
test_count = 0 |
|
|
|
|
|
for _, row in compound_counts.iterrows(): |
|
|
compound = row['SMILES'] |
|
|
count = row['count'] |
|
|
|
|
|
|
|
|
train_deficit = target_train - train_count |
|
|
val_deficit = target_val - val_count |
|
|
test_deficit = target_test - test_count |
|
|
|
|
|
if train_deficit >= val_deficit and train_deficit >= test_deficit: |
|
|
train_compounds.append(compound) |
|
|
train_count += count |
|
|
elif val_deficit >= test_deficit: |
|
|
val_compounds.append(compound) |
|
|
val_count += count |
|
|
else: |
|
|
test_compounds.append(compound) |
|
|
test_count += count |
|
|
|
|
|
train_compounds = set(train_compounds) |
|
|
val_compounds = set(val_compounds) |
|
|
test_compounds = set(test_compounds) |
|
|
|
|
|
|
|
|
train_df = df[df['SMILES'].isin(train_compounds)].copy() |
|
|
val_df = df[df['SMILES'].isin(val_compounds)].copy() |
|
|
test_df = df[df['SMILES'].isin(test_compounds)].copy() |
|
|
|
|
|
print(f"\n Split compounds:") |
|
|
print(f" Train: {len(train_compounds)} compounds ({len(train_df):,} samples, {100*len(train_df)/len(df):.1f}%)") |
|
|
print(f" Val: {len(val_compounds)} compounds ({len(val_df):,} samples, {100*len(val_df)/len(df):.1f}%)") |
|
|
print(f" Test: {len(test_compounds)} compounds ({len(test_df):,} samples, {100*len(test_df)/len(df):.1f}%)") |
|
|
|
|
|
|
|
|
assert len(train_compounds & val_compounds) == 0, "Train and val compounds overlap!" |
|
|
assert len(train_compounds & test_compounds) == 0, "Train and test compounds overlap!" |
|
|
assert len(val_compounds & test_compounds) == 0, "Val and test compounds overlap!" |
|
|
|
|
|
print(f"\n ✓ Compound-disjoint verified: no compound overlap across splits") |
|
|
|
|
|
|
|
|
train_rnas = set(train_df['RNA_seq'].unique()) |
|
|
val_rnas = set(val_df['RNA_seq'].unique()) |
|
|
test_rnas = set(test_df['RNA_seq'].unique()) |
|
|
|
|
|
overlap_train_val = len(train_rnas & val_rnas) |
|
|
overlap_train_test = len(train_rnas & test_rnas) |
|
|
|
|
|
print(f"\n RNA overlap (expected):") |
|
|
print(f" Train-Val: {overlap_train_val} RNAs") |
|
|
print(f" Train-Test: {overlap_train_test} RNAs") |
|
|
|
|
|
return train_df, val_df, test_df |
|
|
|
|
|
|
|
|
def save_splits(train_df, val_df, test_df, output_dir, dataset_name): |
|
|
"""Save splits to files.""" |
|
|
output_path = Path(output_dir) |
|
|
output_path.mkdir(parents=True, exist_ok=True) |
|
|
|
|
|
|
|
|
train_df.to_csv(output_path / 'train_text.csv', index=False) |
|
|
val_df.to_csv(output_path / 'val_text.csv', index=False) |
|
|
test_df.to_csv(output_path / 'test_text.csv', index=False) |
|
|
|
|
|
|
|
|
report = f"""# {dataset_name} Dataset Report |
|
|
|
|
|
## Overview |
|
|
Disjoint splits created from drug_rna_cds_sampled_11 dataset. |
|
|
|
|
|
## Split Statistics |
|
|
|
|
|
### Sample Counts |
|
|
- Train: {len(train_df):,} samples ({100*train_df['label'].mean():.1f}% positive) |
|
|
- Val: {len(val_df):,} samples ({100*val_df['label'].mean():.1f}% positive) |
|
|
- Test: {len(test_df):,} samples ({100*test_df['label'].mean():.1f}% positive) |
|
|
- Total: {len(train_df) + len(val_df) + len(test_df):,} samples |
|
|
|
|
|
### Unique Entities |
|
|
|
|
|
#### Compounds |
|
|
- Train: {train_df['SMILES'].nunique():,} |
|
|
- Val: {val_df['SMILES'].nunique():,} |
|
|
- Test: {test_df['SMILES'].nunique():,} |
|
|
|
|
|
#### RNAs |
|
|
- Train: {train_df['RNA_seq'].nunique():,} |
|
|
- Val: {val_df['RNA_seq'].nunique():,} |
|
|
- Test: {test_df['RNA_seq'].nunique():,} |
|
|
|
|
|
## Disjointness Properties |
|
|
|
|
|
### Compound Disjointness |
|
|
- Train-Val compound overlap: {len(set(train_df['SMILES'].unique()) & set(val_df['SMILES'].unique()))} |
|
|
- Train-Test compound overlap: {len(set(train_df['SMILES'].unique()) & set(test_df['SMILES'].unique()))} |
|
|
- Val-Test compound overlap: {len(set(val_df['SMILES'].unique()) & set(test_df['SMILES'].unique()))} |
|
|
|
|
|
### RNA Disjointness |
|
|
- Train-Val RNA overlap: {len(set(train_df['RNA_seq'].unique()) & set(val_df['RNA_seq'].unique()))} |
|
|
- Train-Test RNA overlap: {len(set(train_df['RNA_seq'].unique()) & set(test_df['RNA_seq'].unique()))} |
|
|
- Val-Test RNA overlap: {len(set(val_df['RNA_seq'].unique()) & set(test_df['RNA_seq'].unique()))} |
|
|
|
|
|
## Output Format |
|
|
Same as drug_rna_cds_sampled_11: |
|
|
- Columns: RNA_ID, Compound_ID, RNA_seq, SMILES, text, label |
|
|
- Files: train_text.csv, val_text.csv, test_text.csv |
|
|
|
|
|
## Use Case |
|
|
This split tests the model's ability to generalize to: |
|
|
- {'New compounds AND new RNAs' if 'disjoint' in dataset_name and 'rna' not in dataset_name and 'compound' not in dataset_name else 'New RNAs' if 'rna' in dataset_name else 'New compounds' if 'compound' in dataset_name else 'New samples'} |
|
|
|
|
|
Date: {pd.Timestamp.now().strftime('%Y-%m-%d %H:%M:%S')} |
|
|
""" |
|
|
|
|
|
with open(output_path / 'DATASET_REPORT.md', 'w') as f: |
|
|
f.write(report) |
|
|
|
|
|
print(f"\n Saved to: {output_path}") |
|
|
print(f" - train_text.csv") |
|
|
print(f" - val_text.csv") |
|
|
print(f" - test_text.csv") |
|
|
print(f" - DATASET_REPORT.md") |
|
|
|
|
|
|
|
|
def main(): |
|
|
parser = argparse.ArgumentParser( |
|
|
description="Create disjoint splits from drug_rna_cds_sampled_11" |
|
|
) |
|
|
parser.add_argument( |
|
|
'--input', |
|
|
default='datasets/drug_rna_cds_sampled_11', |
|
|
help='Input dataset directory' |
|
|
) |
|
|
parser.add_argument( |
|
|
'--seed', |
|
|
type=int, |
|
|
default=42, |
|
|
help='Random seed' |
|
|
) |
|
|
|
|
|
args = parser.parse_args() |
|
|
|
|
|
print("=" * 80) |
|
|
print("CREATING DISJOINT SPLITS FROM drug_rna_cds_sampled_11") |
|
|
print("=" * 80) |
|
|
|
|
|
|
|
|
input_path = Path(args.input) |
|
|
|
|
|
|
|
|
dfs = [] |
|
|
for split in ['train', 'val', 'test']: |
|
|
csv_path = input_path / f'{split}_text.csv' |
|
|
if csv_path.exists(): |
|
|
dfs.append(pd.read_csv(csv_path)) |
|
|
|
|
|
df = pd.concat(dfs, ignore_index=True) |
|
|
print(f"\nLoaded {len(df):,} samples from {input_path}") |
|
|
|
|
|
|
|
|
fully_disjoint_feasible = analyze_disjoint_feasibility(df) |
|
|
|
|
|
|
|
|
if fully_disjoint_feasible: |
|
|
print("\n" + "#" * 80) |
|
|
print("# CREATING: drug_rna_cds_disjoint (FULLY DISJOINT)") |
|
|
print("#" * 80) |
|
|
|
|
|
result = create_fully_disjoint_split(df, seed=args.seed) |
|
|
if result is not None: |
|
|
train_df, val_df, test_df = result |
|
|
save_splits( |
|
|
train_df, val_df, test_df, |
|
|
'datasets/drug_rna_cds_disjoint', |
|
|
'drug_rna_cds_disjoint' |
|
|
) |
|
|
else: |
|
|
print("\n ⚠️ Skipping fully disjoint split - not practical for this dataset") |
|
|
else: |
|
|
print("\n ⚠️ Skipping fully disjoint split - not enough samples") |
|
|
|
|
|
|
|
|
print("\n" + "#" * 80) |
|
|
print("# CREATING: drug_rna_cds_disjoint_rna (RNA-DISJOINT)") |
|
|
print("#" * 80) |
|
|
|
|
|
train_df, val_df, test_df = create_rna_disjoint_split(df, seed=args.seed) |
|
|
save_splits( |
|
|
train_df, val_df, test_df, |
|
|
'datasets/drug_rna_cds_disjoint_rna', |
|
|
'drug_rna_cds_disjoint_rna' |
|
|
) |
|
|
|
|
|
|
|
|
print("\n" + "#" * 80) |
|
|
print("# CREATING: drug_rna_cds_disjoint_compound (COMPOUND-DISJOINT)") |
|
|
print("#" * 80) |
|
|
|
|
|
train_df, val_df, test_df = create_compound_disjoint_split(df, seed=args.seed) |
|
|
save_splits( |
|
|
train_df, val_df, test_df, |
|
|
'datasets/drug_rna_cds_disjoint_compound', |
|
|
'drug_rna_cds_disjoint_compound' |
|
|
) |
|
|
|
|
|
print("\n" + "=" * 80) |
|
|
print("ALL DISJOINT SPLITS CREATED SUCCESSFULLY") |
|
|
print("=" * 80) |
|
|
print("\nCreated datasets:") |
|
|
if fully_disjoint_feasible: |
|
|
print(" 1. drug_rna_cds_disjoint - Fully disjoint (compounds AND RNAs)") |
|
|
print(" 2. drug_rna_cds_disjoint_rna - RNA-disjoint") |
|
|
print(" 3. drug_rna_cds_disjoint_compound - Compound-disjoint") |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
main() |
|
|
|