BioMetaHarmonizer
A Python package for fetching, parsing, and standardizing NCBI BioSample metadata for large-scale genomic epidemiology.
What it does
NCBI BioSample metadata is free-text, crowd-sourced, and inconsistent across submitters. BioMetaHarmonizer fetches BioSample XML records via the Entrez API, maps raw attribute names to a fixed set of standard columns, normalizes placeholder null values, parses dates and geographic strings, and assigns One Health categories. The result is a pandas DataFrame that can be written to CSV, TSV, Excel, Parquet, or JSON Lines (JSONL) — including multiple formats in a single run.
Input can be BioSample accessions (SAMN, SAME, SAMD), assembly accessions (GCF_, GCA_), or a mix of both. Assembly accessions are resolved to BioSample IDs through locally cached NCBI assembly summary flat files.
Optional post-processing extends the harmonized output with decimal coordinates, submitted host health-state metadata, and standards-oriented field aliases. It can also fill missing derived country fields using a bundled offline polygon reference. Native metadata and One Health predictions are preserved, and a separate diagnostic report records parsing issues, conflicting sources, country-assignment provenance, and coordinate-datum assumptions.
Installation
Install from PyPI:
pip install biometaharmonizer
To use coordinate-derived country inference during post-processing, install the geographic extra:
pip install "biometaharmonizer[geo]"
Requires Python 3.9+. Dependencies are declared in pyproject.toml and installed automatically.
Development install (editable, from source):
git clone https://github.com/rustam-bioinfo/BioMetaHarmonizer.git
cd BioMetaHarmonizer
pip install -e .
The package ships with a minimal hand-curated one_health_dictionaries.json. For complete One Health classification — in particular, full NCBI taxonomy coverage of host species names — rebuild this file before use. See Rebuilding schema files.
Quick start
Command line
# Single output file (format inferred from extension)
biometaharmonizer run \
--input accessions.txt \
--email your@email.com \
--output harmonized.csv
# Process large datasets using the maximum allowed batch sizes and an NCBI API key
biometaharmonizer run \
--input accessions.txt \
--email your@email.com \
--output harmonized.csv \
--fetch-batch-size 500 \
--esearch-batch-size 500 \
--api-key KEY
# Save to multiple formats in one run
biometaharmonizer run \
--input accessions.txt \
--email your@email.com \
--output harmonized.csv \
--format csv tsv excel
# Produces: harmonized.csv, harmonized.tsv, harmonized.xlsx
# Run with optional metadata enrichment
biometaharmonizer run \
--input accessions.txt \
--email your@email.com \
--output harmonized_extended.csv \
--postprocess \
--postprocess-report postprocess_diagnostics.csv
# Produces: harmonized_extended.csv: the extended metadata output;
# postprocess_diagnostics.csv: a separate report containing coordinate-parsing statuses, country-lookup results, conflicts, and assignment provenance.
| Flag | Default | Description |
|---|---|---|
--input FILE |
required | Path to accession list (one per line) |
--email EMAIL |
required | Valid contact email for NCBI Entrez — must contain @ and a domain |
--output FILE |
required | Output file path (used as the base name for multi-format output) |
--api-key KEY |
— | NCBI API key; raises rate limit from 3 to 10 requests/second |
--cache-dir DIR |
~/.biometaharmonizer/cache/ |
Directory for assembly summary flat files |
--format FORMAT [FORMAT ...] |
inferred from file extension | One or more of: csv, tsv, excel, parquet, jsonl. When multiple formats are given the stem of --output is reused and the correct extension is substituted for each format. Omit to infer from the output file extension. |
--summary FILE |
— | Write a per-column fill-rate CSV |
--fetch-batch-size N |
200 |
Number of records per efetch request |
--esearch-batch-size N |
200 |
Number of accessions per esearch term |
--refresh-cache |
off | Force re-download of assembly summary flat files regardless of age |
--verbose |
off | Enable DEBUG-level logging |
--postprocess |
off | Append coordinate, health-state, and standards-oriented fields before export. Includes conservative offline inference of missing derived country fields; requires the geographic extra when lookup is needed |
--postprocess-report FILE |
— | Write row-level post-processing diagnostics to CSV. Requires post-processing to be enabled |
Post-processing runs once before export, so all output formats receive the same extended DataFrame. The diagnostic report is separate from the harmonized output and must not overwrite the input, output, or summary file.
Output columns
The output DataFrame contains 53 columns. Columns with no data for a given dataset are present and filled with NaN. Attributes that do not map to any column are preserved as a JSON string in _extra_attributes.
Optional post-processing appends ten columns, producing 63 columns for a canonical 53-column input. Native columns remain unchanged.
| # | Column | Source | Description |
|---|---|---|---|
| 1 | biosample_accession |
BioSample XML | NCBI BioSample accession (e.g. SAMN07597573) |
| 2 | biosample_id |
BioSample XML | NCBI internal numeric BioSample ID |
| 3 | sra_accession |
BioSample XML | Linked SRA accession, if present |
| 4 | bioproject_accession |
BioSample XML / assembly index | Parent BioProject accession |
| 5 | assembly_accession_refseq |
Assembly index | RefSeq assembly accession (GCF_) |
| 6 | assembly_accession_genbank |
Assembly index | GenBank assembly accession (GCA_) |
| 7 | sample_name_id |
BioSample XML | Submitter sample name from <Id db_label="Sample name"> |
| 8 | taxonomy_id |
BioSample XML | NCBI Taxonomy numeric ID |
| 9 | taxonomy_name |
BioSample XML | Taxon name for the assigned taxonomy_id |
| 10 | organism_name |
BioSample XML | Organism name from <OrganismName>; falls back to taxonomy_name |
| 11 | isolate |
BioSample attribute | Isolate identifier |
| 12 | strain |
BioSample attribute | Strain designation |
| 13 | sub_strain |
BioSample attribute | Sub-strain designation |
| 14 | serotype |
BioSample attribute | Serotype |
| 15 | serovar |
BioSample attribute | Serovar |
| 16 | genotype |
BioSample attribute | Genotype or sequence type |
| 17 | culture_collection |
BioSample attribute | Culture collection identifier |
| 18 | host |
BioSample attribute | Host organism name |
| 19 | host_disease |
BioSample attribute | Disease associated with host at sampling |
| 20 | host_age |
BioSample attribute | Age of host |
| 21 | host_sex |
BioSample attribute | Biological sex of host |
| 22 | host_tissue_sampled |
BioSample attribute | Tissue or body site sampled |
| 23 | isolation_source |
BioSample attribute | Material or environment from which the isolate was obtained |
| 24 | sample_type |
BioSample attribute | Sample type or specimen classification |
| 25 | env_broad_scale |
BioSample attribute | Broad environmental context (ENVO) |
| 26 | env_local_scale |
BioSample attribute | Local environmental feature (ENVO) |
| 27 | env_medium |
BioSample attribute | Environmental medium (ENVO) |
| 28 | geo_loc_name |
BioSample attribute | Raw geographic location string as submitted |
| 29 | lat_lon |
BioSample attribute | Decimal lat/lon as submitted |
| 30 | geo_country |
GeoEngine | Country resolved from geo_loc_name |
| 31 | geo_region |
GeoEngine | Sub-national region; populated only from colon-format inputs ("Country: Region, Locality"); NaN for comma-only inputs |
| 32 | geo_locality |
GeoEngine | Locality after the region in colon format, or the part after the first comma in comma-only inputs |
| 33 | geo_iso3166 |
GeoEngine | ISO 3166-1 alpha-2 country code; historical names tagged HISTORICAL |
| 34 | geo_sea_ocean |
GeoEngine | Named aquatic feature from geo_loc_name — covers oceans, seas, gulfs, bays, straits, fjords, lakes, reservoirs, and other water bodies |
| 35 | collection_date |
BioSample attribute → DateEngine | Collection date or supported timestamp normalized to ISO 8601 while preserving supplied precision |
| 36 | collection_date_range |
DateEngine | Verbatim original string for range/approximate date inputs; NaN for point dates |
| 37 | one_health_category |
OneHealthClassifier | One of: Human, Animal, Plant, Food, Environmental, Unclassified |
| 38 | one_health_confidence |
OneHealthClassifier | Float in [0, 1] — see One Health classification |
| 39 | one_health_evidence_level |
OneHealthClassifier | Discretized confidence: high (≥0.85), medium (≥0.60), low (≥0.30), unresolved |
| 40 | outbreak |
BioSample attribute | Outbreak identifier |
| 41 | sequencing_method |
BioSample attribute | Sequencing platform |
| 42 | assembly_method |
BioSample attribute | Genome assembly software |
| 43 | collected_by |
BioSample attribute; <Owner/Name> fallback |
Collector name or institution |
| 44 | ncbi_package |
BioSample XML | NCBI BioSample package (e.g. Microbe.1.0) |
| 45 | submission_date |
BioSample XML | Date first submitted |
| 46 | last_update |
BioSample XML | Date last modified |
| 47 | publication_date |
BioSample XML | Date made publicly available |
| 48 | access |
BioSample XML | public or controlled-access |
| 49 | status |
BioSample XML | Record status (e.g. live, suppressed) |
| 50 | status_date |
BioSample XML | Date current status was assigned |
| 51 | title |
BioSample XML | Free-text title of the BioSample record |
| 52 | description_comment |
BioSample XML | Free-text description or comment block |
| 53 | _extra_attributes |
JSON | All attributes that could not be mapped to a schema column, serialized as a JSON dict. Also contains submission_owner and submission_contact when <Owner> provenance is present alongside an explicit collector. For records submitted under pathogen packages, contains an antibiogram key (see Antibiogram data). |
Optional post-processing columns
| # | Additional column | Source or rule |
|---|---|---|
| 1 | decimalLatitude |
Parsed latitude from lat_lon or separate coordinate attributes in _extra_attributes |
| 2 | decimalLongitude |
Parsed longitude from the same validated coordinate pair |
| 3 | host_health_state |
Submitted health-state metadata recovered from _extra_attributes; not an inferred diagnosis |
| 4 | seq_meth |
Copy of sequencing_method |
| 5 | assembly_software |
Copy of assembly_method |
| 6 | host_disease_stat |
Copy of host_disease, independently of host_health_state |
| 7 | country |
Copy of geo_country, with coordinate-derived fallback only when both derived country fields are absent |
| 8 | countryCode |
Normalized ISO alpha-2 code from geo_iso3166, subject to the same fallback policy |
| 9 | waterBody |
Copy of geo_sea_ocean |
| 10 | locality |
Direct copy of geo_loc_name, without reconstructing it from parsed region or locality fields |
These aliases provide naming correspondences to MIxS and Darwin Core terms. They do not certify full standards compliance or validate source semantics, controlled vocabularies, software versions, or submission checklists.
Non-ISO markers such as HISTORICAL and XK remain in the native geographic fields but are not exported as countryCode.
Antibiogram data
BioSample records submitted under NCBI pathogen packages (Pathogen.cl.1.0, Pathogen.env.1.0, etc.) may include a structured <Antibiogram> section that is a sibling of <Attributes> in the XML. BioMetaHarmonizer parses it explicitly.
When an antibiogram is present, _extra_attributes["antibiogram"] contains a compact JSON-encoded list of dicts, one per antibiotic row. Each dict includes whichever of the following fields NCBI populated for that row:
| Field | Description |
|---|---|
antibiotic_name |
Antibiotic name (e.g. amikacin) |
resistance_phenotype |
susceptible, resistant, or intermediate |
measurement_sign |
==, <=, >=, <, > |
measurement |
Numeric MIC or disk diffusion value |
measurement_units |
mg/L, mm, etc. |
laboratory_typing_method |
MIC, disk diffusion, etc. |
laboratory_typing_platform |
Instrument or method platform |
vendor |
Reagent/kit vendor |
laboratory_typing_method_version_or_reagent |
Version or reagent identifier |
testing_standard |
CLSI, EUCAST, etc. |
Fields with null or missing values are omitted from each row dict so the JSON payload stays compact. Rows where all fields resolved to null are excluded entirely.
Extracting antibiogram data from a result DataFrame:
import json
import pandas as pd
def extract_antibiogram(df):
rows = []
for _, rec in df.iterrows():
extras = rec.get("_extra_attributes")
if not extras:
continue
try:
d = json.loads(extras)
except (ValueError, TypeError):
continue
ab = d.get("antibiogram")
if not ab:
continue
ab_rows = json.loads(ab) if isinstance(ab, str) else ab
for row in ab_rows:
row["biosample_accession"] = rec["biosample_accession"]
rows.append(row)
return pd.DataFrame(rows)
antibiogram_df = extract_antibiogram(df)
Attribute resolution order
For each <Attribute> element in BioSample XML, the output field is resolved in the following order:
-
harmonized_namedirect match: after stripping surrounding whitespace, an exact, case-sensitive match to a schema column is used without synonym lookup. -
Synonym lookup on
harmonized_name: otherwise, the harmonized name is looked up case-insensitively in the synonym table. If the mapped target is a schema column, that column is used. If the target is outside the schema, the non-null value is retained in_extra_attributesunder the mapped target name. In this case,attribute_nameis not tried afterward. -
Synonym lookup on
attribute_name: if neither preceding condition matches, the stripped raw attribute name is looked up case-insensitively in the synonym table. A schema target is used as the output column; a non-schema target is used as the key in_extra_attributes. -
Unresolved attributes: if no mapping is found, non-null values are retained in
_extra_attributesunder the strippedharmonized_name, falling back toattribute_name, then"unknown"if neither name is available.
Missing-value placeholders are normalized before values are assigned to output columns or retained in _extra_attributes.
Synonym sources and precedence
The synonym table is built by build_synonym_lookup() in synonyms.py and cached for the lifetime of the process:
schemas/unified.jsonsupplies project-defined standard keys and curated synonyms.schemas/ncbi_attributes.xml, supplies mappings from the official NCBI BioSample attribute harmonization table.- Project-defined mappings take precedence over NCBI mappings for the same lookup key.
Attribute collisions
When multiple non-null attributes resolve to the same output column, the priority table derived from unified.json determines which value is retained:
- The standard key itself has rank
0, the highest priority. - Synonyms have ranks
1onward, following their order in the field's synonym list. - Source keys without an explicit priority entry default to rank
999. - A lower numerical rank takes precedence. If ranks are equal, the existing value is retained.
- Displaced or lower-priority non-null values are preserved in
_extra_attributesunder_dup_<column>. Multiple values under the same extra key are joined with|.
Attribute-name resolution occurs during BioSample XML ingestion, and the returned DataFrame already conforms to the canonical output schema. No separate column-mapping step is required.
Null normalization
During XML parsing, placeholder values are converted to None before any downstream processing. The full pattern list covers:
missing,missing: lab stock,missing: data agreement established ...N/A,na,null,none,nil,-,.unknown,not provided,not collected,not applicable,not available,not determined,not recorded,not reportedunavailable,unspecified,undetermined,unidentifiedrestricted,restricted access,withheld,confidentialtbd,tba
Common misspellings (misssing, unkown, unknwon) are also matched. Matching is case-insensitive.
Assembly summary cache
On the first run, ingest() downloads two NCBI flat files to resolve assembly accessions and BioProject links:
assembly_summary_refseq.txt(~200 MB)assembly_summary_genbank.txt(~1.5 GB)
These are cached in ~/.biometaharmonizer/cache/ (overridable with --cache-dir or set_cache_dir()). Files older than 7 days are automatically deleted and re-downloaded on the next run.
To force a refresh before the 7-day TTL expires — for example, immediately after a large batch of new assemblies is added to NCBI — pass refresh_cache=True to ingest() or use --refresh-cache on the CLI:
biometaharmonizer run --input ids.txt --email you@example.com \
--output out.csv --refresh-cache
df = ingest("ids.txt", email="you@example.com", refresh_cache=True)
Entrez rate limits
Without an API key, NCBI allows 3 requests per second. With a key, the limit is 10 requests per second. BioMetaHarmonizer enforces inter-request sleep intervals automatically based on whether an API key is set.
Register a free API key at https://www.ncbi.nlm.nih.gov/account/ and pass it as:
biometaharmonizer run --input ids.txt --email you@example.com \
--api-key YOUR_KEY --output out.csv
or:
df = ingest("ids.txt", email="you@example.com", api_key="YOUR_KEY")
Geospatial parsing
GeoEngine splits geo_loc_name into five structured columns: geo_country, geo_region, geo_locality, geo_iso3166, and geo_sea_ocean.
The parser recognizes two input formats:
- Colon format
"Country: Region, Locality"— the part before:becomesgeo_country, the first segment after:becomesgeo_region, and any remainder after the comma becomesgeo_locality. - Comma-only format
"Country, Locality"— the part before the first,becomesgeo_countryand the remainder becomesgeo_locality.geo_regionis leftNaN.
Parenthetical qualifiers (e.g. "United Kingdom (England, Wales & N. Ireland)", "Pacific Ocean (NE)", "Russia (European part)") are stripped from the country token before any lookup. This means both country names and water body names with parenthetical qualifiers are correctly resolved — countries are not missed by pycountry and water bodies are not misrouted to the country resolver.
Water body detection (geo_sea_ocean) uses a two-tier lookup. Tier 1 is an explicit set of canonical names that covers all major oceans, seas, gulfs, bays, and straits — matched with an exact case-insensitive lookup for correctness and explicitness. Names in this set are consciously verified, and entries like "English Channel" and "Mozambique Channel" bypass the regex false-positive risk entirely because they are resolved before Tier 2 runs. Tier 2 is a regex fallback that catches any token containing a water-body keyword (ocean, sea, gulf, bay, strait, fjord, bight, sound, inlet, lagoon, lake, reservoir, estuary, delta, reef, atoll) not already in Tier 1. A negative lookahead blocks known false positives: "Channel Islands", "Gulf States", "British Indian Ocean Territory", and similar compound names where the keyword is part of a political entity name rather than a water body.
Coordinate data (e.g. "40.71 N, 74.00 W") belongs in the lat_lon attribute, not geo_loc_name. Strings submitted to geo_loc_name that look like coordinates are treated as unparseable and return all-NaN geo columns.
| Input | Result |
|---|---|
"USA: California, Los Angeles" |
country=USA, region=California, locality=Los Angeles, iso=US |
"USA: California" |
country=USA, region=California, iso=US |
"Germany, Bavaria" |
country=Germany, locality=Bavaria, iso=DE |
"France" |
country=France, iso=FR |
"Pacific Ocean" |
sea_ocean=Pacific Ocean |
"Pacific Ocean (NE)" |
sea_ocean=Pacific Ocean |
"Pacific Ocean: Mariana Trench" |
sea_ocean=Pacific Ocean, locality=Mariana Trench |
"Red Sea (sampling site 3): surface" |
sea_ocean=Red Sea, locality=surface |
"Gaza Strip" |
country=Gaza Strip, iso=PS |
"West Bank" |
country=West Bank, iso=PS |
"United Kingdom (England, Wales & N. Ireland)" |
country=United Kingdom, iso=GB |
"not applicable" |
all geo columns NaN |
"Lake Baikal" |
sea_ocean=Lake Baikal |
"Gulf of Bothnia" |
sea_ocean=Gulf of Bothnia |
"Svalbard: Revvatnet basin, southern Spitsbergen" |
country=Svalbard, region=Revvatnet basin, locality=southern Spitsbergen, iso=SJ |
"Kosovo" |
country=Kosovo, iso=XK |
Handling notes:
England,Scotland,Wales,Northern Ireland→United Kingdom, isoGBUnited Kingdom (England, Wales & N. Ireland)and similar compound UK variants →United Kingdom, isoGBGaza Strip,West Bank,Gaza,Palestine,Palestinian territories→ isoPSKorea(bare, no qualifier) → South Korea (KR); logged at INFO level- Historical country names (
USSR,Yugoslavia,Zaire,East Germany, etc.) → preserved ingeo_country,geo_iso3166 = HISTORICAL Turkey/Türkiye,Namibia,Burma,DR Congo,Russia,Czech Republic,Svalbard,Kosovo, and several other names are resolved via a hardcoded alias table before pycountry fuzzy lookup.Kosovouses codeXK— a user-assigned code per CLDR and EU conventions, not part of the official ISO 3166-1 standard.- All unique
geo_loc_namevalues are resolved once and cached; pycountry fuzzy lookup runs at most once per unique country string regardless of row count
Date and timestamp parsing
DateEngine preserves the supplied precision of supported collection dates and timestamps. Outputs may contain a year, year and month, full calendar date, or timestamp with explicit clock time. Supplied fractional seconds and resolved timezone offsets are preserved rather than reducing timestamps to calendar dates.
Timestamps require an explicit complete calendar date. Missing times and timezones are not inferred. Unknown timezone abbreviations are rejected with a warning rather than silently discarded.
Ranges and approximate dates remain separate from point dates: collection_date is missing, and collection_date_range retains the original stripped input. Supported timestamp intervals follow the same policy.
One Health classification
OneHealthClassifier loads all biological knowledge from schemas/one_health_dictionaries.json and assigns each record one of six categories: Human, Animal, Plant, Food, Environmental, Unclassified.
classify_multi_field() accepts up to six named pd.Series and returns a DataFrame with seven columns:
| Column | Type | Description |
|---|---|---|
one_health_category |
str | Assigned category; always a string, never NaN |
one_health_term |
str / NaN | The specific term or phrase that triggered the classification |
one_health_confidence |
float | Score in [0, 1]; computed as term_specificity × field_weight + corroboration_bonus |
one_health_evidence_level |
str | high (≥0.85), medium (≥0.60), low (≥0.30), unresolved |
one_health_processing |
str / NaN | Processing/handling term detected in the text (e.g. pasteurized, frozen) |
one_health_setting |
str / NaN | Setting term detected in the text (e.g. clinical, farm, retail) |
one_health_source_field |
str / NaN | Input field that produced the winning classification |
Confidence model. For each field, confidence = min(1.0, term_specificity × field_weight + corroboration_bonus):
term_specificity: 1.0 for host dictionary or unambiguous list hits; 0.90/0.75/0.50 for tier1 phrases by length;WRatio / 100for rapidfuzz fallback; 0.30 for ambiguous terms.field_weight:isolation_source/ host dict hit → 1.00; host text hit → 0.90;env_medium→ 0.85;env_local_scale→ 0.80;sample_type→ 0.70;env_broad_scale→ 0.50.corroboration_bonus: +0.10 when a second independent field agrees with the same category.
Classification pipeline per record:
hostfield: institution guard (strips culture collection prefixes; returns Lab if residual < 4 chars), then bracket/parenthesis annotation stripping (e.g.[NCBITaxon:9825],(Linnaeus 1758)), thenhost_to_categorydictionary lookup with progressive right-token-drop fallback for trinomial/subspecies names, then text classification fallback.isolation_source,env_medium,env_local_scale: matched against unambiguous human/animal term lists, then tier1 patterns, then rapidfuzz fuzzy fallback against the ontology map.sample_type: domain-level signal; used to set category if no specimen field matched.env_broad_scale: supporting signal only; contributes a corroboration bonus but does not set the primary category on its own.- Pass 2 resolves the winning category from accumulated domain/specimen/supporting evidence.
Host trinomial / subspecies fallback. When a host value like Equus ferus caballus is not found as an exact entry in host_to_category, the classifier progressively drops tokens from the right (Equus ferus, then Equus) until a match is found or all prefixes are exhausted. This fallback is active only when every token in the name is composed solely of letters or hyphens (no digits or strain identifiers), so free-text phrases are never misclassified via this path. The bundled one_health_dictionaries.json contains only a hand-curated seed; after running biometaharmonizer build-dicts the full NCBI taxonomy is present and the fallback is rarely needed.
collected_by priority
- Explicit BioSample attribute — any
<Attribute harmonized_name="collected_by">or synonym is always preferred. <Owner/Name>fallback — used only if no explicit collector attribute was found.
When both are present, the submission-side provenance is written to _extra_attributes:
submission_owner—<Owner/Name>valuesubmission_contact— full name from<Owner/Contacts/Contact>
Output formats
from biometaharmonizer import write, write_summary
write(df, "out.csv") # CSV
write(df, "out.tsv", fmt="tsv") # TSV
write(df, "out.xlsx", fmt="excel") # Excel
write(df, "out.parquet", fmt="parquet") # Parquet
write(df, "out.jsonl", fmt="jsonl") # JSON Lines (one record per line)
write_summary(df, "fill_rates.csv") # column, non_null_count, fill_pct
Format strings are case-insensitive. If --format is not specified on the CLI, the format is inferred from the output file extension (.jsonl → jsonl).
The JSONL writer decodes the _extra_attributes field from its JSON string representation into a native Python dict before serialization, so downstream consumers receive a fully nested JSON object rather than a double-encoded string.
Multi-format output
Pass multiple space-separated format names to --format to write all formats in a single pipeline run. The stem of --output is reused and the correct extension is substituted automatically:
biometaharmonizer run \
--input ids.txt \
--email you@example.com \
--output results/harmonized.csv \
--format csv tsv parquet jsonl
# Writes:
# results/harmonized.csv
# results/harmonized.tsv
# results/harmonized.parquet
# results/harmonized.jsonl
When only a single format is given, the --output path is used exactly as specified.
| Format | Extension substituted |
|---|---|
csv |
.csv |
tsv |
.tsv |
excel |
.xlsx |
parquet |
.parquet |
jsonl |
.jsonl |
Rebuilding schema files
The package ships with pre-built schema files. These are sufficient for basic use, but rebuilding them is strongly recommended before processing large or taxonomically diverse datasets.
build-dicts — One Health dictionary
The bundled one_health_dictionaries.json is a minimal hand-curated seed. It covers common host names and key ontology terms, but it does not include the full NCBI taxonomy. Without rebuilding, trinomial host names (e.g. Equus ferus caballus, Bos taurus indicus) and many uncommon species will fall back to the progressive prefix-drop heuristic instead of resolving from an authoritative entry.
To build the full dictionary, run:
biometaharmonizer build-dicts
This queries the OLS4 API (ENVO, FoodOn, UBERON, Plant Ontology) and downloads the NCBI taxonomy dump (~65 MB) to populate host_to_category with scientific names, common names, and equivalent names for all vertebrates and plants. The full build takes a few minutes depending on network speed.
Options:
| Flag | Description |
|---|---|
--base FILE |
Path to the hand-curated base JSON (default: bundled schemas/one_health_dictionaries.json) |
--output FILE |
Destination path for the enriched JSON (default: same as --base) |
--taxdmp PATH |
Path to a pre-downloaded taxdmp.zip or an extracted directory containing names.dmp and nodes.dmp. Skips the ~65 MB NCBI download. |
--skip-ncbi |
Skip NCBI taxonomy entirely (OLS4 terms only). |
--skip-ols |
Skip OLS4 queries (NCBI taxonomy only). |
--umls-key KEY |
Optional UMLS API key for additional synonym expansion. |
--dry-run |
Run all enrichment steps but do not write the output file. |
--verbose-collisions |
Print per-term collision detail. Silent by default. |
The hand-curated entries in the base file always win over ontology-derived data (merge_strategy: base_wins).
build-ncbi-cache — NCBI attribute table
Downloads the official NCBI BioSample attribute harmonization table and stores it as schemas/ncbi_attributes.xml.
biometaharmonizer build-ncbi-cache
Options:
| Flag | Description |
|---|---|
--output-dir DIR |
Directory to write ncbi_attributes.xml into (default: bundled schemas/) |
--skip-fetch |
Skip the network request; only validate an existing ncbi_attributes.xml in the output directory |
generate-report — Interactive HTML report
Generates an interactive, self-contained HTML report from a BioMetaHarmonizer output file. The report includes metadata completeness (fill rates), geographic distribution, temporal trends, taxonomy, One Health breakdown, and a searchable paginated data table — all embedded in a single HTML file with no server required.
# Output defaults to harmonized_report.html next to the input file
biometaharmonizer generate-report harmonized.csv
# Specify a custom output path
biometaharmonizer generate-report harmonized.csv report.html
| Argument | Description |
|---|---|
input |
Path to a BioMetaHarmonizer output file (.csv, .tsv, .xlsx, .parquet) |
output |
(optional) Output .html path. Defaults to <stem>_report.html next to the input. |
Requires plotly (loaded from CDN — no local install needed at runtime) and pandas. For Excel input, also install openpyxl.
Repository structure
BioMetaHarmonizer/
├── src/biometaharmonizer/
│ ├── __init__.py # public API
│ ├── cli.py # CLI entrypoint (run, build-dicts, build-ncbi-cache, generate-report)
│ ├── ingestion.py # retrieval, XML parsing, attribute harmonization, fixed-schema output
│ ├── synonyms.py # two-layer synonym lookup (unified.json + NCBI XML)
│ ├── date_engine.py # date parsing, ISO 8601 output
│ ├── geo_engine.py # geo_loc_name splitting, ISO-3166 resolution
│ ├── one_health.py # One Health categorization
│ ├── output.py # write CSV / TSV / Excel / Parquet / JSONL
│ ├── schemas/
│ │ ├── unified.json # standard keys + synonym lists
│ │ ├── one_health_dictionaries.json # One Health keyword/ontology dict
│ │ └── ncbi_attributes.xml # NCBI harmonization table (optional)
│ └── scripts/
│ ├── __init__.py # exposes subcommand modules
│ ├── generate_summary_report.py # module for generate-report
│ ├── build_dictionaries.py # module for build-dicts
│ └── build_ncbi_attribute_cache.py # module for build-ncbi-cache
├── tests/
└── pyproject.toml
Python API
from biometaharmonizer.ingestion import set_email, ingest
from biometaharmonizer DateEngine, GeoEngine, OneHealthClassifier
from biometaharmonizer import write, write_summary
# Ingest: accepts a file path, a Python list, or a mix of both accession types
# Attribute names and missing-value placeholders are normalized during ingestion.
# The returned DataFrame already uses the canonical output columns.
set_email("your@email.com")
df = ingest("accessions.txt")
# or: df = ingest(["SAMN12345678", "GCF_000001405.39"])
# Force re-download of assembly summary flat files (bypasses 7-day TTL):
# df = ingest("accessions.txt", refresh_cache=True)
# Date parsing: 40+ input formats -> ISO 8601 (YYYY / YYYY-MM / YYYY-MM-DD)
de = DateEngine()
date_df = de.parse_with_range(df["collection_date"])
df["collection_date"] = date_df["collection_date"]
df["collection_date_range"] = date_df["collection_date_range"]
# Geography: splits geo_loc_name into country, region, locality, ISO code, sea
ge = GeoEngine()
geo_df = ge.parse(df["geo_loc_name"])
for col in geo_df.columns:
df[col] = geo_df[col]
# One Health classification across multiple source columns simultaneously
oh = OneHealthClassifier()
src = {col: df[col] for col in
["isolation_source", "env_broad_scale", "env_local_scale",
"env_medium", "sample_type", "host"]
if col in df.columns}
oh_df = oh.classify_multi_field(**src)
for col in oh_df.columns:
df[col] = oh_df[col]
# Write output
write(df, "harmonized.csv")
write_summary(df, "fill_rates.csv")
License
MIT
Metadata
Release files for biometaharmonizer 1.0.9
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| biometaharmonizer-1.0.9.tar.gz | 5.1 MB | With provenance | Details for biometaharmonizer-1.0.9.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| biometaharmonizer-1.0.9-py3-none-any.whl | Python 3 | none | any | Details for biometaharmonizer-1.0.9-py3-none-any.whl |
Total release size: 10.2 MB
Release files / biometaharmonizer-1.0.9.tar.gz
| Download URL | biometaharmonizer-1.0.9.tar.gz |
|---|---|
| Size | 5.1 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a2ce838ab61af4450298e99f7c1be3ce19fe8f16166e0d5697d80c69de0b215c
|
|
BLAKE2b-256 checksum How to use checksums |
df47e88aee2d15be9b281dc315c068602d49d3546ff5b0e3ccf97acbc001ea6f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 22, 2026.
Transparency logRelease files / biometaharmonizer-1.0.9-py3-none-any.whl
| Download URL | biometaharmonizer-1.0.9-py3-none-any.whl |
|---|---|
| Size | 5.1 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
d5c3e45a43fef4c786eb2e9689348b5b87bda88d9243a4f2ad29883d4a1964d9
|
|
BLAKE2b-256 checksum How to use checksums |
779f8969d2ed5f96cf851e4dd411c19f4187020d2310c7b4e14a701717f0feb8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 22, 2026.
Transparency logSecurity for biometaharmonizer 1.0.9
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for biometaharmonizer-1.0.9.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 22, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.