Utilities Module (biallelic.misc)¶
The misc module provides utility functions for file I/O, string manipulation, module discovery, and visualization support.
Utility functions for biallelic analysis pipeline.
Provides common utilities for file I/O, string manipulation, module discovery, dynamic imports, and visualization color schemes.
- class biallelic.misc.DefaultHelpParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=<class 'argparse.HelpFormatter'>, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True, exit_on_error=True)[source]¶
Bases:
ArgumentParserCustom argument parser with improved error handling.
Extends ArgumentParser to display help text when errors occur, providing users with available options immediately.
- class biallelic.misc.SubcommandHelpFormatter(prog, indent_increment=2, max_help_position=24, width=None)[source]¶
Bases:
RawDescriptionHelpFormatterCustom argparse formatter for better subcommand help display.
Extends RawDescriptionHelpFormatter to improve formatting of subcommands in argparse, removing extra parsing headers for cleaner output.
- biallelic.misc.camel_case_split(input_str: str) list[source]¶
Split camelCase string into individual words.
Splits a camelCase string by finding transitions from lowercase to uppercase characters. Useful for parsing enum or class names.
- Args:
input_str: CamelCase or PascalCase string to split
- Returns:
List of individual words from the input string
- Example:
>>> camel_case_split("CamelCaseExample") ['Camel', 'Case', 'Example'] >>> camel_case_split("HTTPSConnection") ['HTTPS', 'Connection']
- biallelic.misc.color_palettes(x: str = 'default') Dict[str, str][source]¶
Get color palette for biallelic inactivation visualization.
Returns a dictionary mapping biallelic hit types to hex color codes for use in oncoprint and other visualizations.
- Args:
x: Palette name (default: “default”, currently only one palette available)
- Returns:
Dictionary mapping hit type strings to hex color codes
- Example:
>>> colors = color_palettes() >>> colors["som_loss/som_snv"] '#c6c0ac'
- biallelic.misc.generate_uid(n: int = 4) str[source]¶
Generate a unique identifier with timestamp and random suffix.
Creates a UID combining current timestamp and random alphanumeric characters. Format: YYMMDDHHMMss.ffffff_XXXX
- Args:
n: Length of random suffix (default: 4, range: 1-10 recommended)
- Returns:
Unique identifier string combining timestamp and random part
- Example:
>>> uid = generate_uid() # e.g., "251029094958.153950_A1B2" >>> uid = generate_uid(n=8) # e.g., "251029094958.153950_A1B2C3D4"
- biallelic.misc.get_module_method(parent, module: str, method: str) Callable | None[source]¶
Get a specific method from a module in a package.
Dynamically locates a module by name and retrieves a specific method/function from it. Used for plugin-style architecture where driver and analysis modules are discovered and invoked at runtime.
- Args:
parent: Parent package object module: Name of module (e.g., “maf”, “bed”) method: Name of method/function in module (e.g., “snv”, “genes”)
- Returns:
Callable method object, or None if module/method not found
- Example:
>>> import biallelic.drivers >>> snv_loader = get_module_method(biallelic.drivers, "maf", "snv") >>> snv_loader is not None True
- biallelic.misc.get_modules_names(parent) List[str][source]¶
Get list of module names from a package.
Discovers all modules in a package and returns their simple names (without the package prefix).
- Args:
parent: Package object
- Returns:
List of module names (e.g., [“maf”, “bed”, “vcf_vep_ppcg”])
- biallelic.misc.import_module(module_name: str, module_path: str) ModuleType[source]¶
Dynamically load a Python module from file path.
- Args:
module_name: Name for the imported module module_path: Absolute file path to module .py file
- Returns:
Imported module object
- Raises:
FileNotFoundError: If module_path does not exist ImportError: If module cannot be loaded
- biallelic.misc.make_ucsc_format(chrom: str, start: int, end: int) str[source]¶
Format genomic coordinates in UCSC Genome Browser format.
Converts genomic coordinates to UCSC format (chr:start-end). Automatically adds “chr” prefix if not present.
- Args:
chrom: Chromosome identifier (with or without “chr” prefix) start: 0-based start coordinate end: 0-based end coordinate
- Returns:
Formatted string in UCSC format (e.g., “chr17:7577121-7590863”)
- Example:
>>> make_ucsc_format("17", 7577121, 7590863) 'chr17:7577121-7590863' >>> make_ucsc_format("chrX", 100, 200) 'chrX:100-200'
- biallelic.misc.package_modules(package) Set[str][source]¶
Discover all modules in a package.
Scans package directory and returns fully-qualified module names for all Python files (excluding __init__.py).
- Args:
package: Package object (use your_package not “your_package”)
- Returns:
Set of fully-qualified module names (e.g., “biallelic.drivers.maf”)
- Example:
>>> import biallelic.drivers >>> modules = package_modules(biallelic.drivers) >>> "biallelic.drivers.maf" in modules True
- biallelic.misc.try_import(path: str, module_name: str) ModuleType[source]¶
Import or create a module in a specific directory.
Creates the directory structure if needed, ensures __init__.py exists, and imports the module.
- Args:
path: Base directory path module_name: Name of module to create/import
- Returns:
Imported module object
- Raises:
IOError: If directory cannot be created or __init__.py cannot be written
- biallelic.misc.xopen(filename: str, mode: str = 'r', bgzip: bool = False)[source]¶
Open files transparently with automatic format detection.
Unified file opener that handles regular text files, gzip-compressed files, and BGZF files. Automatically detects format from filename extension. Special handling for stdin/stdout with filename ‘-‘.
- Args:
filename: Path to file, or ‘-’ for stdin (read) or stdout (write) mode: File open mode (‘r’, ‘w’, ‘a’, ‘rt’, ‘wb’, etc.) bgzip: If True, use BGZF compression; otherwise auto-detect from .gz
- Returns:
File object (text or binary mode as specified)
- Raises:
FileNotFoundError: If file doesn’t exist (read mode) IOError: If file cannot be opened
- Example:
>>> with xopen("data.txt", "r") as f: ... data = f.read() >>> with xopen("data.txt.gz", "rt") as f: # Auto-decompresses ... data = f.read() >>> with xopen("-", "r") as f: # Read from stdin ... line = f.readline()
Overview¶
This module contains:
File I/O: Transparent handling of regular, gzip, and BGZF files
String Utilities: Formatting and parsing functions
Module Discovery: Dynamic plugin loading for drivers and analyses
Visualization: Color palettes for oncoprint generation
Unique IDs: UID generation for analysis runs
File I/O Functions¶
Transparent file opening with automatic format detection:
from biallelic.misc import xopen
# Read text file
with xopen("data.txt", "r") as f:
content = f.read()
# Read gzip-compressed file (auto-detected)
with xopen("data.txt.gz", "rt") as f:
lines = f.readlines()
# Read BGZF-compressed file
with xopen("data.txt.bgz", "r", bgzip=True) as f:
data = f.read()
# Write gzip-compressed file
with xopen("output.txt.gz", "wt") as f:
f.write("data")
# Read from stdin / write to stdout
with xopen("-", "r") as f:
user_input = f.read()
String Utilities¶
Working with genomic data strings:
from biallelic.misc import make_ucsc_format, camel_case_split
# Format genomic coordinates in UCSC style
ucsc = make_ucsc_format("17", 7577121, 7590863)
# Returns: "chr17:7577121-7590863"
# Split camelCase/PascalCase strings
words = camel_case_split("AberrationType")
# Returns: ["Aberration", "Type"]
Module Discovery¶
Finding and loading driver modules:
from biallelic.misc import (
package_modules,
get_modules_names,
get_module_method
)
import biallelic.drivers
# Get all module names in package
all_modules = package_modules(biallelic.drivers)
# Returns: {"biallelic.drivers.maf", "biallelic.drivers.bed", ...}
# Get simple module names
driver_names = get_modules_names(biallelic.drivers)
# Returns: ["maf", "bed", "simple_segments", ...]
# Get specific method from module
snv_loader = get_module_method(
biallelic.drivers,
"maf",
"snv"
)
# Returns: callable function for loading SNVs from MAF files
Dynamic Module Loading¶
Advanced usage for custom modules:
from biallelic.misc import import_module, try_import
# Load module directly from file path
my_driver = import_module("my_driver", "/path/to/my_driver.py")
snv_data = my_driver.snv(file_path, logger, reference_map)
# Create and import custom module directory
custom_analysis = try_import("/path/to/analyses", "my_analysis")
Unique ID Generation¶
Generate unique identifiers for analysis runs:
from biallelic.misc import generate_uid
# Generate default UID
uid1 = generate_uid()
# Returns: "251029123456.789012_A1B2C3D4"
# Generate with longer random suffix
uid2 = generate_uid(n=8)
# Returns: "251029123456.789012_X1Y2Z3W4V5"
Format: YYMMDDHHMMss.ffffff_RANDOM
YY: 2-digit year
MM: 2-digit month
DD: 2-digit day
HH: 2-digit hour
MM: 2-digit minute
ss: 2-digit second
ffffff: 6-digit microsecond
RANDOM: n random alphanumeric characters
Visualization Support¶
Color palettes for genomic visualization:
from biallelic.misc import color_palettes
colors = color_palettes()
# Returns: {"som_snv/som_snv": "#2c4c68", ...}
# Use in visualization
hit_color = colors.get("som_loss/som_snv", "#000000")
Available Colors¶
Biallelic hit type to color mapping:
germ_snp/som_loss: #768b02 (olive green)som_cn_loh/som_snv: #8b6a54 (brown)som_gain_loh/som_snv: #aa96b1 (purple)som_loss/methyl: #d5b28a (tan)som_loss/som_indel: #80997f (gray-green)som_loss/som_loss: #d56e67 (coral red)som_loss/som_snv: #c6c0ac (beige)som_loss/som_sv: #5a4b67 (slate purple)som_snv/som_snv: #2c4c68 (navy blue)som_loss/subclonal_snv: #a05a6e (mauve)
Argparse Utilities¶
Custom argparse components:
from biallelic.misc import SubcommandHelpFormatter, DefaultHelpParser
# Better subcommand help formatting
parser = DefaultHelpParser(
formatter_class=SubcommandHelpFormatter,
description="Biallelic inactivation analysis"
)
# Improved error handling - shows help on error
parser.error("Invalid option") # Shows help instead of just error
See Also¶
Orchestrator Module (biallelic.bi): Using utilities for orchestration
Development Guide: Guide for custom drivers
Python pathlib: https://docs.python.org/3/library/pathlib.html
Python zipfile: https://docs.python.org/3/library/zipfile.html