Research Toolbox API

A compact reference for the reusable utilities in inoue0426/research_toolbox. The preferred interface is the short facade: import research_toolbox as rt.

Design rule. Common operations get short names; domain modules retain explicit long-form APIs. Scientific assumptions such as thresholds, organism, review status, and invalid-input behavior stay configurable.

Install

git clone https://github.com/inoue0426/research_toolbox.git
cd research_toolbox
pip install -e .

# optional extras
pip install -e '.[evaluation]'
pip install -e '.[chemistry]'
pip install -e '.[visualization]'
pip install -e '.[all]'

Quick start

import research_toolbox as rt

rt.seed(42)
metrics = rt.evaluate_binary(y_true, y_prob)
fp = rt.fingerprint("CCO")
cache = rt.open_cache(".cache")
sections = rt.read_pmc("article.xml")
uid = rt.gene_to_uniprot("TP53")
gene = rt.uniprot_to_gene("P04637")

Top-level API

Function / classPurpose
rt.seed(value=42, deterministic=True)Seed Python, NumPy, and PyTorch when available.
rt.evaluate_binary(y_true, y_score, threshold=0.5)Compute common binary-classification metrics.
rt.summarize_runs(results)Summarize metrics across repeated runs or seeds with mean, standard deviation, and valid count.
rt.fingerprint(smiles, ...)Create one Morgan fingerprint.
rt.fingerprints(smiles_iterable, ...)Create Morgan fingerprints in batch.
rt.open_cache(path=".cache")Open a persistent JSON-backed cache.
rt.cached_lookup(cache, key, fetcher, ...)Cache-through helper for expensive lookups.
rt.read_pmc(xml_path, ...)Extract broad sections from PMC/JATS XML.
rt.normalize_drug(value)Normalize a drug string for matching/caching.
rt.normalize_gene(value)Normalize a gene string for matching/caching.
rt.normalize_protein(value)Normalize a protein string for matching/caching.
rt.normalize_text(value)Normalize free text for simple matching.
rt.gene_to_uniprot(gene, ...)Map one gene symbol/name to UniProtKB accession(s).
rt.genes_to_uniprot(genes, ...)Batch gene → UniProtKB mapping.
rt.uniprot_to_gene(accession, ...)Map one UniProtKB accession to its primary gene name.
rt.uniprots_to_gene(accessions, ...)Batch UniProtKB → gene mapping.
rt.UniProtClient(...)Reusable client with retry/backoff and optional cache support.
rt.UniProtRecordStructured UniProt record containing accession, gene, entry, organism, review status, and protein name.

Gene ↔ UniProt

The default mapping behavior is intentionally opinionated for the common biomedical case: humanorganism_id=9606reviewed=True. These filters can be overridden.

import research_toolbox as rt

rt.gene_to_uniprot("TP53")
# 'P04637'

rt.uniprot_to_gene("P04637")
# 'TP53'

rt.genes_to_uniprot(["TP53", "EGFR", "BRCA1"])
rt.uniprots_to_gene(["P04637", "P00533", "P38398"])

# mouse
rt.gene_to_uniprot("Trp53", organism_id=10090)

# include reviewed and unreviewed entries
rt.gene_to_uniprot("TP53", reviewed=None)

# keep every match
rt.gene_to_uniprot("TP53", all_matches=True)

Cached client

client = rt.UniProtClient(cache=rt.open_cache(".cache/uniprot"))
uid = rt.gene_to_uniprot("TP53", client=client)
record = client.uniprot_to_record("P04637")

record.accession
record.gene_name
record.entry_name
record.organism_id
record.reviewed
record.protein_name

Network/API failures raise exceptions; a valid query with no match returns None. This keeps “not found” distinct from “request failed.”

Evaluation

APINotes
evaluate_binary
compute_binary_metrics
Accuracy, balanced accuracy, precision, recall, specificity, F1, F2, G-mean, MCC, Cohen's κ, Brier score, AUROC, AUPR, and log loss. Single-class AUROC/AUPR are returned as nan.
summarize_runs
summarize_evaluations
summarize_binary_metrics
Summarize repeated runs into a pandas DataFrame with mean/std/n. summarize_runs is the recommended name.
run1 = rt.evaluate_binary(y_true, pred_seed_1)
run2 = rt.evaluate_binary(y_true, pred_seed_2)
run3 = rt.evaluate_binary(y_true, pred_seed_3)
summary = rt.summarize_runs([run1, run2, run3])

