Przejdź do głównej zawartości

Convert HGVS to genomic coordinates in pandas

When a CSV contains HGVS strings from several sources, convert them to a common hg38 representation before joining or annotating the data. A coding or genomic expression may give one allele, while a protein expression may give several. Keep the candidate alleles linked to the source row so you can review them later.

Read the CSV and convert the HGVS column​

Install the dependencies with python -m pip install pandas requests. The sample CSV is embedded so you can run the example directly. To use your own file, pass its path to pd.read_csv and keep the hgvs column as text. Use versioned accessions when you have them.

Send a JSON array of expression strings to POST /cloud/api-public/v2/convert. Each result includes a status and may include candidates, warnings and errors. This example sends blank expressions straight to the review table and preserves the order of the other results.

from io import StringIO

import pandas as pd
import requests

demo_csv = """hgvs,source
NM_000492.3:c.983T>A,table A
NC_000016.10:g.68829788del,table A
AGT:p.Met259Ser,table B
invalid-hgvs,table B
"""
source = pd.read_csv(StringIO(demo_csv), dtype={"hgvs": "string"})
source.insert(0, "row_id", source.index)
source["query"] = source["hgvs"].str.strip().fillna("")
queries = source.loc[source["query"].ne(""), "query"]

ready_rows = []
review_rows = [
{"row_id": row_id, "status": "MISSING_INPUT", "issue_codes": ""}
for row_id in source.index[source["query"].eq("")]
]
url = "https://api.genebe.net/cloud/api-public/v2/convert"
with requests.Session() as session:
for start in range(0, len(queries), 50):
batch = queries.iloc[start : start + 50]
response = session.post(url, json=batch.tolist(), timeout=30)
response.raise_for_status()
results = response.json()["results"]
if [result["input"] for result in results] != batch.tolist():
raise ValueError(f"Unexpected HGVS results for batch starting at {start}")

for row_id, result in zip(batch.index, results):
candidates = result.get("candidates") or []
issues = (result.get("warnings") or []) + (result.get("errors") or [])
details = {
"row_id": row_id,
"status": result["status"],
"issue_codes": ",".join(issue["code"] for issue in issues),
}
if result["status"] == "RESOLVED" and len(candidates) == 1 and not issues:
ready_rows.append({**details, **candidates[0]})
else:
for candidate in candidates or [{}]:
review_rows.append({**details, **candidate})

required = ["row_id", "status", "issue_codes", "genome", "chr", "pos", "ref", "alt"]
for filename, records, relationship in [
("hgvs.hg38.csv", ready_rows, "one_to_one"),
("hgvs-review.csv", review_rows, "one_to_many"),
]:
result = pd.DataFrame.from_records(records)
result = result.reindex(columns=required + [col for col in result if col not in required])
result["pos"] = result["pos"].astype("Int64")
output = source.merge(result, on="row_id", how="inner", validate=relationship)
output.to_csv(filename, index=False)

Review the converted and ambiguous rows​

HGVS expressionExample resultOutput file
NM_000492.3:c.983T>A7-117540213-T-Ahgvs.hg38.csv
NC_000016.10:g.68829788del16-68829784-AT-Ahgvs.hg38.csv
AGT:p.Met259SerAMBIGUOUS, six DNA candidates in this runhgvs-review.csv
invalid-hgvsNOT_RECOGNIZEDhgvs-review.csv

The deletion has a shared anchor base and a different position in the VCF-style output. Keep pos, ref and alt together. The review file has one row per candidate and keeps a row for each expression with zero candidates. When available, use the original coding or genomic description to resolve a protein-only match. See the HGVS tool reference for individual lookups, or continue with batch annotation in pandas.