abyss-db-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
abyss_cli.py ADDED
@@ -0,0 +1,1518 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ abyss_cli.py — Command-line interface for ABYSS.
4
+
5
+ Query the ABYSS *Acinetobacter baumannii* genomic surveillance database
6
+ from the terminal. The full dataset ships bundled with the package.
7
+
8
+ ABYSS (Acinetobacter baumannii Yielding Surveillance System) is part of
9
+ the ARGUS
10
+ initiative for ESKAPE pathogen surveillance.
11
+ """
12
+
13
+ import argparse
14
+ import gzip
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import random
19
+ import re
20
+ import signal
21
+ import sys
22
+ import tempfile
23
+ import urllib.error
24
+ import urllib.request
25
+ import zipfile
26
+ from pathlib import Path
27
+ from typing import Optional
28
+
29
+ import pandas as pd
30
+
31
+ if sys.platform != "win32" and hasattr(signal, "SIGPIPE"):
32
+ signal.signal(signal.SIGPIPE, signal.SIG_DFL)
33
+
34
+ __version__ = "0.1.0"
35
+ __author__ = "Brown Beckley"
36
+ __affiliation__ = "University of Ghana Medical School, Accra, Ghana"
37
+ __license__ = "MIT"
38
+
39
+ DATA_REPO = "bbeckley-hub/argus-data"
40
+ DATA_ASSET_NAME = "abyss_data.zip"
41
+ DATA_TAG_PREFIX = "abyss-data-"
42
+
43
+
44
+ # ---------------------------------------------------------------------------
45
+ # Lineage signatures
46
+ # ---------------------------------------------------------------------------
47
+
48
+ LINEAGE_SIGNATURES = {
49
+ # Historical global clone names
50
+ "GC1": {"ic": "IC1"},
51
+ "GC2": {"ic": "IC2"},
52
+ # International clones (Pasteur scheme)
53
+ "IC1": {"ic": "IC1"},
54
+ "IC2": {"ic": "IC2"},
55
+ "IC3": {"ic": "IC3"},
56
+ "IC4": {"ic": "IC4"},
57
+ "IC5": {"ic": "IC5"},
58
+ "IC6": {"ic": "IC6"},
59
+ "IC7": {"ic": "IC7"},
60
+ "IC8": {"ic": "IC8"},
61
+ "IC9": {"ic": "IC9"},
62
+ # Widely-used Oxford sequence types
63
+ "ST25": {"oxford_st": "25"},
64
+ "ST92": {"oxford_st": "92"},
65
+ "ST195": {"oxford_st": "195"},
66
+ "ST208": {"oxford_st": "208"},
67
+ "ST218": {"oxford_st": "218"},
68
+ }
69
+
70
+
71
+ # ---------------------------------------------------------------------------
72
+ # Carbapenemase detection
73
+ # ---------------------------------------------------------------------------
74
+
75
+ CARBAPENEMASE_PATTERNS = [
76
+ r"OXA-23(?!\d)",
77
+ r"OXA-24(?!\d)",
78
+ r"OXA-40(?!\d)",
79
+ r"OXA-58(?!\d)",
80
+ r"OXA-72(?!\d)",
81
+ r"OXA-143(?!\d)",
82
+ r"OXA-235(?!\d)",
83
+ r"NDM(?!\d)",
84
+ r"KPC(?!\d)",
85
+ r"IMP(?!\d)",
86
+ r"VIM(?!\d)",
87
+ r"SPM(?!\d)",
88
+ r"SIM(?!\d)",
89
+ r"GIM(?!\d)",
90
+ ]
91
+ CARBAPENEMASE_RE = re.compile("|".join(CARBAPENEMASE_PATTERNS), re.IGNORECASE)
92
+
93
+
94
+ # ---------------------------------------------------------------------------
95
+ # Output format map
96
+ # ---------------------------------------------------------------------------
97
+
98
+ EXT_MAP = {
99
+ "accession": ".txt",
100
+ "biosample": "_biosamples.txt",
101
+ "bioproject": "_bioprojects.txt",
102
+ "tsv": ".tsv",
103
+ "csv": ".csv",
104
+ "json": ".json",
105
+ }
106
+ VALID_FORMATS = set(EXT_MAP.keys())
107
+
108
+
109
+ # ---------------------------------------------------------------------------
110
+ # Color support
111
+ # ---------------------------------------------------------------------------
112
+
113
+ def _supports_color(stream):
114
+ if os.environ.get("NO_COLOR"):
115
+ return False
116
+ if os.environ.get("FORCE_COLOR"):
117
+ return True
118
+ try:
119
+ return stream.isatty()
120
+ except (AttributeError, ValueError):
121
+ return False
122
+
123
+
124
+ class _Palette:
125
+ CODES = {
126
+ "RESET": "\033[0m", "BOLD": "\033[1m", "DIM": "\033[2m",
127
+ "ITALIC": "\033[3m", "UNDER": "\033[4m",
128
+ "RED": "\033[91m", "GREEN": "\033[92m", "YELLOW": "\033[93m",
129
+ "BLUE": "\033[94m", "MAGENTA": "\033[95m", "CYAN": "\033[96m",
130
+ "WHITE": "\033[97m", "GOLD": "\033[33m", "GRAY": "\033[90m",
131
+ }
132
+
133
+ def __init__(self, enabled):
134
+ self._on = enabled
135
+
136
+ def __getattr__(self, name):
137
+ return self.CODES.get(name, "") if self._on else ""
138
+
139
+
140
+ C = _Palette(_supports_color(sys.stderr))
141
+ CO = _Palette(_supports_color(sys.stdout))
142
+
143
+
144
+ # ---------------------------------------------------------------------------
145
+ # Banner
146
+ # ---------------------------------------------------------------------------
147
+
148
+ ABYSS_ASCII = r"""
149
+ _ ____ __ ____ ____
150
+ / \ | __ ) \ \ / / ___/ ___|
151
+ / _ \ | _ \ \ V /\___ \___ \
152
+ / ___ \| |_) | | | ___) |__) |
153
+ /_/ \_\____/ |_| |____/____/
154
+ """
155
+
156
+
157
+ def print_banner(quiet=False):
158
+ """Print the ABYSS banner to stderr (skipped in quiet mode)."""
159
+ if quiet or not _supports_color(sys.stderr):
160
+ return
161
+ print(f"{C.GOLD}{C.BOLD}{ABYSS_ASCII}{C.RESET}", file=sys.stderr)
162
+ print(
163
+ f"{C.CYAN} ABYSS CLI · v{__version__}{C.RESET}",
164
+ file=sys.stderr,
165
+ )
166
+ print(
167
+ f"{C.DIM} Acinetobacter baumannii Yielding Surveillance System{C.RESET}",
168
+ file=sys.stderr,
169
+ )
170
+ print(
171
+ f"{C.DIM} ARGUS initiative · {__affiliation__} · MIT License{C.RESET}",
172
+ file=sys.stderr,
173
+ )
174
+ print("", file=sys.stderr)
175
+
176
+
177
+ # ---------------------------------------------------------------------------
178
+ # Data discovery
179
+ # ---------------------------------------------------------------------------
180
+
181
+ def _get_candidates(explicit: Optional[str] = None) -> list[Path]:
182
+ candidates: list[Path] = []
183
+ if explicit:
184
+ candidates.append(Path(explicit).expanduser().resolve())
185
+ env = os.environ.get("ABYSS_DATA_DIR")
186
+ if env:
187
+ candidates.append(Path(env).expanduser().resolve())
188
+ candidates.extend([
189
+ Path.home() / ".abyss" / "data",
190
+ Path.home() / ".local" / "share" / "abyss",
191
+ Path.cwd() / "data",
192
+ Path(sys.prefix) / "share" / "abyss" / "data",
193
+ ])
194
+ return candidates
195
+
196
+
197
+ def find_data_dir(explicit: Optional[str] = None) -> Optional[Path]:
198
+ """Return the first candidate that contains a master table."""
199
+ for c in _get_candidates(explicit):
200
+ try:
201
+ if (c / "master" / "abyss_all.tsv").exists() or \
202
+ (c / "master" / "abyss_all.tsv.gz").exists():
203
+ return c
204
+ except (OSError, PermissionError):
205
+ continue
206
+ return None
207
+
208
+
209
+ def read_manifest(data_dir: Path) -> dict:
210
+ """Load the release manifest if it exists."""
211
+ p = data_dir / "master" / "abyss_manifest.json"
212
+ if not p.exists():
213
+ return {}
214
+ try:
215
+ with open(p) as f:
216
+ return json.load(f)
217
+ except Exception:
218
+ return {}
219
+
220
+
221
+ def read_tsv(path: Path, **kwargs) -> pd.DataFrame:
222
+ """Read a TSV, transparently handling gzip."""
223
+ if not path.exists():
224
+ gz = path.with_suffix(path.suffix + ".gz")
225
+ if gz.exists():
226
+ path = gz
227
+ else:
228
+ raise FileNotFoundError(f"Data file not found: {path}")
229
+ if path.suffix == ".gz":
230
+ return pd.read_csv(path, sep="\t", dtype=str, compression="gzip", **kwargs)
231
+ return pd.read_csv(path, sep="\t", dtype=str, **kwargs)
232
+
233
+
234
+ def load_master(data_dir: Path) -> pd.DataFrame:
235
+ """Load the master table."""
236
+ return read_tsv(data_dir / "master" / "abyss_all.tsv")
237
+
238
+
239
+ # ---------------------------------------------------------------------------
240
+ # Logging helpers
241
+ # ---------------------------------------------------------------------------
242
+
243
+ def log_loading(msg): print(f"{C.CYAN}🔍 {msg}{C.RESET}", file=sys.stderr)
244
+ def log_found(n): print(f"{C.GREEN}{C.BOLD}✨ Found {n:,} matching genomes{C.RESET}", file=sys.stderr)
245
+ def log_debug(msg): print(f"{C.GRAY} [debug] {msg}{C.RESET}", file=sys.stderr)
246
+ def log_error(msg): print(f"{C.RED}{C.BOLD}❌ {msg}{C.RESET}", file=sys.stderr)
247
+ def log_warn(msg): print(f"{C.YELLOW}⚠️ {msg}{C.RESET}", file=sys.stderr)
248
+ def log_info(msg): print(f"{C.CYAN}ℹ️ {msg}{C.RESET}", file=sys.stderr)
249
+ def log_write(path, rows, fmt):
250
+ print(f"{C.GREEN}💾{C.RESET} {C.CYAN}{path}{C.RESET} "
251
+ f"{C.DIM}({rows:,} rows · {fmt.upper()}){C.RESET}", file=sys.stderr)
252
+
253
+
254
+ def debug_step(label, df, enabled):
255
+ """Print a debug trace if --debug is enabled."""
256
+ if enabled:
257
+ log_debug(f"{label}: {len(df):,} rows")
258
+
259
+
260
+ def log_zero():
261
+ print(f"{C.YELLOW}{C.BOLD}⚠️ Found 0 matching genomes{C.RESET}", file=sys.stderr)
262
+ print(f"{C.GRAY} 💡 Try removing a filter, or run with "
263
+ f"{C.BOLD}--debug{C.RESET}{C.GRAY} to see where the count drops.{C.RESET}",
264
+ file=sys.stderr)
265
+
266
+
267
+ # ---------------------------------------------------------------------------
268
+ # Filter functions
269
+ # ---------------------------------------------------------------------------
270
+
271
+ def _norm_st(value: str) -> str:
272
+ v = str(value).strip()
273
+ if v.upper().startswith("ST"):
274
+ v = v[2:]
275
+ return v
276
+
277
+
278
+ def filter_st(df, value, debug=False):
279
+ """Filter by Pasteur sequence type. Accepts 2 or ST2."""
280
+ t = _norm_st(value)
281
+ col = df["mlst_st"].fillna("").astype(str).str.strip()
282
+ col_clean = col.str.replace(r"^[Ss][Tt]", "", regex=True)
283
+ result = df[col_clean == t]
284
+ debug_step(f"--st {t}", result, debug)
285
+ return result
286
+
287
+
288
+ def filter_oxford_st(df, value, debug=False):
289
+ """Filter by Oxford sequence type. Accepts 208 or ST208."""
290
+ t = _norm_st(value)
291
+ col = df["mlst_st_oxford"].fillna("").astype(str).str.strip()
292
+ col_clean = col.str.replace(r"^[Ss][Tt]", "", regex=True)
293
+ result = df[col_clean == t]
294
+ debug_step(f"--oxford-st {t}", result, debug)
295
+ return result
296
+
297
+
298
+ def filter_ic(df, value, debug=False):
299
+ v = str(value).strip().upper()
300
+ if not v.startswith("IC"):
301
+ v = "IC" + v
302
+ result = df[df["mlst_ic"].fillna("").str.upper().str.strip() == v]
303
+ debug_step(f"--ic {v}", result, debug)
304
+ return result
305
+
306
+
307
+ def filter_kl(df, value, debug=False):
308
+ v = str(value).strip().upper()
309
+ if not v.startswith("KL"):
310
+ v = "KL" + v
311
+ result = df[df["kl_locus"].fillna("").str.upper().str.strip() == v]
312
+ debug_step(f"--kl {v}", result, debug)
313
+ return result
314
+
315
+
316
+ def filter_ocl(df, value, debug=False):
317
+ v = str(value).strip().upper()
318
+ if not v.startswith("OCL"):
319
+ v = "OCL" + v
320
+ result = df[df["ocl_locus"].fillna("").str.upper().str.strip() == v]
321
+ debug_step(f"--ocl {v}", result, debug)
322
+ return result
323
+
324
+
325
+ def filter_oxa(df, value, debug=False):
326
+ v = str(value).strip().upper()
327
+ if not v.startswith("OXA"):
328
+ v = "OXA-" + v
329
+ pat = re.compile(re.escape(v) + r"(?!\d)")
330
+ result = df[df["oxa_variant"].fillna("").str.upper().str.contains(pat, na=False)]
331
+ debug_step(f"--oxa {v}", result, debug)
332
+ return result
333
+
334
+
335
+ def filter_country(df, value, debug=False):
336
+ c = str(value).strip().lower()
337
+ col_a = df["country"].fillna("").str.lower()
338
+ col_b = df["country_raw"].fillna("").str.lower() if "country_raw" in df.columns else col_a
339
+ result = df[col_a.str.contains(c, na=False) | col_b.str.contains(c, na=False)]
340
+ debug_step(f"--country '{value}'", result, debug)
341
+ return result
342
+
343
+
344
+ def filter_continent(df, value, debug=False):
345
+ c = str(value).strip().lower()
346
+ result = df[df["continent"].fillna("").str.lower().str.contains(c, na=False)]
347
+ debug_step(f"--continent '{value}'", result, debug)
348
+ return result
349
+
350
+
351
+ def filter_region(df, value, debug=False):
352
+ c = str(value).strip().lower()
353
+ result = df[df["region"].fillna("").str.lower().str.contains(c, na=False)]
354
+ debug_step(f"--region '{value}'", result, debug)
355
+ return result
356
+
357
+
358
+ def filter_super_group(df, value, debug=False):
359
+ c = str(value).strip().lower()
360
+ result = df[df["super_group"].fillna("").str.lower().str.contains(c, na=False)]
361
+ debug_step(f"--super-group '{value}'", result, debug)
362
+ return result
363
+
364
+
365
+ def filter_source(df, value, debug=False):
366
+ s = str(value).strip().lower()
367
+ col_a = df["source"].fillna("").str.lower()
368
+ col_b = df["source_raw"].fillna("").str.lower() if "source_raw" in df.columns else col_a
369
+ result = df[col_a.str.contains(s, na=False) | col_b.str.contains(s, na=False)]
370
+ debug_step(f"--source '{value}'", result, debug)
371
+ return result
372
+
373
+
374
+ def filter_host(df, value, debug=False):
375
+ h = str(value).strip()
376
+ result = df[df["host"].fillna("").str.contains(h, case=False, na=False)]
377
+ debug_step(f"--host '{value}'", result, debug)
378
+ return result
379
+
380
+
381
+ def filter_year(df, value, debug=False):
382
+ yc = df["year"].fillna("").astype(str).str[:4]
383
+ if "-" in str(value):
384
+ a, b = str(value).split("-")
385
+ result = df[(yc >= a.strip()) & (yc <= b.strip())]
386
+ debug_step(f"--year {a}-{b}", result, debug)
387
+ else:
388
+ result = df[yc == str(value).strip()]
389
+ debug_step(f"--year {value}", result, debug)
390
+ return result
391
+
392
+
393
+ def filter_complete(df, debug=False):
394
+ result = df[df["assembly_level"].fillna("") == "Complete Genome"]
395
+ debug_step("--complete-only", result, debug)
396
+ return result
397
+
398
+
399
+ def filter_has_kl(df, debug=False):
400
+ mask = df["kl_locus"].notna() & (df["kl_locus"].fillna("").str.len() > 0)
401
+ result = df[mask]
402
+ debug_step("--has-kl", result, debug)
403
+ return result
404
+
405
+
406
+ def filter_has_oxa(df, debug=False):
407
+ mask = df["oxa_variant"].notna() & (df["oxa_variant"].fillna("").str.len() > 0)
408
+ result = df[mask]
409
+ debug_step("--has-oxa", result, debug)
410
+ return result
411
+
412
+
413
+ def filter_min_completeness(df, value, debug=False):
414
+ comp = pd.to_numeric(df["checkm_completeness"], errors="coerce")
415
+ result = df[comp >= float(value)]
416
+ debug_step(f"--min-completeness {value}", result, debug)
417
+ return result
418
+
419
+
420
+ def filter_max_contamination(df, value, debug=False):
421
+ cont = pd.to_numeric(df["checkm_contamination"], errors="coerce")
422
+ result = df[cont <= float(value)]
423
+ debug_step(f"--max-contamination {value}", result, debug)
424
+ return result
425
+
426
+
427
+ # ---------------------------------------------------------------------------
428
+ # Combined typing filters (precomputed columns: combo, ksk, kso)
429
+ # ---------------------------------------------------------------------------
430
+
431
+ def _filter_exact(df, col, value, flag, debug=False):
432
+ v = str(value).strip().upper()
433
+ result = df[df[col].fillna("").str.upper().str.strip() == v]
434
+ debug_step(f"--{flag} {v}", result, debug)
435
+ return result
436
+
437
+
438
+ def filter_combo(df, value, debug=False):
439
+ """Combined typing string ST-KL:OCL (e.g., ST1013-KL171:OCL4)."""
440
+ return _filter_exact(df, "combo", value, "combo", debug)
441
+
442
+
443
+ def filter_ksk(df, value, debug=False):
444
+ """Combined ST-KL pair (e.g., ST1013-KL171; ksk column)."""
445
+ return _filter_exact(df, "ksk", value, "ksk", debug)
446
+
447
+
448
+ def filter_kso(df, value, debug=False):
449
+ """Combined ST-OCL pair (e.g., ST1013-OCL4; kso column)."""
450
+ return _filter_exact(df, "kso", value, "kso", debug)
451
+
452
+
453
+ # ---------------------------------------------------------------------------
454
+ # Gene filters
455
+ # ---------------------------------------------------------------------------
456
+
457
+ def _gene_col(df_gene) -> Optional[str]:
458
+ for c in ["gene", "Gene", "gene_name", "Gene_Name"]:
459
+ if c in df_gene.columns:
460
+ return c
461
+ return None
462
+
463
+
464
+ def _gene_filter(df, gene_path: Path, genes: list[str], match_all: bool,
465
+ debug_label: str, debug: bool):
466
+ if not gene_path.exists() and not gene_path.with_suffix(gene_path.suffix + ".gz").exists():
467
+ log_error(f"Gene table not found: {gene_path}")
468
+ print(f" Reinstall the package to restore bundled data, or set "
469
+ f"ABYSS_DATA_DIR to a complete data directory.", file=sys.stderr)
470
+ sys.exit(1)
471
+ df_gene = read_tsv(gene_path)
472
+ df_gene["accession"] = df_gene["accession"].str.replace(r"\.fna$", "", regex=True)
473
+ gene_col = _gene_col(df_gene)
474
+ if not gene_col:
475
+ log_warn(f"No gene column found in {gene_path.name}")
476
+ return df
477
+
478
+ hit_sets = []
479
+ for g in genes:
480
+ hit_sets.append(set(
481
+ df_gene[df_gene[gene_col].str.contains(g, case=False, na=False)]["accession"]
482
+ ))
483
+
484
+ if match_all:
485
+ # Intersection of all hit sets
486
+ valid = hit_sets[0] if hit_sets else set()
487
+ for s in hit_sets[1:]:
488
+ valid = valid.intersection(s)
489
+ else:
490
+ # Union of all hit sets
491
+ valid = set()
492
+ for s in hit_sets:
493
+ valid = valid.union(s)
494
+ # Restrict to the current filtered dataframe
495
+ result = df[df["accession"].isin(valid)]
496
+ debug_step(debug_label, result, debug)
497
+ return result
498
+
499
+
500
+ def filter_amr(df, data_dir, genes, match_all, debug=False):
501
+ return _gene_filter(
502
+ df, data_dir / "gene_annotations" / "amr_all.tsv",
503
+ [g.strip() for g in genes.split(",")], match_all,
504
+ f"--amr {genes}", debug,
505
+ )
506
+
507
+
508
+ def filter_vfdb(df, data_dir, genes, match_all, debug=False):
509
+ return _gene_filter(
510
+ df, data_dir / "gene_annotations" / "vfdb_all.tsv",
511
+ [g.strip() for g in genes.split(",")], match_all,
512
+ f"--vfdb {genes}", debug,
513
+ )
514
+
515
+
516
+ def filter_plasmid(df, data_dir, genes, match_all, debug=False):
517
+ return _gene_filter(
518
+ df, data_dir / "gene_annotations" / "plasmid_all.tsv",
519
+ [g.strip() for g in genes.split(",")], match_all,
520
+ f"--plasmid {genes}", debug,
521
+ )
522
+
523
+
524
+ def filter_crab(df, data_dir, debug=False):
525
+ """Filter to genomes carrying any acquired carbapenemase."""
526
+ amr_path = data_dir / "gene_annotations" / "amr_all.tsv"
527
+ if not amr_path.exists() and not amr_path.with_suffix(".tsv.gz").exists():
528
+ log_warn("AMR table not found, cannot apply --crab")
529
+ return df
530
+ amr = read_tsv(amr_path)
531
+ amr["accession"] = amr["accession"].str.replace(r"\.fna$", "", regex=True)
532
+ gene_col = _gene_col(amr)
533
+ if not gene_col:
534
+ log_warn("No gene column in AMR table")
535
+ return df
536
+ hits = amr[amr[gene_col].str.contains(CARBAPENEMASE_RE, na=False)]
537
+ crab_accessions = set(hits["accession"])
538
+ result = df[df["accession"].isin(crab_accessions)]
539
+ debug_step(f"--crab ({len(crab_accessions):,} accessions with acquired carbapenemase)", result, debug)
540
+ return result
541
+
542
+ # ---------------------------------------------------------------------------
543
+ # Boolean composition: comma = OR within a flag; --not-* = exclusion
544
+ # ---------------------------------------------------------------------------
545
+
546
+ OR_FN = {
547
+ "st": filter_st, "oxford_st": filter_oxford_st, "ic": filter_ic,
548
+ "kl": filter_kl, "ocl": filter_ocl, "oxa": filter_oxa,
549
+ "combo": filter_combo, "ksk": filter_ksk, "kso": filter_kso,
550
+ "country": filter_country, "continent": filter_continent,
551
+ "region": filter_region, "source": filter_source, "host": filter_host,
552
+ "year": filter_year, "super_group": filter_super_group,
553
+ }
554
+
555
+ GENE_FN = {
556
+ "amr": filter_amr, "vfdb": filter_vfdb, "plasmid": filter_plasmid,
557
+ }
558
+
559
+
560
+ def apply_or(df, fname, value, debug=False):
561
+ """Comma-separated values in a typing/metadata flag are OR-combined."""
562
+ parts = [p.strip() for p in str(value).split(",") if p.strip()]
563
+ if len(parts) <= 1:
564
+ return OR_FN[fname](df, value, debug=debug)
565
+ mask = pd.Series(False, index=df.index)
566
+ for p in parts:
567
+ sub = OR_FN[fname](df, p, debug=debug)
568
+ mask |= df.index.isin(sub.index)
569
+ result = df[mask]
570
+ debug_step("--" + fname.replace("_", "-") + " " + " | ".join(parts), result, debug)
571
+ return result
572
+
573
+
574
+ def apply_not(df, fname, value, data_dir, debug=False):
575
+ """--not-<field>: drop genomes matching ANY listed value."""
576
+ if fname == "crab":
577
+ sub = filter_crab(df, data_dir, debug=debug)
578
+ elif fname in GENE_FN:
579
+ sub = GENE_FN[fname](df, data_dir, str(value), match_all=False, debug=debug)
580
+ else:
581
+ parts = [p.strip() for p in str(value).split(",") if p.strip()]
582
+ mask = pd.Series(False, index=df.index)
583
+ for p in parts:
584
+ s = OR_FN[fname](df, p, debug=debug)
585
+ mask |= df.index.isin(s.index)
586
+ sub = df[mask]
587
+ result = df[~df.index.isin(sub.index)]
588
+ debug_step("--not-" + fname.replace("_", "-") + " " + str(value), result, debug)
589
+ return result
590
+
591
+
592
+ # ---------------------------------------------------------------------------
593
+ # Output serialization
594
+ # ---------------------------------------------------------------------------
595
+
596
+ def serialize(df, fmt):
597
+ if fmt == "accession":
598
+ return "\n".join(df["accession"].tolist())
599
+ if fmt == "tsv":
600
+ return df.to_csv(sep="\t", index=False)
601
+ if fmt == "csv":
602
+ return df.to_csv(index=False)
603
+ if fmt == "json":
604
+ return df.to_json(orient="records", indent=2, force_ascii=False)
605
+ if fmt in ("biosample", "bioproject"):
606
+ col = "biosample" if fmt == "biosample" else "bioproject"
607
+ if col not in df.columns:
608
+ return ""
609
+ seen = set()
610
+ for val in df[col].dropna():
611
+ for piece in str(val).split(","):
612
+ piece = piece.strip()
613
+ if piece and piece != "NA":
614
+ seen.add(piece)
615
+ return "\n".join(sorted(seen)) + "\n" if seen else ""
616
+ raise ValueError(f"Unknown format: {fmt}")
617
+
618
+
619
+ def resolve_output_paths(base_output, formats):
620
+ p = Path(base_output)
621
+ for ext in EXT_MAP.values():
622
+ if p.suffix == ext:
623
+ p = p.with_suffix("")
624
+ break
625
+ return {fmt: Path(str(p) + EXT_MAP[fmt]) for fmt in formats}
626
+
627
+
628
+ def print_footer(quiet=False, count_mode=False):
629
+ if quiet:
630
+ return
631
+ line = f"{C.GRAY}{'─' * 76}{C.RESET}"
632
+ print("", file=sys.stderr)
633
+ print(line, file=sys.stderr)
634
+ if count_mode:
635
+ print(f"{C.CYAN} 🧬 https://abyss-db.org/ · abyss --about · abyss --help{C.RESET}",
636
+ file=sys.stderr)
637
+ else:
638
+ print(f"{C.GOLD}{C.BOLD} 🧬 ABYSS-CLI{C.RESET} {C.DIM}· {__affiliation__}{C.RESET}",
639
+ file=sys.stderr)
640
+ print(f"{C.CYAN} 🌐 Web {C.RESET}https://abyss-db.org/", file=sys.stderr)
641
+ print(f"{C.GOLD} ⭐ Star {C.RESET}https://github.com/bbeckley-hub/abyss-db-cli",
642
+ file=sys.stderr)
643
+ print(f"{C.RED} 🐛 Bugs {C.RESET}https://github.com/bbeckley-hub/abyss-db-cli/issues",
644
+ file=sys.stderr)
645
+ print(f"{C.CYAN} 📚 Docs {C.RESET}abyss --examples · abyss --about · abyss --list <field>",
646
+ file=sys.stderr)
647
+ print(line, file=sys.stderr)
648
+
649
+
650
+ # ---------------------------------------------------------------------------
651
+ # Help / examples / about text
652
+ # ---------------------------------------------------------------------------
653
+
654
+ HELP_EPILOG = f"""
655
+ {CO.GOLD}{CO.BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{CO.RESET}
656
+ {CO.GOLD}{CO.BOLD} ⚡ QUICK EXAMPLES{CO.RESET}
657
+ {CO.GOLD}{CO.BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{CO.RESET}
658
+
659
+ {CO.CYAN} Count IC2 (Global Clone 2) genomes:{CO.RESET}
660
+ $ abyss --ic IC2 --count
661
+
662
+ {CO.CYAN} Carbapenem-resistant A. baumannii in Europe:{CO.RESET}
663
+ $ abyss --crab --continent Europe --count
664
+
665
+ {CO.CYAN} OXA-23 producers in China:{CO.RESET}
666
+ $ abyss --amr blaOXA-23 --country China --count
667
+
668
+ {CO.CYAN} Export GC2 bloodstream isolates:{CO.RESET}
669
+ $ abyss --lineage GC2 --source blood -o gc2_blood.txt
670
+
671
+ {CO.CYAN} Filter by capsule type:{CO.RESET}
672
+ $ abyss --kl KL2 --count
673
+
674
+ {CO.CYAN} Boolean: IC1 or IC2, excluding NDM carriers:{CO.RESET}
675
+ $ abyss --ic IC1,IC2 --not-amr blaNDM --count
676
+
677
+ {CO.CYAN} Combined typing (ST-K, ST-O, ST-K:O) query:{CO.RESET}
678
+ $ abyss --combo ST1013-KL171:OCL4 --count
679
+ $ abyss --ksk ST1013-KL171 --count
680
+ $ abyss --kso ST1013-OCL4 --count
681
+
682
+ {CO.CYAN} List available values for a field:{CO.RESET}
683
+ $ abyss --list ic
684
+ $ abyss --list oxa
685
+ $ abyss --list combo
686
+
687
+ {CO.GOLD}{CO.BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{CO.RESET}
688
+ {CO.GOLD}{CO.BOLD} 📚 MORE INFORMATION{CO.RESET}
689
+ {CO.GOLD}{CO.BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{CO.RESET}
690
+
691
+ abyss --examples Full gallery of example queries
692
+ abyss --about Author, affiliation, citations, and links
693
+ abyss --list FIELD List unique values in a column (ic, oxa, kl, combo, ...)
694
+ abyss --version CLI version and data version
695
+ """
696
+
697
+ EXAMPLES_GALLERY = f"""
698
+ {CO.CYAN}{CO.BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{CO.RESET}
699
+ {CO.CYAN}{CO.BOLD} 🧬 ABYSS CLI — Example Queries{CO.RESET}
700
+ {CO.GRAY} Copy-paste these into your terminal.{CO.RESET}
701
+ {CO.CYAN}{CO.BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{CO.RESET}
702
+
703
+ {CO.GOLD}{CO.BOLD} 📊 Counting genomes{CO.RESET}
704
+ {CO.GRAY} ─────────────────────────────────────────────────────────────{CO.RESET}
705
+
706
+ {CO.CYAN}$ abyss --ic IC2 --count{CO.RESET}
707
+ {CO.CYAN}$ abyss --crab --count{CO.RESET}
708
+ {CO.CYAN}$ abyss --amr blaOXA-23 --continent Asia --count{CO.RESET}
709
+ {CO.CYAN}$ abyss --kl KL2 --count{CO.RESET}
710
+
711
+ {CO.GOLD}{CO.BOLD} 📤 Exporting accessions{CO.RESET}
712
+ {CO.GRAY} ─────────────────────────────────────────────────────────────{CO.RESET}
713
+
714
+ {CO.CYAN}$ abyss --ic IC2 -o ic2.txt{CO.RESET}
715
+ {CO.CYAN}$ abyss --crab --format tsv,accession -o crab_results{CO.RESET}
716
+ {CO.CYAN}$ abyss --amr blaOXA-23 --format csv,json,accession -o oxa23{CO.RESET}
717
+
718
+ {CO.GOLD}{CO.BOLD} 🧬 Typing filters{CO.RESET}
719
+ {CO.GRAY} ─────────────────────────────────────────────────────────────{CO.RESET}
720
+
721
+ {CO.CYAN}$ abyss --st 2 --count{CO.RESET}
722
+ {CO.CYAN}$ abyss --oxford-st 208 --count{CO.RESET}
723
+ {CO.CYAN}$ abyss --ic IC5 --count{CO.RESET}
724
+ {CO.CYAN}$ abyss --kl KL49 --ocl OCL10 --count{CO.RESET}
725
+
726
+ {CO.GOLD}{CO.BOLD} 🔗 Combined typing (ST-KL:OCL, ST-KL, ST-OCL){CO.RESET}
727
+ {CO.GRAY} ─────────────────────────────────────────────────────────────{CO.RESET}
728
+
729
+ {CO.CYAN}$ abyss --combo ST1013-KL171:OCL4 --count{CO.RESET}
730
+ {CO.CYAN}$ abyss --ksk ST1013-KL171,ST1013-KL201 --count{CO.RESET}
731
+ {CO.CYAN}$ abyss --kso ST1013-OCL4 --count{CO.RESET}
732
+ {CO.GRAY} Full triple: --combo ST-KL:OCL. ST-KL pair: --ksk.{CO.RESET}
733
+ {CO.GRAY} ST-OCL pair: --kso. Run abyss --list combo / ksk / kso{CO.RESET}
734
+ {CO.GRAY} to see stored values. Comma = OR within each flag.{CO.RESET}
735
+
736
+ {CO.GOLD}{CO.BOLD} 🌍 Geography and source{CO.RESET}
737
+ {CO.GRAY} ─────────────────────────────────────────────────────────────{CO.RESET}
738
+
739
+ {CO.CYAN}$ abyss --continent Europe --count{CO.RESET}
740
+ {CO.CYAN}$ abyss --country Brazil --source blood --count{CO.RESET}
741
+ {CO.CYAN}$ abyss --region "Sao Paulo" --count{CO.RESET}
742
+ {CO.CYAN}$ abyss --super-group "ICU" --count{CO.RESET}
743
+
744
+ {CO.GOLD}{CO.BOLD} 💊 Resistance and gene content{CO.RESET}
745
+ {CO.GRAY} ─────────────────────────────────────────────────────────────{CO.RESET}
746
+
747
+ {CO.CYAN}$ abyss --crab --count{CO.RESET}
748
+ {CO.CYAN}$ abyss --amr blaNDM --count{CO.RESET}
749
+ {CO.CYAN}$ abyss --amr blaOXA-23,blaOXA-24 --any --count{CO.RESET}
750
+ {CO.CYAN}$ abyss --plasmid IncP1 --count{CO.RESET}
751
+
752
+ {CO.GOLD}{CO.BOLD} ⚙️ Quality filters{CO.RESET}
753
+ {CO.GRAY} ─────────────────────────────────────────────────────────────{CO.RESET}
754
+
755
+ {CO.CYAN}$ abyss --complete-only --count{CO.RESET}
756
+ {CO.CYAN}$ abyss --min-completeness 95 --count{CO.RESET}
757
+ {CO.CYAN}$ abyss --complete-only --max-contamination 2 --count{CO.RESET}
758
+
759
+ {CO.GOLD}{CO.BOLD} 🏷 Lineage shortcuts{CO.RESET}
760
+ {CO.GRAY} ─────────────────────────────────────────────────────────────{CO.RESET}
761
+
762
+ GC1 · GC2 · IC1 · IC2 · IC3 · IC4 · IC5 · IC6 · IC7 · IC8 · IC9
763
+ ST25 · ST92 · ST195 · ST208 · ST218 (Oxford scheme)
764
+
765
+ {CO.CYAN}$ abyss --lineage GC2 --country "United States" --count{CO.RESET}
766
+
767
+ {CO.GRAY} GC1 and GC2 are aliases for IC1 and IC2, the historical names for the{CO.RESET}
768
+ {CO.GRAY} two pandemic global clones. ST25, ST92, ST195, ST208, and ST218 use{CO.RESET}
769
+ {CO.GRAY} the Oxford MLST scheme; --st uses the Pasteur scheme.{CO.RESET}
770
+
771
+ {CO.GOLD}{CO.BOLD} 🔍 Exploring the data{CO.RESET}
772
+ {CO.GRAY} ─────────────────────────────────────────────────────────────{CO.RESET}
773
+
774
+ {CO.CYAN}$ abyss --list ic{CO.RESET}
775
+ {CO.CYAN}$ abyss --list oxa{CO.RESET}
776
+ {CO.CYAN}$ abyss --list kl{CO.RESET}
777
+ {CO.CYAN}$ abyss --list combo{CO.RESET}
778
+ {CO.CYAN}$ abyss --list ksk{CO.RESET}
779
+ {CO.CYAN}$ abyss --list kso{CO.RESET}
780
+ {CO.CYAN}$ abyss --list continent{CO.RESET}
781
+ {CO.CYAN}$ abyss --list source{CO.RESET}
782
+ {CO.CYAN}$ abyss --list country{CO.RESET}
783
+ """
784
+
785
+
786
+ ABOUT_TEXT = f"""
787
+ {CO.CYAN}{CO.BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{CO.RESET}
788
+
789
+ {CO.CYAN}Author:{CO.RESET} {__author__}
790
+ {CO.CYAN}Affiliation:{CO.RESET} {__affiliation__}
791
+ {CO.CYAN}License:{CO.RESET} {__license__}
792
+ {CO.CYAN}Version:{CO.RESET} v{__version__}
793
+
794
+ {CO.GOLD}{CO.BOLD} 📖 About ABYSS{CO.RESET}
795
+ {CO.GRAY} ─────────────────────────────────────────────────────────────{CO.RESET}
796
+
797
+ ABYSS (Acinetobacter baumannii Yielding Surveillance System) is part
798
+ of the
799
+ ARGUS initiative for ESKAPE pathogen surveillance. It provides
800
+ interactive access to typing, gene annotation, and epidemiological
801
+ metadata for A. baumannii genomes from the NCBI Assembly database.
802
+
803
+ Data are typed with a species-optimized pipeline that covers both
804
+ MLST schemes (Pasteur and Oxford), Kaptive capsule typing (KL and
805
+ OCL), OXA variant identification, and gene content from standard
806
+ databases (AMR, VFDB, PlasmidFinder).
807
+
808
+ {CO.GOLD}{CO.BOLD} 🔗 Links{CO.RESET}
809
+ {CO.GRAY} ─────────────────────────────────────────────────────────────{CO.RESET}
810
+
811
+ {CO.CYAN}🌐 Web platform:{CO.RESET} https://abyss-db.org/
812
+ {CO.CYAN}📦 PyPI:{CO.RESET} https://pypi.org/project/abyss-db-cli/
813
+ {CO.CYAN}📚 CLI repo:{CO.RESET} https://github.com/bbeckley-hub/abyss-db-cli
814
+ {CO.CYAN}🧬 ARGUS umbrella:{CO.RESET} https://argus-db.org/
815
+ {CO.CYAN}🐛 Report bugs:{CO.RESET} https://github.com/bbeckley-hub/abyss-db-cli/issues
816
+ """
817
+
818
+
819
+ # ---------------------------------------------------------------------------
820
+ # --version
821
+ # ---------------------------------------------------------------------------
822
+
823
+ def _version_str():
824
+ base = f"ABYSS-CLI v{__version__} — {__affiliation__}"
825
+ try:
826
+ d = find_data_dir()
827
+ if d:
828
+ manifest = read_manifest(d)
829
+ version = None
830
+ vf = d / "DATA_VERSION"
831
+ if vf.exists():
832
+ version = vf.read_text().strip()
833
+ if not version:
834
+ version = manifest.get("version") or manifest.get("data_version") or "unknown"
835
+ count = manifest.get("genome_count") or manifest.get("total_genomes")
836
+ date = manifest.get("release_date") or manifest.get("date")
837
+ bits = [f"Data version: {version}"]
838
+ if count:
839
+ bits.append(f"{int(count):,} genomes")
840
+ if date:
841
+ bits.append(str(date))
842
+ base += f"\n {' · '.join(bits)} ({d})"
843
+ except Exception:
844
+ pass
845
+ return base
846
+
847
+
848
+ # ---------------------------------------------------------------------------
849
+ # --list command
850
+ # ---------------------------------------------------------------------------
851
+
852
+ LIST_FIELDS = {
853
+ "ic": "mlst_ic",
854
+ "oxa": "oxa_variant",
855
+ "kl": "kl_locus",
856
+ "ocl": "ocl_locus",
857
+ "st": "mlst_st",
858
+ "oxford_st": "mlst_st_oxford",
859
+ "combo": "combo",
860
+ "ksk": "ksk",
861
+ "kso": "kso",
862
+ "country": "country",
863
+ "continent": "continent",
864
+ "region": "region",
865
+ "source": "source",
866
+ "host": "host",
867
+ "super_group": "super_group",
868
+ "year": "year",
869
+ "assembly_level": "assembly_level",
870
+ "refseq_category": "refseq_category",
871
+ }
872
+
873
+
874
+ def cmd_list(field: str, data_dir: Path, top: int = 50) -> int:
875
+ col = LIST_FIELDS.get(field.lower())
876
+ if not col:
877
+ log_error(f"Unknown field '{field}'.")
878
+ print(f" Available: {', '.join(sorted(LIST_FIELDS))}", file=sys.stderr)
879
+ return 1
880
+ df = load_master(data_dir)
881
+ if col not in df.columns:
882
+ log_error(f"Column '{col}' not found in master table.")
883
+ return 1
884
+ values = df[col].fillna("").astype(str).str.strip()
885
+ values = values[values != ""]
886
+ counts = values.value_counts()
887
+ print(f"{field}: {len(counts):,} unique values")
888
+ print("─" * 60)
889
+ for value, count in counts.head(top).items():
890
+ print(f" {value:<40} {count:>10,}")
891
+ if len(counts) > top:
892
+ print(f" ... and {len(counts) - top:,} more")
893
+ return 0
894
+
895
+
896
+ # ---------------------------------------------------------------------------
897
+ # `abyss init` subcommand
898
+ # ---------------------------------------------------------------------------
899
+
900
+ def _download_with_progress(url: str, dest: Path) -> None:
901
+ """Download a URL to dest, printing a progress bar to stderr."""
902
+ print(f"{C.CYAN}📥{C.RESET} Downloading...", file=sys.stderr)
903
+ last_pct = -1
904
+
905
+ def _hook(blocks, block_size, total_size):
906
+ nonlocal last_pct
907
+ if total_size <= 0:
908
+ return
909
+ downloaded = blocks * block_size
910
+ pct = int(100 * downloaded / total_size)
911
+ if pct != last_pct and pct % 5 == 0:
912
+ mb_done = downloaded / 1_048_576
913
+ mb_total = total_size / 1_048_576
914
+ bar_len = 30
915
+ filled = int(bar_len * pct / 100)
916
+ bar = "\u2588" * filled + "\u2591" * (bar_len - filled)
917
+ print(
918
+ f" {C.CYAN}{bar}{C.RESET} {pct:3d}% "
919
+ f"({mb_done:.1f}/{mb_total:.1f} MB)",
920
+ file=sys.stderr,
921
+ end="\r",
922
+ )
923
+ last_pct = pct
924
+
925
+ urllib.request.urlretrieve(url, str(dest), reporthook=_hook)
926
+ print("", file=sys.stderr)
927
+
928
+
929
+ def _sha256(path: Path) -> str:
930
+ """Return the hex SHA256 digest of a file."""
931
+ h = hashlib.sha256()
932
+ with open(path, "rb") as f:
933
+ for chunk in iter(lambda: f.read(1 << 20), b""):
934
+ h.update(chunk)
935
+ return h.hexdigest()
936
+
937
+
938
+ def _latest_data_tag() -> Optional[str]:
939
+ """Return the newest release tag for this CLI's data product.
940
+
941
+ The argus-data repo hosts data releases for several ARGUS products, so
942
+ the repo-wide 'latest' release is not necessarily an ABYSS one; products
943
+ are namespaced by tag prefix (e.g. 'abyss-data-v1.0.0')."""
944
+ url = f"https://api.github.com/repos/{DATA_REPO}/releases?per_page=100"
945
+ try:
946
+ req = urllib.request.Request(
947
+ url, headers={"Accept": "application/vnd.github+json"}
948
+ )
949
+ with urllib.request.urlopen(req, timeout=30) as r:
950
+ releases = json.load(r)
951
+ except Exception:
952
+ return None
953
+ for rel in releases:
954
+ tag = rel.get("tag_name", "")
955
+ if tag.startswith(DATA_TAG_PREFIX):
956
+ return tag
957
+ return None
958
+
959
+
960
+ def _resolve_data_url(version: Optional[str]) -> tuple[str, str]:
961
+ """Return (zip_url, sha256_url) for the requested data version."""
962
+ if version and version.lower() not in ("latest", "main"):
963
+ tag = version.strip()
964
+ if not tag.startswith("v") and not tag.startswith(DATA_TAG_PREFIX):
965
+ tag = "v" + tag
966
+ if not tag.startswith(DATA_TAG_PREFIX):
967
+ tag = DATA_TAG_PREFIX + tag
968
+ base = (f"https://github.com/{DATA_REPO}/releases/download/"
969
+ f"{tag}/{DATA_ASSET_NAME}")
970
+ return base, f"{base}.sha256"
971
+ tag = _latest_data_tag()
972
+ if tag:
973
+ base = (f"https://github.com/{DATA_REPO}/releases/download/"
974
+ f"{tag}/{DATA_ASSET_NAME}")
975
+ return base, f"{base}.sha256"
976
+ base = (f"https://github.com/{DATA_REPO}/releases/latest/download/"
977
+ f"{DATA_ASSET_NAME}")
978
+ return base, f"{base}.sha256"
979
+
980
+
981
+ def _resolve_init_target(output: Optional[str]) -> Path:
982
+ """Decide where `abyss init` should write.
983
+
984
+ Prefers an existing writable data directory (so updates overwrite in
985
+ place). Read-only locations are skipped, falling through to the
986
+ ~/.abyss/data default."""
987
+ if output:
988
+ return Path(output).expanduser().resolve()
989
+
990
+ env_dir = os.environ.get("ABYSS_DATA_DIR")
991
+ if env_dir:
992
+ return Path(env_dir).expanduser().resolve()
993
+
994
+ for candidate in _get_candidates():
995
+ try:
996
+ has_data = (
997
+ (candidate / "master" / "abyss_all.tsv").exists()
998
+ or (candidate / "master" / "abyss_all.tsv.gz").exists()
999
+ )
1000
+ if has_data and os.access(candidate, os.W_OK):
1001
+ return candidate
1002
+ except (OSError, PermissionError):
1003
+ continue
1004
+
1005
+ return Path.home() / ".abyss" / "data"
1006
+
1007
+
1008
+ def _installed_data_version(target: Path) -> str:
1009
+ """Installed data version: DATA_VERSION file first, then the manifest."""
1010
+ vf = target / "DATA_VERSION"
1011
+ if vf.exists():
1012
+ return vf.read_text().strip() or "unknown"
1013
+ manifest = read_manifest(target)
1014
+ return manifest.get("version") or manifest.get("data_version") or "unknown"
1015
+
1016
+
1017
+ def cmd_init(argv):
1018
+ """Handle the `abyss init` subcommand."""
1019
+ output: Optional[str] = None
1020
+ version: Optional[str] = None
1021
+ force = False
1022
+ from_file: Optional[Path] = None
1023
+ quiet = False
1024
+ allow_unverified = "--allow-unverified" in argv
1025
+
1026
+ i = 0
1027
+ while i < len(argv):
1028
+ a = argv[i]
1029
+ if a in ("-o", "--output", "--path", "--data-dir"):
1030
+ output = argv[i + 1]
1031
+ i += 2
1032
+ elif a in ("-v", "--version"):
1033
+ version = argv[i + 1]
1034
+ i += 2
1035
+ elif a in ("-f", "--from-file"):
1036
+ from_file = Path(argv[i + 1]).expanduser()
1037
+ i += 2
1038
+ elif a in ("--force", "--allow-unverified"):
1039
+ if a == "--force":
1040
+ force = True
1041
+ i += 1
1042
+ elif a in ("-q", "--quiet"):
1043
+ quiet = True
1044
+ i += 1
1045
+ elif a in ("-h", "--help"):
1046
+ print("""Usage: abyss init [OPTIONS]
1047
+
1048
+ Download or refresh the ABYSS data bundle.
1049
+
1050
+ Where does it write?
1051
+ 1. --output <path>
1052
+ 2. $ABYSS_DATA_DIR
1053
+ 3. Existing writable data location
1054
+ 4. ~/.abyss/data (default for new installs)
1055
+
1056
+ Options:
1057
+ -o, --output PATH Install to PATH (default: auto)
1058
+ -v, --version VERSION Specific data version (default: latest); re-downloads
1059
+ even when data is already installed
1060
+ -f, --from-file ZIP Install from a local zip. The companion ZIP.sha256
1061
+ must exist and match, otherwise the install is
1062
+ refused.
1063
+ --force Overwrite without asking
1064
+ --allow-unverified Proceed without checksum verification when the
1065
+ checksum file is missing or cannot be downloaded
1066
+ (checksum mismatch is always fatal)
1067
+ -q, --quiet Suppress banner
1068
+ """)
1069
+ return 0
1070
+ else:
1071
+ i += 1
1072
+
1073
+ target = _resolve_init_target(output)
1074
+
1075
+ if not quiet:
1076
+ print_banner(quiet=False)
1077
+
1078
+ master_tsv = target / "master" / "abyss_all.tsv"
1079
+ master_gz = target / "master" / "abyss_all.tsv.gz"
1080
+ has_data = master_tsv.exists() or master_gz.exists()
1081
+
1082
+ if has_data and not force and from_file is None and version is None:
1083
+ print(f"{C.GREEN}\u2713{C.RESET} Data already installed at {target}",
1084
+ file=sys.stderr)
1085
+ print(f" Installed version: {_installed_data_version(target)}",
1086
+ file=sys.stderr)
1087
+ print(
1088
+ f" Use {C.CYAN}--force{C.RESET} to reinstall, "
1089
+ f"or {C.CYAN}-v <version>{C.RESET} to install a specific version.",
1090
+ file=sys.stderr,
1091
+ )
1092
+ print_footer(quiet, count_mode=True)
1093
+ return 0
1094
+
1095
+ target.mkdir(parents=True, exist_ok=True)
1096
+ tmp_zip: Optional[Path] = None
1097
+
1098
+ try:
1099
+ if from_file is not None:
1100
+ if not from_file.exists():
1101
+ log_error(f"Local zip not found: {from_file}")
1102
+ return 1
1103
+ zip_path = from_file
1104
+ print(f"{C.CYAN}\U0001F4E6{C.RESET} Installing from local file: "
1105
+ f"{zip_path}", file=sys.stderr)
1106
+ sidecar = Path(str(from_file) + ".sha256")
1107
+ if sidecar.exists():
1108
+ expected = sidecar.read_text().split()[0].strip()
1109
+ actual = _sha256(zip_path)
1110
+ if expected.lower() != actual.lower():
1111
+ log_error("Checksum mismatch \u2014 file may be corrupted")
1112
+ return 1
1113
+ print(f"{C.GREEN}\u2713{C.RESET} Checksum verified",
1114
+ file=sys.stderr)
1115
+ elif allow_unverified:
1116
+ log_warn(
1117
+ f"No checksum sidecar ({sidecar.name}) \u2014 proceeding "
1118
+ "without verification (--allow-unverified)"
1119
+ )
1120
+ else:
1121
+ log_error(f"No checksum sidecar ({sidecar.name}) \u2014 "
1122
+ "refusing to install")
1123
+ print(
1124
+ f" Create it with: {C.CYAN}sha256sum {zip_path} > "
1125
+ f"{sidecar}{C.RESET}",
1126
+ file=sys.stderr,
1127
+ )
1128
+ print(
1129
+ f" Or re-run with {C.CYAN}--allow-unverified{C.RESET} "
1130
+ "to install without verification.",
1131
+ file=sys.stderr,
1132
+ )
1133
+ return 1
1134
+ else:
1135
+ zip_url, sha_url = _resolve_data_url(version)
1136
+ print(f"{C.CYAN}\U0001F4E5{C.RESET} Downloading ABYSS data",
1137
+ file=sys.stderr)
1138
+ print(f" {C.DIM}URL: {zip_url}{C.RESET}", file=sys.stderr)
1139
+ print(f" {C.DIM}Target: {target}{C.RESET}", file=sys.stderr)
1140
+ print("", file=sys.stderr)
1141
+
1142
+ tmp_dir = Path(tempfile.mkdtemp(prefix="abyss-init-"))
1143
+ zip_path = tmp_dir / DATA_ASSET_NAME
1144
+
1145
+ try:
1146
+ _download_with_progress(zip_url, zip_path)
1147
+ except urllib.error.HTTPError as e:
1148
+ log_error(f"Download failed: HTTP {e.code}")
1149
+ if e.code == 404:
1150
+ print(" The release or asset does not exist.",
1151
+ file=sys.stderr)
1152
+ print(f" Check: https://github.com/{DATA_REPO}/releases",
1153
+ file=sys.stderr)
1154
+ return 1
1155
+ except Exception as e:
1156
+ log_error(f"Download failed: {e}")
1157
+ return 1
1158
+
1159
+ try:
1160
+ with urllib.request.urlopen(sha_url, timeout=30) as r:
1161
+ expected = r.read().decode().split()[0].strip()
1162
+ actual = _sha256(zip_path)
1163
+ if expected.lower() != actual.lower():
1164
+ log_error("Checksum mismatch \u2014 download may be corrupted")
1165
+ return 1
1166
+ print(f"{C.GREEN}\u2713{C.RESET} Checksum verified",
1167
+ file=sys.stderr)
1168
+ except Exception:
1169
+ if allow_unverified:
1170
+ log_warn("Checksum not available \u2014 proceeding "
1171
+ "(--allow-unverified)")
1172
+ else:
1173
+ log_error("Checksum file could not be downloaded \u2014 "
1174
+ "aborting")
1175
+ print(
1176
+ f" Re-run with {C.CYAN}--allow-unverified{C.RESET} "
1177
+ f"to skip checksum verification.",
1178
+ file=sys.stderr,
1179
+ )
1180
+ return 1
1181
+
1182
+ tmp_zip = zip_path
1183
+
1184
+ print(f"{C.CYAN}\U0001F4C2{C.RESET} Extracting...", file=sys.stderr)
1185
+ with zipfile.ZipFile(zip_path, "r") as z:
1186
+ names = z.namelist()
1187
+ z.extractall(target)
1188
+
1189
+ installed_version = _installed_data_version(target)
1190
+
1191
+ if not master_tsv.exists() and not master_gz.exists():
1192
+ log_error("Zip extracted, but master/abyss_all.tsv is missing")
1193
+ return 1
1194
+
1195
+ n_files = len([n for n in names if not n.endswith("/")])
1196
+ total_bytes = sum((target / n).stat().st_size
1197
+ for n in names if (target / n).is_file())
1198
+ total_mb = total_bytes / 1_048_576
1199
+
1200
+ print(
1201
+ f"{C.GREEN}\u2713{C.RESET} Data installed \u2192 {target}\n"
1202
+ f" Version: {installed_version}\n"
1203
+ f" Files: {n_files}\n"
1204
+ f" Size: {total_mb:.1f} MB",
1205
+ file=sys.stderr,
1206
+ )
1207
+ print_footer(quiet, count_mode=True)
1208
+ return 0
1209
+
1210
+ except zipfile.BadZipFile:
1211
+ log_error("Downloaded file is not a valid zip")
1212
+ return 1
1213
+ except Exception as e:
1214
+ log_error(f"Unexpected error: {e}")
1215
+ return 1
1216
+ finally:
1217
+ if tmp_zip and tmp_zip.exists():
1218
+ try:
1219
+ tmp_zip.unlink()
1220
+ tmp_zip.parent.rmdir()
1221
+ except Exception:
1222
+ pass
1223
+
1224
+
1225
+ # ---------------------------------------------------------------------------
1226
+ # Main
1227
+ # ---------------------------------------------------------------------------
1228
+
1229
+ def main(argv=None):
1230
+ if argv is None:
1231
+ argv = sys.argv[1:]
1232
+
1233
+ if argv and argv[0] in ("init", "setup"):
1234
+ sys.exit(cmd_init(argv[1:]))
1235
+
1236
+ parser = argparse.ArgumentParser(
1237
+ description="ABYSS CLI — query A. baumannii genomes from your terminal.",
1238
+ epilog=HELP_EPILOG,
1239
+ formatter_class=argparse.RawDescriptionHelpFormatter,
1240
+ )
1241
+
1242
+ parser.add_argument("--config", "-c", help="JSON config file with query parameters.")
1243
+ parser.add_argument("--data-dir", default=None,
1244
+ help="Path to ABYSS data directory (default: auto-detect)")
1245
+ parser.add_argument("--debug", action="store_true", help="Show row counts after each filter.")
1246
+ parser.add_argument("--lineage",
1247
+ help="Pre-defined lineage shortcut (GC1, GC2, IC1-IC9, ST25, ST92, ST195, ST208, ST218)")
1248
+ parser.add_argument("--quiet", "-q", action="store_true",
1249
+ help="Suppress banner and footer.")
1250
+ parser.add_argument("--examples", action="store_true",
1251
+ help="Print example gallery and exit.")
1252
+ parser.add_argument("--about", action="store_true",
1253
+ help="Print author and citation info and exit.")
1254
+ parser.add_argument("--list", metavar="FIELD",
1255
+ help="List unique values for a field and exit. "
1256
+ "Fields: ic, oxa, kl, ocl, st, oxford_st, combo, ksk, kso, "
1257
+ "country, continent, region, source, host, super_group, year, "
1258
+ "assembly_level, refseq_category.")
1259
+ parser.add_argument("--version", action="version", version=_version_str())
1260
+
1261
+ grp_type = parser.add_argument_group("Typing filters")
1262
+ grp_type.add_argument("--st", help="MLST Pasteur sequence type (e.g., 2)")
1263
+ grp_type.add_argument("--oxford-st", help="MLST Oxford sequence type (e.g., 208)")
1264
+ grp_type.add_argument("--ic", help="International clone (IC1-IC9)")
1265
+ grp_type.add_argument("--kl", help="K-locus capsule (e.g., KL2, KL49)")
1266
+ grp_type.add_argument("--ocl", help="OC-locus (e.g., OCL1, OCL5)")
1267
+ grp_type.add_argument("--oxa", help="Intrinsic OXA variant (e.g., OXA-66, OXA-69); acquired carbapenemases such as OXA-23 are queried with --amr")
1268
+ grp_type.add_argument("--combo", help="Combined typing string ST-KL:OCL (e.g., ST1013-KL171:OCL4), exact match; comma = OR; see abyss --list combo")
1269
+ grp_type.add_argument("--ksk", help="Combined ST-KL pair (e.g., ST1013-KL171), exact match; comma = OR; see abyss --list ksk")
1270
+ grp_type.add_argument("--kso", help="Combined ST-OCL pair (e.g., ST1013-OCL4), exact match; comma = OR; see abyss --list kso")
1271
+
1272
+ grp_meta = parser.add_argument_group("Epidemiological metadata")
1273
+ grp_meta.add_argument("--country", help="Country of origin")
1274
+ grp_meta.add_argument("--continent", help="Continent (Europe, Asia, Africa, ...)")
1275
+ grp_meta.add_argument("--region", help="Region or sub-country location")
1276
+ grp_meta.add_argument("--source", help="Isolation source (e.g., blood, urine)")
1277
+ grp_meta.add_argument("--host", help="Host species")
1278
+ grp_meta.add_argument("--year", help="Collection year or range (e.g., 2019, 2015-2023)")
1279
+ grp_meta.add_argument("--super-group", help="Super-group label (e.g., ICU, Environmental)")
1280
+
1281
+ grp_gene = parser.add_argument_group("Gene content")
1282
+ grp_gene.add_argument("--amr", help="AMR gene(s), comma-separated")
1283
+ grp_gene.add_argument("--vfdb", help="Virulence gene(s), comma-separated")
1284
+ grp_gene.add_argument("--plasmid", help="Plasmid replicon(s), comma-separated")
1285
+ grp_gene.add_argument("--any", action="store_true",
1286
+ help="Match ANY of the given genes (default: ALL)")
1287
+ grp_gene.add_argument("--crab", action="store_true",
1288
+ help="Carbapenem-resistant: has any acquired carbapenemase "
1289
+ "(OXA-23, OXA-24/40, OXA-58, NDM, KPC, etc.)")
1290
+
1291
+ grp_qc = parser.add_argument_group("Quality filters")
1292
+ grp_qc.add_argument("--complete-only", action="store_true",
1293
+ help="Only complete genomes (assembly_level == 'Complete Genome')")
1294
+ grp_qc.add_argument("--min-completeness", type=float,
1295
+ help="Minimum CheckM completeness (genomes without CheckM are excluded)")
1296
+ grp_qc.add_argument("--max-contamination", type=float,
1297
+ help="Maximum CheckM contamination (genomes without CheckM are excluded)")
1298
+ grp_qc.add_argument("--has-kl", action="store_true",
1299
+ help="Only genomes with a Kaptive KL result")
1300
+ grp_qc.add_argument("--has-oxa", action="store_true",
1301
+ help="Only genomes with an OXA variant called")
1302
+
1303
+ grp_bool = parser.add_argument_group(
1304
+ "Boolean logic (comma = OR within a flag; --not-* excludes)",
1305
+ "Filters combine with AND. Commas in one filter mean OR "
1306
+ "(e.g., --ic IC1,IC2). --not-<field> drops genomes matching ANY "
1307
+ "listed value (e.g., --not-amr blaNDM,blaOXA-23).")
1308
+ for _bf in ("st", "oxford_st", "ic", "kl", "ocl", "oxa",
1309
+ "combo", "ksk", "kso",
1310
+ "country", "continent", "region", "source", "host", "year",
1311
+ "super_group", "amr", "vfdb", "plasmid"):
1312
+ grp_bool.add_argument(
1313
+ "--not-" + _bf.replace("_", "-"),
1314
+ dest="not_" + _bf, default=None,
1315
+ help="Exclude genomes whose --" + _bf.replace("_", "-") +
1316
+ " matches any listed value (comma = OR)")
1317
+ grp_bool.add_argument("--not-crab", dest="not_crab", action="store_true",
1318
+ help="Exclude genomes carrying any acquired carbapenemase")
1319
+
1320
+ grp_out = parser.add_argument_group("Output options")
1321
+ grp_out.add_argument("--format", "-f", default="accession",
1322
+ help="Output format(s), comma-separated: accession, tsv, csv, json, "
1323
+ "biosample, bioproject. Default: accession.")
1324
+ grp_out.add_argument("--output", "-o", default="stdout",
1325
+ help="Output base path (extension added per format)")
1326
+ grp_out.add_argument("--count", action="store_true",
1327
+ help="Only print the number of matching genomes")
1328
+
1329
+ args = parser.parse_args(argv)
1330
+
1331
+ # Short-circuit flags
1332
+ if args.examples:
1333
+ print_banner(quiet=args.quiet)
1334
+ print(EXAMPLES_GALLERY)
1335
+ print_footer(args.quiet, count_mode=True)
1336
+ sys.exit(0)
1337
+ if args.about:
1338
+ print_banner(quiet=args.quiet)
1339
+ print(ABOUT_TEXT)
1340
+ print_footer(args.quiet, count_mode=True)
1341
+ sys.exit(0)
1342
+
1343
+ # Resolve data directory
1344
+ data_dir = find_data_dir(args.data_dir)
1345
+ if data_dir is None:
1346
+ log_error("ABYSS data not found.")
1347
+ print(" Searched:", file=sys.stderr)
1348
+ for c in _get_candidates(args.data_dir):
1349
+ print(f" • {c}", file=sys.stderr)
1350
+ print("", file=sys.stderr)
1351
+ print(" Fix one of these ways:", file=sys.stderr)
1352
+ print(f" {C.CYAN}abyss init{C.RESET} "
1353
+ "(download the data bundle)", file=sys.stderr)
1354
+ print(f" {C.CYAN}abyss --data-dir /path/to/data ...{C.RESET} "
1355
+ "(use a custom location)", file=sys.stderr)
1356
+ print(f" {C.CYAN}export ABYSS_DATA_DIR=/path/to/data{C.RESET} "
1357
+ "(env var)", file=sys.stderr)
1358
+ sys.exit(1)
1359
+
1360
+ # --list command
1361
+ if args.list:
1362
+ sys.exit(cmd_list(args.list, data_dir))
1363
+
1364
+ # Validate formats
1365
+ formats = [f.strip().lower() for f in str(args.format).split(",") if f.strip()]
1366
+ for f in formats:
1367
+ if f not in VALID_FORMATS:
1368
+ log_error(f"Unknown format '{f}'. Valid: {', '.join(sorted(VALID_FORMATS))}")
1369
+ sys.exit(1)
1370
+ if not formats:
1371
+ formats = ["accession"]
1372
+
1373
+ # Apply lineage signature
1374
+ if args.lineage:
1375
+ key = args.lineage.upper().strip()
1376
+ sig = LINEAGE_SIGNATURES.get(key)
1377
+ if sig is None:
1378
+ log_error(f"Unknown lineage '{args.lineage}'.")
1379
+ print(f" Available: {', '.join(sorted(LINEAGE_SIGNATURES))}", file=sys.stderr)
1380
+ sys.exit(1)
1381
+ log_info(f"Applying lineage signature: {args.lineage}")
1382
+ if not args.ic and "ic" in sig:
1383
+ args.ic = sig["ic"]
1384
+ if not args.st and "st" in sig:
1385
+ args.st = sig["st"]
1386
+ if not args.oxford_st and "oxford_st" in sig:
1387
+ args.oxford_st = sig["oxford_st"]
1388
+ if not args.kl and "kl" in sig:
1389
+ args.kl = sig["kl"]
1390
+
1391
+ # Load config file
1392
+ if args.config:
1393
+ cp = Path(args.config)
1394
+ if not cp.exists():
1395
+ log_error(f"Config file {cp} not found.")
1396
+ sys.exit(1)
1397
+ with open(cp) as f:
1398
+ cfg = json.load(f)
1399
+ log_info(f"Loaded config from {cp}")
1400
+ for k, v in cfg.items():
1401
+ key = k.replace("-", "_")
1402
+ if hasattr(args, key):
1403
+ setattr(args, key, v)
1404
+ elif k == "any" and v:
1405
+ args.any = True
1406
+ else:
1407
+ log_warn(f"Unknown config key '{k}'")
1408
+
1409
+ # Bare invocation: help
1410
+ has_filter = any([
1411
+ args.st, args.oxford_st, args.ic, args.kl, args.ocl, args.oxa,
1412
+ args.combo, args.ksk, args.kso,
1413
+ args.country, args.continent, args.region, args.source, args.host,
1414
+ args.year, args.super_group,
1415
+ args.amr, args.vfdb, args.plasmid, args.crab,
1416
+ args.complete_only, args.min_completeness, args.max_contamination,
1417
+ args.has_kl, args.has_oxa,
1418
+ any(getattr(args, "not_" + f) for f in (
1419
+ "st", "oxford_st", "ic", "kl", "ocl", "oxa",
1420
+ "combo", "ksk", "kso",
1421
+ "country", "continent", "region", "source", "host", "year", "super_group",
1422
+ "amr", "vfdb", "plasmid")),
1423
+ args.not_crab,
1424
+ ])
1425
+ if not has_filter and not args.count and args.output == "stdout":
1426
+ print_banner(quiet=args.quiet)
1427
+ print(parser.format_help())
1428
+ print(f"\n{C.YELLOW}💡 Add a filter, e.g.:{C.RESET}", file=sys.stderr)
1429
+ print(f" {C.CYAN}abyss --ic IC2 --count{C.RESET}", file=sys.stderr)
1430
+ print(f" {C.CYAN}abyss --crab --continent Europe --count{C.RESET}", file=sys.stderr)
1431
+ print(f"\n {C.CYAN}abyss --examples{C.RESET} for a full gallery.\n", file=sys.stderr)
1432
+ sys.exit(0)
1433
+
1434
+ # Banner
1435
+ if not args.quiet and _supports_color(sys.stderr):
1436
+ print_banner(quiet=False)
1437
+
1438
+ # Load data
1439
+ log_loading("Loading ABYSS master table...")
1440
+ df = load_master(data_dir)
1441
+ debug_step("Initial load", df, args.debug)
1442
+
1443
+ # Apply filters
1444
+ for _f in ("ic", "st", "oxford_st", "kl", "ocl", "oxa",
1445
+ "combo", "ksk", "kso",
1446
+ "country", "continent", "region", "source", "host", "year", "super_group"):
1447
+ _val = getattr(args, _f)
1448
+ if _val:
1449
+ df = apply_or(df, _f, _val, debug=args.debug)
1450
+
1451
+ if args.crab: df = filter_crab(df, data_dir, args.debug)
1452
+ if args.amr: df = filter_amr(df, data_dir, args.amr, match_all=not args.any, debug=args.debug)
1453
+ if args.vfdb: df = filter_vfdb(df, data_dir, args.vfdb, match_all=not args.any, debug=args.debug)
1454
+ if args.plasmid: df = filter_plasmid(df, data_dir, args.plasmid, match_all=not args.any, debug=args.debug)
1455
+
1456
+ if args.complete_only: df = filter_complete(df, args.debug)
1457
+ if args.min_completeness: df = filter_min_completeness(df, args.min_completeness, args.debug)
1458
+ if args.max_contamination: df = filter_max_contamination(df, args.max_contamination, args.debug)
1459
+ if args.has_kl: df = filter_has_kl(df, args.debug)
1460
+ if args.has_oxa: df = filter_has_oxa(df, args.debug)
1461
+
1462
+ # Boolean NOT (applied last: positive matches, minus exclusions)
1463
+ for _f in ("ic", "st", "oxford_st", "kl", "ocl", "oxa",
1464
+ "combo", "ksk", "kso",
1465
+ "country", "continent", "region", "source", "host", "year", "super_group",
1466
+ "amr", "vfdb", "plasmid"):
1467
+ _val = getattr(args, "not_" + _f, None)
1468
+ if _val:
1469
+ df = apply_not(df, _f, _val, data_dir, debug=args.debug)
1470
+ if args.not_crab:
1471
+ df = apply_not(df, "crab", "", data_dir, debug=args.debug)
1472
+
1473
+ # Count mode
1474
+ if args.count:
1475
+ print(f"{len(df):,}", flush=True)
1476
+ print_footer(args.quiet, count_mode=True)
1477
+ sys.exit(0)
1478
+
1479
+ if len(df) == 0:
1480
+ log_zero()
1481
+ print_footer(args.quiet, count_mode=True)
1482
+ sys.exit(0)
1483
+
1484
+ log_found(len(df))
1485
+
1486
+ # Write output
1487
+ if args.output == "stdout" and len(formats) > 1:
1488
+ log_error("Please specify --output (-o) when requesting multiple formats.")
1489
+ sys.exit(1)
1490
+
1491
+ if args.output == "stdout":
1492
+ print(serialize(df, formats[0]))
1493
+ if not args.quiet:
1494
+ print(f"{C.GRAY} (streamed {len(df):,} rows to stdout · {formats[0]}){C.RESET}",
1495
+ file=sys.stderr)
1496
+ else:
1497
+ paths = resolve_output_paths(args.output, formats)
1498
+ for fmt, path in paths.items():
1499
+ content = serialize(df, fmt)
1500
+ if fmt in ("biosample", "bioproject") and not content.strip():
1501
+ log_warn(f"Skipping '{path}' — 0 {fmt} accessions in the selected rows")
1502
+ continue
1503
+ count = len(content.strip().split("\n")) if fmt in ("biosample", "bioproject") else len(df)
1504
+ path.write_text(content)
1505
+ log_write(path, count, fmt)
1506
+
1507
+ print_footer(args.quiet, count_mode=False)
1508
+
1509
+
1510
+ if __name__ == "__main__":
1511
+ try:
1512
+ main()
1513
+ except BrokenPipeError:
1514
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
1515
+ sys.exit(0)
1516
+ except KeyboardInterrupt:
1517
+ print(f"\n{C.YELLOW}⚠️ Interrupted.{C.RESET}", file=sys.stderr)
1518
+ sys.exit(130)