Chemistry

APIPurpose
fingerprint
smiles_to_morgan_fingerprint
SMILES → Morgan bit vector (NumPy array).
fingerprints
smiles_to_morgan_fingerprints
Batch conversion preserving input order.
fp = rt.fingerprint(
    "CCO",
    radius=2,
    n_bits=2048,
    use_chirality=True,
    on_error="raise",   # "raise" | "none" | "zero"
)

RDKit is an optional dependency. Invalid-SMILES behavior is explicit rather than silently substituting a plausible-looking vector.

Caching

JSONFileCache stores one JSON-serializable value per hashed key and writes atomically.

cache = rt.open_cache(".cache")
cache["result"] = {"score": 0.91}
result = cache["result"]

"result" in cache
len(cache)
cache.delete("result")
cache.clear()

value = cache.get_or_set("expensive", expensive_function)
value = rt.cached_lookup(cache, "expensive", expensive_function)
MethodPurpose
get(key, default=None)Read a cached value.
set(key, value)Atomically write a value.
get_or_set(key, fetcher, cache_none=True)Compute only on cache miss.
contains(key)Check key presence.
delete(key)Delete one entry.
clear()Remove all JSON cache entries.

Biomedical text

APIPurpose
read_pmc
extract_pmc_sections
Heuristically extract Abstract, Introduction, Methods, Results, and Discussion-like sections from JATS/PMC XML.
normalize_drug / normalize_drug_nameWhitespace normalization + lowercase.
normalize_gene / normalize_gene_nameWhitespace normalization + uppercase.
normalize_protein / normalize_protein_nameWhitespace normalization + uppercase.
normalize_text / clean_text_for_matchingCollapse whitespace + lowercase free text.
Normalization helpers are string normalization only. They are not biomedical entity resolution. Use the UniProt mapping utilities when identifier resolution is needed.

Reproducibility

info = rt.seed(42, deterministic=True)
# alias: from reproducibility import seed_everything

Seeds Python, NumPy, PyTorch CPU, and CUDA when PyTorch is installed. Deterministic execution can affect speed and does not guarantee bitwise identity across different hardware/software stacks.

Visualization

The plotting API is optimized for publication figures that remain editable in Adobe Illustrator: Arial-first, all shared text defaults at 10 pt, PDF/PS Type 42 fonts, SVG text preserved as text, vector-first export, and 600 dpi raster fallback.

fig, ax = rt.viz.scatter(
    y_true, y_pred,
    xlabel="Observed",
    ylabel="Predicted",
    identity_line=True,
)
rt.viz.save(fig, "figures/prediction")
APIPurpose
rt.viz.linePublication-ready line plot.
rt.viz.scatterScatter plot with optional identity line.
rt.viz.barBar plot with optional errors / horizontal layout.
rt.viz.grouped_barGrouped bars from named series.
rt.viz.boxBox plot with optional raw-point overlay.
rt.viz.heatmapDependency-light Matplotlib heatmap.
rt.viz.saveExport PDF/SVG/PNG (or selected formats).
FigureConfigReusable width/font/line/marker/DPI configuration; default font size is 10 pt.
SINGLE_COLUMN89 mm publication preset.
DOUBLE_COLUMN178 mm publication preset.
new_figureCreate a styled Matplotlib figure.
illustrator_styleTemporary style context manager.
set_illustrator_styleApply style globally.
style_axisApply shared styling to an existing axis.
add_panel_labelAdd panel labels such as A/B/C.
label_panelsSequentially label multiple axes.
add_significance_barAdd a significance bracket and label.
figure_sizeConvert target publication width to Matplotlib figsize.
mm_to_inchesMillimeter → inch conversion.

Domain imports

The facade is recommended, but explicit imports remain supported.

from evaluation import evaluate_binary, compute_binary_metrics
from chemistry import fingerprint, smiles_to_morgan_fingerprint
from caching import open_cache, JSONFileCache, cached_lookup
from biomed import (
    read_pmc,
    normalize_gene,
    gene_to_uniprot,
    uniprot_to_gene,
    UniProtClient,
)
from reproducibility import seed, seed_everything
from visualization import scatter, save, FigureConfig

Source and maintenance

GitHub repository →

This page is a human-readable API catalog. When the toolbox changes, this page should be updated alongside the public facade and module __all__ exports.

← Back to projects