Spaces:
Running
Running
File size: 17,910 Bytes
6754836 68a03a2 6754836 68a03a2 6754836 68a03a2 6754836 68a03a2 6754836 68a03a2 6754836 68a03a2 6754836 e8e66c2 6754836 68a03a2 6754836 68a03a2 6754836 68a03a2 6754836 e8e66c2 6754836 e8e66c2 6754836 e8e66c2 6754836 e8e66c2 6754836 e8e66c2 6754836 e8e66c2 6754836 68a03a2 6754836 68a03a2 6754836 68a03a2 6754836 68a03a2 6754836 68a03a2 6754836 | 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 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 | """
Tests for CPR CLI (protein_conformal/cli.py).
Tests cover:
- Help text for all commands
- Basic functionality with mock data
- Error handling
"""
import subprocess
import sys
import tempfile
import numpy as np
import pandas as pd
import pytest
from pathlib import Path
def run_cli(*args):
"""Helper to run CLI commands via subprocess."""
result = subprocess.run(
[sys.executable, '-m', 'protein_conformal.cli'] + list(args),
capture_output=True,
text=True
)
return result
def test_main_help():
"""Test that 'cpr --help' shows all subcommands."""
result = run_cli('--help')
assert result.returncode == 0
assert 'embed' in result.stdout
assert 'search' in result.stdout
assert 'verify' in result.stdout
assert 'prob' in result.stdout
assert 'calibrate' in result.stdout
assert 'Conformal Protein Retrieval' in result.stdout
def test_main_no_command():
"""Test that running cpr with no command shows help."""
result = run_cli()
assert result.returncode == 1
# Should show help when no command provided
assert 'embed' in result.stdout or 'embed' in result.stderr
def test_embed_help():
"""Test that 'cpr embed --help' works and shows expected options."""
result = run_cli('embed', '--help')
assert result.returncode == 0
assert '--input' in result.stdout
assert '--output' in result.stdout
assert '--model' in result.stdout
assert 'protein-vec' in result.stdout
assert 'clean' in result.stdout
assert '--cpu' in result.stdout
def test_search_help():
"""Test that 'cpr search --help' works."""
result = run_cli('search', '--help')
assert result.returncode == 0
assert '--input' in result.stdout
assert '--database' in result.stdout
assert '--output' in result.stdout
assert '--k' in result.stdout
assert '--threshold' in result.stdout
assert '--database-meta' in result.stdout
def test_verify_help():
"""Test that 'cpr verify --help' works."""
result = run_cli('verify', '--help')
assert result.returncode == 0
assert '--check' in result.stdout
assert 'syn30' in result.stdout
assert 'fdr' in result.stdout
assert 'dali' in result.stdout
assert 'clean' in result.stdout
def test_prob_help():
"""Test that 'cpr prob --help' works."""
result = run_cli('prob', '--help')
assert result.returncode == 0
assert '--input' in result.stdout
assert '--calibration' in result.stdout
assert '--output' in result.stdout
assert '--score-column' in result.stdout
assert '--n-calib' in result.stdout
assert '--seed' in result.stdout
def test_calibrate_help():
"""Test that 'cpr calibrate --help' works."""
result = run_cli('calibrate', '--help')
assert result.returncode == 0
assert '--calibration' in result.stdout
assert '--output' in result.stdout
assert '--alpha' in result.stdout
assert '--n-trials' in result.stdout
assert '--n-calib' in result.stdout
assert '--method' in result.stdout
assert 'ltt' in result.stdout
assert 'quantile' in result.stdout
def test_embed_missing_args():
"""Test that embed command fails without required args."""
result = run_cli('embed')
assert result.returncode != 0
assert '--input' in result.stderr or 'required' in result.stderr
def test_search_missing_args():
"""Test that search command fails without required args."""
result = run_cli('search')
assert result.returncode != 0
assert '--input' in result.stderr or 'required' in result.stderr
def test_verify_missing_args():
"""Test that verify command fails without required args."""
result = run_cli('verify')
assert result.returncode != 0
assert '--check' in result.stderr or 'required' in result.stderr
def test_verify_invalid_check():
"""Test that verify command fails with invalid check name."""
result = run_cli('verify', '--check', 'invalid_check_name')
assert result.returncode != 0
def test_search_with_mock_data(tmp_path):
"""Test search command with small mock embeddings."""
# Create mock query and database embeddings
np.random.seed(42)
query_embeddings = np.random.randn(5, 128).astype(np.float32)
db_embeddings = np.random.randn(20, 128).astype(np.float32)
# Normalize to unit vectors (for cosine similarity)
query_embeddings = query_embeddings / np.linalg.norm(query_embeddings, axis=1, keepdims=True)
db_embeddings = db_embeddings / np.linalg.norm(db_embeddings, axis=1, keepdims=True)
# Save to temp files
query_file = tmp_path / "query.npy"
db_file = tmp_path / "db.npy"
output_file = tmp_path / "results.csv"
np.save(query_file, query_embeddings)
np.save(db_file, db_embeddings)
# Run search (use --no-filter since random embeddings won't pass FDR threshold)
result = run_cli(
'search',
'--input', str(query_file),
'--database', str(db_file),
'--output', str(output_file),
'--k', '3',
'--no-filter'
)
assert result.returncode == 0
assert output_file.exists()
# Verify output
df = pd.read_csv(output_file)
assert len(df) == 5 * 3 # 5 queries * 3 neighbors
assert 'query_idx' in df.columns
assert 'match_idx' in df.columns
assert 'similarity' in df.columns
# Check that similarities are reasonable (cosine similarity range)
assert df['similarity'].min() >= -1.0
assert df['similarity'].max() <= 1.0
def test_search_with_threshold(tmp_path):
"""Test search command with similarity threshold."""
np.random.seed(42)
query_embeddings = np.random.randn(3, 128).astype(np.float32)
db_embeddings = np.random.randn(10, 128).astype(np.float32)
query_embeddings = query_embeddings / np.linalg.norm(query_embeddings, axis=1, keepdims=True)
db_embeddings = db_embeddings / np.linalg.norm(db_embeddings, axis=1, keepdims=True)
query_file = tmp_path / "query.npy"
db_file = tmp_path / "db.npy"
output_file = tmp_path / "results.csv"
np.save(query_file, query_embeddings)
np.save(db_file, db_embeddings)
# Run search with high threshold
result = run_cli(
'search',
'--input', str(query_file),
'--database', str(db_file),
'--output', str(output_file),
'--k', '10',
'--threshold', '0.9'
)
assert result.returncode == 0
assert output_file.exists()
# With high threshold on random embeddings, file may be empty or have few results
# Random unit vectors have expected cosine similarity ~0, so 0.9 threshold filters most
try:
df = pd.read_csv(output_file)
# With high threshold, we should have fewer results
assert len(df) <= 3 * 10 # At most 3 queries * 10 neighbors
# All results should be above threshold
if len(df) > 0:
assert df['similarity'].min() >= 0.9
except pd.errors.EmptyDataError:
# Empty file is valid - no results passed threshold
pass
def test_search_with_metadata(tmp_path):
"""Test search command with database metadata."""
np.random.seed(42)
query_embeddings = np.random.randn(2, 128).astype(np.float32)
db_embeddings = np.random.randn(5, 128).astype(np.float32)
query_embeddings = query_embeddings / np.linalg.norm(query_embeddings, axis=1, keepdims=True)
db_embeddings = db_embeddings / np.linalg.norm(db_embeddings, axis=1, keepdims=True)
query_file = tmp_path / "query.npy"
db_file = tmp_path / "db.npy"
meta_file = tmp_path / "meta.csv"
output_file = tmp_path / "results.csv"
np.save(query_file, query_embeddings)
np.save(db_file, db_embeddings)
# Create metadata
meta_df = pd.DataFrame({
'protein_id': [f'PROT_{i:03d}' for i in range(5)],
'description': [f'Protein {i}' for i in range(5)],
'organism': ['E. coli', 'Human', 'Yeast', 'Mouse', 'Rat'],
})
meta_df.to_csv(meta_file, index=False)
# Run search with metadata (use --no-filter since random embeddings won't pass FDR threshold)
result = run_cli(
'search',
'--input', str(query_file),
'--database', str(db_file),
'--database-meta', str(meta_file),
'--output', str(output_file),
'--k', '3',
'--no-filter'
)
assert result.returncode == 0
assert output_file.exists()
df = pd.read_csv(output_file)
assert len(df) == 2 * 3 # 2 queries * 3 neighbors
# Check that metadata columns were added
assert 'match_protein_id' in df.columns
assert 'match_description' in df.columns
assert 'match_organism' in df.columns
def test_prob_with_mock_data(tmp_path):
"""Test prob command with mock calibration data and scores."""
np.random.seed(42)
# Create mock calibration data (format: array of dicts with S_i, exact, partial)
n_calib = 50
cal_data = []
for i in range(n_calib):
sims = np.random.uniform(0.998, 0.9999, size=10).astype(np.float32)
exact_labels = (np.random.random(10) < 0.2).astype(bool)
partial_labels = exact_labels | (np.random.random(10) < 0.1)
cal_data.append({
"S_i": sims,
"exact": exact_labels,
"partial": partial_labels,
})
cal_file = tmp_path / "calibration.npy"
np.save(cal_file, np.array(cal_data, dtype=object))
# Create input scores
scores = np.array([0.9985, 0.9990, 0.9995, 0.9998])
score_file = tmp_path / "scores.npy"
np.save(score_file, scores)
output_file = tmp_path / "probs.csv"
# Run prob command
result = run_cli(
'prob',
'--input', str(score_file),
'--calibration', str(cal_file),
'--output', str(output_file),
'--n-calib', '50',
'--seed', '42'
)
assert result.returncode == 0
assert output_file.exists()
df = pd.read_csv(output_file)
assert len(df) == 4
assert 'score' in df.columns
assert 'probability' in df.columns
assert 'uncertainty' in df.columns
# Probabilities should be in [0, 1]
assert df['probability'].min() >= 0.0
assert df['probability'].max() <= 1.0
# Uncertainties should be in [0, 1]
assert df['uncertainty'].min() >= 0.0
assert df['uncertainty'].max() <= 1.0
def test_prob_with_csv_input(tmp_path):
"""Test prob command with CSV input (e.g., from search results)."""
np.random.seed(42)
# Create mock calibration data (format: array of dicts with S_i, exact, partial)
n_calib = 30
cal_data = []
for i in range(n_calib):
sims = np.random.uniform(0.998, 0.9999, size=5).astype(np.float32)
exact_labels = (np.random.random(5) < 0.2).astype(bool)
partial_labels = exact_labels | (np.random.random(5) < 0.1)
cal_data.append({
"S_i": sims,
"exact": exact_labels,
"partial": partial_labels,
})
cal_file = tmp_path / "calibration.npy"
np.save(cal_file, np.array(cal_data, dtype=object))
# Create CSV input with similarity scores
input_df = pd.DataFrame({
'query_idx': [0, 0, 1, 1],
'match_idx': [5, 10, 3, 8],
'similarity': [0.9985, 0.9990, 0.9995, 0.9998],
'match_protein_id': ['PROT_A', 'PROT_B', 'PROT_C', 'PROT_D'],
})
input_file = tmp_path / "input.csv"
input_df.to_csv(input_file, index=False)
output_file = tmp_path / "output.csv"
# Run prob command
result = run_cli(
'prob',
'--input', str(input_file),
'--calibration', str(cal_file),
'--output', str(output_file),
'--score-column', 'similarity',
'--n-calib', '30'
)
assert result.returncode == 0
assert output_file.exists()
df = pd.read_csv(output_file)
assert len(df) == 4
# Original columns should be preserved
assert 'query_idx' in df.columns
assert 'match_idx' in df.columns
assert 'similarity' in df.columns
assert 'match_protein_id' in df.columns
# New columns should be added
assert 'probability' in df.columns
assert 'uncertainty' in df.columns
def test_calibrate_with_mock_data(tmp_path):
"""Test calibrate command with mock calibration data."""
np.random.seed(42)
# Create mock calibration data (format: array of dicts with S_i, exact, partial)
n_samples = 100
cal_data = []
for i in range(n_samples):
sims = np.random.uniform(0.997, 0.9999, size=10).astype(np.float32)
# Create labels: higher similarity -> higher chance of being positive
exact_labels = (sims > 0.9995).astype(bool)
partial_labels = (sims > 0.999).astype(bool)
cal_data.append({
"S_i": sims,
"exact": exact_labels,
"partial": partial_labels,
})
cal_file = tmp_path / "calibration.npy"
np.save(cal_file, np.array(cal_data, dtype=object))
output_file = tmp_path / "thresholds.csv"
# Run calibrate command (small number of trials for speed)
result = run_cli(
'calibrate',
'--calibration', str(cal_file),
'--output', str(output_file),
'--alpha', '0.1',
'--n-trials', '5',
'--n-calib', '50',
'--method', 'quantile',
'--seed', '42'
)
assert result.returncode == 0
assert output_file.exists()
df = pd.read_csv(output_file)
assert len(df) == 5 # 5 trials
assert 'trial' in df.columns
assert 'alpha' in df.columns
assert 'fdr_threshold' in df.columns
assert 'fnr_threshold' in df.columns
# All alpha values should be 0.1
assert (df['alpha'] == 0.1).all()
# Thresholds should be in reasonable range
assert df['fdr_threshold'].min() > 0.0
assert df['fdr_threshold'].max() <= 1.0
assert df['fnr_threshold'].min() > 0.0
assert df['fnr_threshold'].max() <= 1.0
def test_embed_missing_input_file():
"""Test that embed fails gracefully with missing input file."""
with tempfile.NamedTemporaryFile(suffix='.npy', delete=False) as tmp:
output_file = tmp.name
try:
result = run_cli(
'embed',
'--input', '/nonexistent/file.fasta',
'--output', output_file
)
assert result.returncode != 0
finally:
Path(output_file).unlink(missing_ok=True)
def test_search_missing_query_file(tmp_path):
"""Test that search fails gracefully with missing query file."""
# Create a valid database file
db_embeddings = np.random.randn(10, 128).astype(np.float32)
db_file = tmp_path / "db.npy"
np.save(db_file, db_embeddings)
output_file = tmp_path / "results.csv"
result = run_cli(
'search',
'--input', '/nonexistent/query.npy',
'--database', str(db_file),
'--output', str(output_file)
)
assert result.returncode != 0
def test_search_missing_database_file(tmp_path):
"""Test that search fails gracefully with missing database file."""
# Create a valid query file
query_embeddings = np.random.randn(5, 128).astype(np.float32)
query_file = tmp_path / "query.npy"
np.save(query_file, query_embeddings)
output_file = tmp_path / "results.csv"
result = run_cli(
'search',
'--input', str(query_file),
'--database', '/nonexistent/db.npy',
'--output', str(output_file)
)
assert result.returncode != 0
def test_prob_missing_calibration_file(tmp_path):
"""Test that prob fails gracefully with missing calibration file."""
scores = np.array([0.998, 0.999])
score_file = tmp_path / "scores.npy"
np.save(score_file, scores)
output_file = tmp_path / "probs.csv"
result = run_cli(
'prob',
'--input', str(score_file),
'--calibration', '/nonexistent/calibration.npy',
'--output', str(output_file)
)
assert result.returncode != 0
def test_calibrate_missing_calibration_file(tmp_path):
"""Test that calibrate fails gracefully with missing calibration file."""
output_file = tmp_path / "thresholds.csv"
result = run_cli(
'calibrate',
'--calibration', '/nonexistent/calibration.npy',
'--output', str(output_file),
'--n-trials', '1'
)
assert result.returncode != 0
def test_search_with_k_larger_than_database(tmp_path):
"""Test search when k is larger than database size."""
np.random.seed(42)
query_embeddings = np.random.randn(2, 128).astype(np.float32)
db_embeddings = np.random.randn(3, 128).astype(np.float32) # Only 3 items
query_embeddings = query_embeddings / np.linalg.norm(query_embeddings, axis=1, keepdims=True)
db_embeddings = db_embeddings / np.linalg.norm(db_embeddings, axis=1, keepdims=True)
query_file = tmp_path / "query.npy"
db_file = tmp_path / "db.npy"
output_file = tmp_path / "results.csv"
np.save(query_file, query_embeddings)
np.save(db_file, db_embeddings)
# Request k=10 but only have 3 items in database (use --no-filter)
result = run_cli(
'search',
'--input', str(query_file),
'--database', str(db_file),
'--output', str(output_file),
'--k', '10',
'--no-filter'
)
# Should succeed (FAISS will return at most db size)
assert result.returncode == 0
assert output_file.exists()
df = pd.read_csv(output_file)
# Should have at most 2 * 3 = 6 results (2 queries, 3 db items each)
assert len(df) <= 6
def test_cli_module_import():
"""Test that CLI module can be imported and has expected functions."""
from protein_conformal import cli
assert hasattr(cli, 'main')
assert hasattr(cli, 'cmd_embed')
assert hasattr(cli, 'cmd_search')
assert hasattr(cli, 'cmd_verify')
assert hasattr(cli, 'cmd_prob')
assert hasattr(cli, 'cmd_calibrate')
assert callable(cli.main)
|