diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..82c3c17 --- /dev/null +++ b/.gitignore @@ -0,0 +1,139 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# Virtual environments +.env +.venv +venv/ +ENV/ +env/ + +# Jupyter Notebook +.ipynb_checkpoints/ +*.nbconvert.ipynb + +# PyCharm +.idea/ + +# VSCode +.vscode/ + +# macOS +.DS_Store + +# Linux +*~ + +# Logs +logs/ +*.log + +# Testing +.pytest_cache/ +.coverage +htmlcov/ +.tox/ +.mypy_cache/ +.ruff_cache/ + +# Type checking +.pyre/ + +# Data files +data/ +datasets/ +*.csv +*.tsv +*.parquet +*.feather +*.h5 +*.hdf5 +*.db + +# Model artifacts +models/ +checkpoints/ +*.ckpt +*.pt +*.pth +*.onnx +*.joblib +*.pkl + +# Experiment tracking +mlruns/ +wandb/ +tensorboard/ +runs/ + +# Outputs +outputs/ +results/ +figures/ +plots/ +reports/ + +# Temporary files +tmp/ +temp/ +*.tmp + +# Secrets / credentials +.env.local +.env.* +!.env.example + +# Package managers +Pipfile.lock + +# Hatch +.hatch/ + +# DVC +.dvc/cache/ +.dvc/tmp/ + +# Snakemake +.snakemake/ + +# R +.Rhistory +.RData +.Rproj.user/ + +# Docker +*.pid + +# AWS / cloud +.aws/ + +# IDE-specific notebooks +.spyproject/ + +# Ignore large binaries +*.zip +*.tar.gz +*.7z +uv.lock diff --git a/krakenparser/__init__.py b/krakenparser/__init__.py index 11e7468..6310840 100755 --- a/krakenparser/__init__.py +++ b/krakenparser/__init__.py @@ -1,9 +1,11 @@ +#!/usr/bin/env python3 + from .kpplot.clustermap import clustermap from .kpplot.stackedbar import stacked_barplot from .kpplot.streamgraph import streamgraph __all__: list[str] = [ + "clustermap", "stacked_barplot", "streamgraph", - "clustermap", ] diff --git a/krakenparser/counts/convert2csv.py b/krakenparser/counts/convert2csv.py index afd1828..cdea1c0 100755 --- a/krakenparser/counts/convert2csv.py +++ b/krakenparser/counts/convert2csv.py @@ -8,7 +8,7 @@ import logging from pathlib import Path -from typing import Optional +from typing import Annotated import pandas as pd import typer @@ -57,18 +57,22 @@ def convert_to_csv(input_file: Path, output_file: Path) -> None: @app.callback(invoke_without_command=True) def main( ctx: typer.Context, - input_file: Optional[Path] = typer.Option( - None, - "-i", - "--input", - help="Path to the input tab-delimited TXT file (samples in columns, taxa in rows).", - ), - output_file: Optional[Path] = typer.Option( - None, - "-o", - "--output", - help="Path to the output transposed CSV file.", - ), + input_file: Annotated[ + Path | None, + typer.Option( + "-i", + "--input", + help="Path to the input tab-delimited TXT file (samples in columns, taxa in rows).", + ), + ] = None, + output_file: Annotated[ + Path | None, + typer.Option( + "-o", + "--output", + help="Path to the output transposed CSV file.", + ), + ] = None, ) -> None: """Reads a TXT file, reorganizes the data, and converts it into a CSV file.""" logging.basicConfig(level=logging.INFO, format="%(message)s") diff --git a/krakenparser/counts/processing_script.py b/krakenparser/counts/processing_script.py index b3e9608..c934a21 100755 --- a/krakenparser/counts/processing_script.py +++ b/krakenparser/counts/processing_script.py @@ -12,7 +12,7 @@ import sys import tempfile from pathlib import Path -from typing import Optional +from typing import Annotated import typer @@ -106,18 +106,22 @@ def process_files(source_file: Path, destination_file: Path) -> None: @app.callback(invoke_without_command=True) def main( ctx: typer.Context, - input_file: Optional[Path] = typer.Option( - None, - "-i", - "--input", - help="Path to the source file (used to extract and truncate header labels).", - ), - output_file: Optional[Path] = typer.Option( - None, - "-o", - "--output", - help="Path to the destination matrix undergoing taxonomic name sanitation.", - ), + input_file: Annotated[ + Path | None, + typer.Option( + "-i", + "--input", + help="Path to the source file (used to extract and truncate header labels).", + ), + ] = None, + output_file: Annotated[ + Path | None, + typer.Option( + "-o", + "--output", + help="Path to the destination matrix undergoing taxonomic name sanitation.", + ), + ] = None, ) -> None: """Reads a source file, processes its first line, modifies taxa names in a destination file, and updates it.""" logging.basicConfig(level=logging.INFO, format="%(message)s") diff --git a/krakenparser/counts/split_mpa.py b/krakenparser/counts/split_mpa.py index ef42763..beafb02 100644 --- a/krakenparser/counts/split_mpa.py +++ b/krakenparser/counts/split_mpa.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 """Decomposition utility to partition master MPA matrices into rank-specific text tables. This module splits combined multi-sample MetaPhlAn files into separate tables grouped @@ -11,7 +10,7 @@ import re import sys from pathlib import Path -from typing import Optional +from typing import Annotated import typer @@ -172,18 +171,22 @@ def split_mpa( @app.callback(invoke_without_command=True) def main( ctx: typer.Context, - input_file: Optional[Path] = typer.Option( - None, - "-i", - "--input", - help="Input combined MPA file.", - ), - output_dir: Optional[Path] = typer.Option( - None, - "-o", - "--output", - help="Output directory root pathway.", - ), + input_file: Annotated[ + Path | None, + typer.Option( + "-i", + "--input", + help="Input combined MPA file.", + ), + ] = None, + output_dir: Annotated[ + Path | None, + typer.Option( + "-o", + "--output", + help="Output directory root pathway.", + ), + ] = None, viruses_only: bool = typer.Option( False, "--viruses", diff --git a/krakenparser/kpplot/__init__.py b/krakenparser/kpplot/__init__.py index 1dd6b4e..0421dfc 100644 --- a/krakenparser/kpplot/__init__.py +++ b/krakenparser/kpplot/__init__.py @@ -4,11 +4,11 @@ from .streamgraph import KpStreamgraph, streamgraph __all__: list[str] = [ - "KpPlotBase", "KpClustermap", - "clustermap", + "KpPlotBase", "KpStackedBarplot", - "stacked_barplot", "KpStreamgraph", + "clustermap", + "stacked_barplot", "streamgraph", ] diff --git a/krakenparser/kpplot/base.py b/krakenparser/kpplot/base.py index cc72858..218ccb7 100644 --- a/krakenparser/kpplot/base.py +++ b/krakenparser/kpplot/base.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 """Base classes and data aggregation utilities for metagenomic visualization. This module provides structural baselines for managing Matplotlib canvas states @@ -7,7 +6,6 @@ """ from pathlib import Path -from typing import Optional, Union import matplotlib.pyplot as plt import pandas as pd @@ -37,10 +35,10 @@ def plotfig(self) -> plt.Figure: def savefig( self, - path: Union[Path, str], + path: Path | str, dpi: int = 300, transparent: bool = False, - bbox_inches: Optional[str] = "tight", + bbox_inches: str | None = "tight", ) -> None: """Commit the current canvas state atomically to a physical image file. diff --git a/krakenparser/kpplot/clustermap.py b/krakenparser/kpplot/clustermap.py index a96d4eb..b3d39ae 100644 --- a/krakenparser/kpplot/clustermap.py +++ b/krakenparser/kpplot/clustermap.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 """Hierarchical clustering and heatmap visualization module for metagenomic profiles. This module leverages Seaborn's ClusterGrid matrix engine to compute and render @@ -6,7 +5,8 @@ taxonomic patterns and sample cohort similarities. """ -from typing import Literal, Optional, Sequence, Tuple +from collections.abc import Sequence +from typing import Literal import matplotlib.pyplot as plt import pandas as pd @@ -33,22 +33,22 @@ def __init__(self, fig: plt.Figure, ax: plt.Axes, grid: ClusterGrid) -> None: def clustermap( df: pd.DataFrame, - metadata: Optional[pd.DataFrame] = None, - metadata_group: Optional[str] = None, - sample_order: Optional[Sequence[str]] = None, + metadata: pd.DataFrame | None = None, + metadata_group: str | None = None, + sample_order: Sequence[str] | None = None, clust_linewidths: float = 0.5, clust_linecolor: str = "grey", x_axis: str = "Sample_id", y_axis: str = "taxon", - figsize: Optional[Tuple[float, float]] = None, + figsize: tuple[float, float] | None = None, cmap: str = "Greens", - title: Optional[str] = None, + title: str | None = None, title_fontsize: float = 16.0, title_color: str = "black", title_weight: Literal["normal", "bold", "heavy", "light"] = "normal", title_style: Literal["normal", "italic", "oblique"] = "normal", - xlabel: Optional[str] = None, - ylabel: Optional[str] = None, + xlabel: str | None = None, + ylabel: str | None = None, xlabel_fontsize: float = 12.0, ylabel_fontsize: float = 12.0, xlabel_color: str = "black", @@ -69,11 +69,11 @@ def clustermap( yticks_color: str = "black", yticks_weight: Literal["normal", "bold", "heavy", "light"] = "normal", yticks_style: Literal["normal", "italic", "oblique"] = "normal", - standard_scale: Optional[int] = None, - z_score: Optional[int] = None, + standard_scale: int | None = None, + z_score: int | None = None, legend_title: str = "Relative abundance (%)", - cbar_pos: Tuple[float, float, float, float] = (1.02, 0.3, 0.03, 0.4), - background_color: Optional[str] = "white", + cbar_pos: tuple[float, float, float, float] = (1.02, 0.3, 0.03, 0.4), + background_color: str | None = "white", ) -> KpClustermap: """Generate a highly customizable, publication-grade hierarchical clustermap. diff --git a/krakenparser/kpplot/stackedbar.py b/krakenparser/kpplot/stackedbar.py index 5f1d56b..3193427 100644 --- a/krakenparser/kpplot/stackedbar.py +++ b/krakenparser/kpplot/stackedbar.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 """Stacked barplot visualization module for compositional metagenomic profiles. This module builds normalized, multi-component stacked column charts tracking @@ -6,7 +5,8 @@ or aggregated experimental cohorts. """ -from typing import Literal, Optional, Sequence, Tuple, Union +from collections.abc import Sequence +from typing import Literal import matplotlib.pyplot as plt import numpy as np @@ -31,15 +31,15 @@ def __init__(self, fig: plt.Figure, ax: plt.Axes) -> None: def stacked_barplot( df: pd.DataFrame, - metadata: Optional[pd.DataFrame] = None, - metadata_group: Optional[str] = None, - sample_order: Optional[Sequence[str]] = None, - figsize: Tuple[float, float] = (14.0, 7.0), - cmap: Union[str, Sequence[str]] = "tab20", + metadata: pd.DataFrame | None = None, + metadata_group: str | None = None, + sample_order: Sequence[str] | None = None, + figsize: tuple[float, float] = (14.0, 7.0), + cmap: str | Sequence[str] = "tab20", bar_width: float = 0.6, edgecolor: str = "black", edge_linewidth: float = 0.3, - title: Optional[str] = None, + title: str | None = None, title_fontsize: float = 16.0, title_color: str = "black", title_weight: Literal["normal", "bold", "heavy", "light"] = "normal", @@ -60,7 +60,7 @@ def stacked_barplot( xticks_color: str = "black", xticks_weight: Literal["normal", "bold", "heavy", "light"] = "normal", xticks_style: Literal["normal", "italic", "oblique"] = "normal", - background_color: Optional[str] = "white", + background_color: str | None = "white", grid: bool = True, grid_linestyle: str = "--", grid_alpha: float = 0.7, @@ -68,7 +68,7 @@ def stacked_barplot( legend_fontsize: float = 9.0, legend_fontstyle: Literal["normal", "italic", "oblique"] = "italic", legend_loc: str = "upper left", - legend_bbox: Tuple[float, float] = (1.05, 1.0), + legend_bbox: tuple[float, float] = (1.05, 1.0), show_legend: bool = True, ) -> KpStackedBarplot: """Generate a publication-grade customizable stacked barplot for relative abundances. @@ -154,7 +154,7 @@ def stacked_barplot( # Step 5: Establish palette map dictionaries compliant with static analysis if isinstance(cmap, str): palette_colors = sns.color_palette(cmap, n_colors=len(df_plot.columns)) - color_dict: dict[str, Union[str, tuple[float, ...]]] = { + color_dict: dict[str, str | tuple[float, ...]] = { str(col): color for col, color in zip(df_plot.columns, palette_colors) } elif isinstance(cmap, (list, tuple, np.ndarray, pd.Series)) or hasattr( diff --git a/krakenparser/kpplot/streamgraph.py b/krakenparser/kpplot/streamgraph.py index 6a2719e..e19dbed 100644 --- a/krakenparser/kpplot/streamgraph.py +++ b/krakenparser/kpplot/streamgraph.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 """Streamgraph visualization module for continuous-like metagenomic cohort profiles. This module renders smooth, contiguous stacked area charts representing @@ -6,7 +5,8 @@ or grouped metadata categories. """ -from typing import Any, Literal, Optional, Sequence, Tuple, Union +from collections.abc import Sequence +from typing import Any, Literal import matplotlib.pyplot as plt import numpy as np @@ -31,16 +31,16 @@ def __init__(self, fig: plt.Figure, ax: plt.Axes) -> None: def streamgraph( df: pd.DataFrame, - metadata: Optional[pd.DataFrame] = None, - metadata_group: Optional[str] = None, - sample_order: Optional[Sequence[str]] = None, - figsize: Tuple[float, float] = (14.0, 7.0), - cmap: Union[str, Sequence[str]] = "tab20", + metadata: pd.DataFrame | None = None, + metadata_group: str | None = None, + sample_order: Sequence[str] | None = None, + figsize: tuple[float, float] = (14.0, 7.0), + cmap: str | Sequence[str] = "tab20", bar_width: float = 0.6, fill_alpha: float = 1.0, - edgecolor: Optional[str] = None, + edgecolor: str | None = None, edge_linewidth: float = 0.3, - title: Optional[str] = None, + title: str | None = None, title_fontsize: float = 16.0, title_color: str = "black", title_weight: Literal["normal", "bold", "heavy", "light"] = "normal", @@ -61,7 +61,7 @@ def streamgraph( xticks_color: str = "black", xticks_weight: Literal["normal", "bold", "heavy", "light"] = "normal", xticks_style: Literal["normal", "italic", "oblique"] = "normal", - background_color: Optional[str] = "white", + background_color: str | None = "white", grid: bool = True, grid_linestyle: str = "--", grid_alpha: float = 0.7, @@ -69,7 +69,7 @@ def streamgraph( legend_fontsize: float = 9.0, legend_fontstyle: Literal["normal", "italic", "oblique"] = "italic", legend_loc: str = "upper left", - legend_bbox: Tuple[float, float] = (1.05, 1.0), + legend_bbox: tuple[float, float] = (1.05, 1.0), show_legend: bool = True, ) -> KpStreamgraph: """Generate a highly customizable streamgraph/stacked-area plot for relative abundances. diff --git a/krakenparser/krakenparser.py b/krakenparser/krakenparser.py index c755fcb..29f238c 100755 --- a/krakenparser/krakenparser.py +++ b/krakenparser/krakenparser.py @@ -11,7 +11,7 @@ from importlib.metadata import PackageNotFoundError as _PNF from importlib.metadata import version as _pkg_version from pathlib import Path -from typing import Optional +from typing import Annotated import typer @@ -65,12 +65,16 @@ def _version_callback(value: bool) -> None: @app.callback(invoke_without_command=True) def main_callback( ctx: typer.Context, - input_dir: Optional[Path] = typer.Option( - None, "-i", "--input", help="Directory containing Kraken2 report files." - ), - output_dir: Optional[Path] = typer.Option( - None, "-o", "--output", help="Output directory." - ), + input_dir: Annotated[ + Path | None, + typer.Option( + "-i", "--input", help="Directory containing Kraken2 report files." + ), + ] = None, + output_dir: Annotated[ + Path | None, + typer.Option("-o", "--output", help="Output directory."), + ] = None, viruses: bool = typer.Option( False, "-viruses", @@ -98,7 +102,7 @@ def main_callback( keep_human: bool = typer.Option( False, "-keep-human", "--keep-human", help="Do not filter human-related taxa." ), - version: Optional[bool] = typer.Option( + version: bool | None = typer.Option( None, "-V", "--version", @@ -109,7 +113,7 @@ def main_callback( depth: int = typer.Option( 1000, "-d", "--depth", help="Rarefaction depth for β-diversity." ), - seed: Optional[int] = typer.Option( + seed: int | None = typer.Option( None, "-s", "--seed", help="Random seed for reproducible rarefaction." ), overwrite: bool = typer.Option( diff --git a/krakenparser/mpa/mpa_table.py b/krakenparser/mpa/mpa_table.py index a6f13b7..1938ccd 100644 --- a/krakenparser/mpa/mpa_table.py +++ b/krakenparser/mpa/mpa_table.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 """Aggregation engine for merging multiple MetaPhlAn (MPA) files into a unified matrix. This module parses multi-sample taxonomic report files formatted in the MetaPhlAn @@ -10,7 +9,7 @@ import logging import sys from pathlib import Path -from typing import Optional +from typing import Annotated import typer @@ -132,18 +131,22 @@ def combine_mpa(in_files: list[Path], o_file: Path) -> None: @app.callback(invoke_without_command=True) def main( ctx: typer.Context, - in_files: Optional[list[Path]] = typer.Option( - None, - "-i", - "--input", - help="Input MPA files (one per sample). Repeat the '-i' option for multiple files.", - ), - o_file: Optional[Path] = typer.Option( - None, - "-o", - "--output", - help="Output merged MPA file path.", - ), + in_files: Annotated[ + list[Path] | None, + typer.Option( + "-i", + "--input", + help="Input MPA files (one per sample). Repeat the '-i' option for multiple files.", + ), + ] = None, + o_file: Annotated[ + Path | None, + typer.Option( + "-o", + "--output", + help="Output merged MPA file path.", + ), + ] = None, ) -> None: """Combine MPA files into a single tab-delimited table.""" logging.basicConfig(level=logging.INFO, format="%(message)s") diff --git a/krakenparser/mpa/transform2mpa.py b/krakenparser/mpa/transform2mpa.py index a64de28..a822e67 100644 --- a/krakenparser/mpa/transform2mpa.py +++ b/krakenparser/mpa/transform2mpa.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 """Taxonomic format converter translating Kraken2 reports to MetaPhlAn (MPA) layout. This module parses standard space-indented hierarchical Kraken2 and KrakenUniq output @@ -9,7 +8,7 @@ import logging import sys from pathlib import Path -from typing import Any, Optional +from typing import Annotated, Any import typer @@ -174,25 +173,31 @@ def kreport_to_mpa( @app.callback(invoke_without_command=True) def main( ctx: typer.Context, - r_file: Optional[Path] = typer.Option( - None, - "-r", - "--report-file", - "--report", - help="Single input Kraken2 report file.", - ), - input_dir: Optional[Path] = typer.Option( - None, - "-i", - "--input", - help="Input directory containing Kraken2 report files (batch mode).", - ), - o_file: Optional[Path] = typer.Option( - None, - "-o", - "--output", - help="Output MPA file (single mode) or output directory (batch mode).", - ), + r_file: Annotated[ + Path | None, + typer.Option( + "-r", + "--report-file", + "--report", + help="Single input Kraken2 report file.", + ), + ] = None, + input_dir: Annotated[ + Path | None, + typer.Option( + "-i", + "--input", + help="Input directory containing Kraken2 report files (batch mode).", + ), + ] = None, + o_file: Annotated[ + Path | None, + typer.Option( + "-o", + "--output", + help="Output MPA file (single mode) or output directory (batch mode).", + ), + ] = None, display_header: bool = typer.Option( False, "--display-header", @@ -242,12 +247,12 @@ def main( use_reads: bool = not percentages remove_spaces: bool = not keep_spaces - kwargs: dict[str, Any] = dict( - display_header=display_header, - include_intermediate=intermediate_ranks, - use_reads=use_reads, - remove_spaces=remove_spaces, - ) + kwargs: dict[str, Any] = { + "display_header": display_header, + "include_intermediate": intermediate_ranks, + "use_reads": use_reads, + "remove_spaces": remove_spaces, + } try: if input_dir: diff --git a/krakenparser/pipeline.py b/krakenparser/pipeline.py index 0520780..c226d63 100644 --- a/krakenparser/pipeline.py +++ b/krakenparser/pipeline.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 """Core orchestration engine for the KrakenParser execution pipeline. This module consolidates independent taxonomic processing steps into a seamless, @@ -10,7 +9,7 @@ import shutil import sys from pathlib import Path -from typing import Optional +from typing import Annotated import pandas as pd import typer @@ -55,29 +54,27 @@ def _is_processable(filepath: Path) -> bool: try: if b"\x00" in filepath.read_bytes(): return False - except Exception: + except OSError: return False try: with open(filepath, "r", encoding="utf-8", errors="strict") as f: f.read(1024) return True - except UnicodeDecodeError: - return False - except Exception: + except (UnicodeDecodeError, OSError): return False def run_pipeline( input_dir: Path, - output_dir: Optional[Path] = None, + output_dir: Path | None = None, keep_human: bool = False, viruses_only: bool = False, bacteria_only: bool = False, fungi_only: bool = False, archaea_only: bool = False, rarefaction_depth: int = 1000, - seed: Optional[int] = None, + seed: int | None = None, overwrite: bool = False, ) -> None: """Execute the sequential programmatic workflow blocks of KrakenParser. @@ -204,18 +201,22 @@ def run_pipeline( no_args_is_help=True, ) def main( - input_dir: Path = typer.Option( - ..., - "-i", - "--input", - help="Directory containing Kraken2 report files.", - ), - output_dir: Optional[Path] = typer.Option( - None, - "-o", - "--output", - help="Output directory (default: parent of input).", - ), + input_dir: Annotated[ + Path, + typer.Option( + "-i", + "--input", + help="Directory containing Kraken2 report files.", + ), + ], + output_dir: Annotated[ + Path | None, + typer.Option( + "-o", + "--output", + help="Output directory (default: parent of input).", + ), + ] = None, keep_human: bool = typer.Option( False, "--keep-human", @@ -247,7 +248,7 @@ def main( "--depth", help="Rarefaction depth for β-diversity.", ), - seed: Optional[int] = typer.Option( + seed: int | None = typer.Option( None, "-s", "--seed", diff --git a/krakenparser/stats/diversity.py b/krakenparser/stats/diversity.py index e9dfb29..58b3f05 100644 --- a/krakenparser/stats/diversity.py +++ b/krakenparser/stats/diversity.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 """Statistical module for calculating microbial community alpha and beta diversities. This module provides industry-standard ecological metrics including Shannon Index, @@ -8,8 +7,9 @@ import logging import sys +from collections.abc import Sequence from pathlib import Path -from typing import Any, Optional, Sequence +from typing import Annotated, Any import numpy as np import pandas as pd @@ -150,7 +150,7 @@ def calc_beta_div( df: pd.DataFrame, output_path: Path, rarefaction_depth: int, - seed: Optional[int] = None, + seed: int | None = None, ) -> None: """Compute composition dissimilarity matrices utilizing uniform rarefied values. @@ -210,25 +210,29 @@ def calc_beta_div( @app.callback(invoke_without_command=True) def main( ctx: typer.Context, - input_file: Optional[Path] = typer.Option( - None, - "-i", - "--input", - help="Input total count table CSV (species level).", - ), - output_dir: Optional[Path] = typer.Option( - None, - "-o", - "--output", - help="Output directory path.", - ), + input_file: Annotated[ + Path | None, + typer.Option( + "-i", + "--input", + help="Input total count table CSV (species level).", + ), + ] = None, + output_dir: Annotated[ + Path | None, + typer.Option( + "-o", + "--output", + help="Output directory path.", + ), + ] = None, depth: int = typer.Option( 1000, "-d", "--depth", help="Rarefaction depth for β diversity.", ), - seed: Optional[int] = typer.Option( + seed: int | None = typer.Option( None, "-s", "--seed", diff --git a/krakenparser/stats/relabund.py b/krakenparser/stats/relabund.py index 60e945c..028ea2c 100644 --- a/krakenparser/stats/relabund.py +++ b/krakenparser/stats/relabund.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 """Normalization module for calculating relative abundances of microbial taxa. This module reshapes wide count matrices into tidy long-format tables, converts @@ -11,7 +10,7 @@ import sys import warnings from pathlib import Path -from typing import Any, Optional +from typing import Annotated, Any import numpy as np import pandas as pd @@ -31,7 +30,7 @@ def calculate_rel_abund( - input_file: Path, output_file: Path, other_threshold: Optional[float] = None + input_file: Path, output_file: Path, other_threshold: float | None = None ) -> None: """Transform absolute taxonomic counts to relative percentage profiles. @@ -106,24 +105,30 @@ def calculate_rel_abund( @app.callback(invoke_without_command=True) def main( ctx: typer.Context, - input_file: Optional[Path] = typer.Option( - None, - "-i", - "--input", - help="Input CSV file with counts.", - ), - output_file: Optional[Path] = typer.Option( - None, - "-o", - "--output", - help="Output CSV file path.", - ), - other: Optional[float] = typer.Option( - None, - "-O", - "--other", - help="Threshold for grouping taxa into 'Other ( None: """Calculates taxa relative abundance and saves it to a CSV file.""" logging.basicConfig(level=logging.INFO, format="%(message)s") diff --git a/krakenparser/utils.py b/krakenparser/utils.py index 1517864..7a789b2 100644 --- a/krakenparser/utils.py +++ b/krakenparser/utils.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 """Shared utility wrappers and filesystem helpers for the KrakenParser suite. This module provides low-level infrastructure operations, such as safe path diff --git a/pyproject.toml b/pyproject.toml index 5110fba..65902bd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,11 +4,11 @@ build-backend = "setuptools.build_meta" [project] name = "krakenparser" -version = "1.1.2" +version = "1.1.3" description = "A collection of scripts designed to process Kraken2 reports and convert them into CSV format." readme = { file = "README.md", content-type = "text/markdown" } license = { file = "LICENSE" } -authors = [{ name = "Ilia Popov", email = "iljapopov17@gmail.com" }] +authors = [{ name = "Ilya (Ilia) Popov", email = "ilypopv@gmail.com" }] requires-python = ">=3.10,<=3.16" dependencies = [ "pandas>=2.0.0,<=2.3.3", @@ -39,6 +39,7 @@ filterwarnings = [ "ignore:Tight layout not applied.*:UserWarning", "ignore:Samples with zero total abundance.*:UserWarning", ] +pythonpath = ["."] [tool.coverage.run] source = ["krakenparser"] diff --git a/tests/test_units.py b/tests/test_units.py index 9e4891b..4969c2a 100644 --- a/tests/test_units.py +++ b/tests/test_units.py @@ -34,7 +34,7 @@ def test_parse_line_standard_rank(): def test_parse_line_root_has_zero_depth(): line = "99.98\t999980\t0\tR\t1\troot\n" - name, depth, rank, cum_reads, pct = _parse_line(line) + name, depth, rank, _cum_reads, _pct = _parse_line(line) assert name == "root" assert depth == 0