File size: 17,434 Bytes
6edb4a9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 |
#!/usr/bin/env python3
"""
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:,}")
# Analyze compound-RNA pairs
pairs = df.groupby(['SMILES', 'RNA_seq']).size().reset_index(name='count')
print(f" Unique (compound, RNA) pairs: {len(pairs):,}")
# Check samples per entity
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}")
# Estimate fully disjoint feasibility
# For fully disjoint: need non-overlapping sets of (compound, RNA) pairs
# This is only possible if we can partition compounds and RNAs
# Simple heuristic: check if we have enough samples
min_samples_needed = int(0.15 * n_samples) # For test set (15%)
print(f"\n Minimum samples needed for test (15%): {min_samples_needed:,}")
# Check if we can allocate compounds/RNAs
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:,}")
# Check actual connectivity
compound_to_rnas = df.groupby('SMILES')['RNA_seq'].apply(set).to_dict()
rna_to_compounds = df.groupby('RNA_seq')['SMILES'].apply(set).to_dict()
# Calculate how connected the graph is
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}")
# Determine feasibility
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)
# Get unique entities
compounds = df['SMILES'].unique()
rnas = df['RNA_seq'].unique()
# Shuffle
np.random.shuffle(compounds)
np.random.shuffle(rnas)
# Split compounds
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:])
# Split RNAs
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:])
# Assign samples based on BOTH compound and RNA membership
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)
# Get RNAs with their sample counts
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) # Shuffle
# Target sample counts
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}%)")
# Greedy assignment: assign RNAs to splits to match target ratios
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']
# Assign to the split that needs samples most
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)
# Assign samples based on RNA
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}%)")
# Verify disjointness
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")
# Check compound overlap (expected)
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)
# Get compounds with their sample counts
compound_counts = df.groupby('SMILES').size().reset_index(name='count')
compound_counts = compound_counts.sample(frac=1, random_state=seed).reset_index(drop=True) # Shuffle
# Target sample counts
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}%)")
# Greedy assignment: assign compounds to splits to match target ratios
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']
# Assign to the split that needs samples most
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)
# Assign samples based on compound
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}%)")
# Verify disjointness
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")
# Check RNA overlap (expected)
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)
# Save CSV files
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)
# Create report
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)
# Load data
input_path = Path(args.input)
# Combine all splits from source
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}")
# Analyze feasibility
fully_disjoint_feasible = analyze_disjoint_feasibility(df)
# 1. Try fully disjoint
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")
# 2. Create RNA-disjoint
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'
)
# 3. Create compound-disjoint
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()
|