Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 16 additions & 16 deletions .github/workflows/pytest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
name: Run all python tests

on:
workflow_dispatch:
push:
branches: [ master, next-minor-release ]
pull_request:
Expand All @@ -12,31 +13,29 @@ on:
jobs:
lint:
name: Linting using flake8
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
- uses: actions/checkout@v6
- uses: actions/setup-python@v6
with:
python-version: "3.9"
python-version: "3.12"
- name: Install flake8
run: python -m pip install flake8
- name: Run flake8
uses: julianwachholz/flake8-action@v2
with:
checkName: "Python Lint"
path: .
config: flake8.ini
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: python -m flake8 --config flake8.ini .
pytest:
needs: lint
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ ubuntu-latest, macos-latest ]
# Python 3.8/3.9 are unavailable on Ubuntu 26.04 and macOS arm64.
os: [ ubuntu-24.04, macos-15-intel ]
python-version: [ '3.8','3.9','3.10','3.11','3.12','3.13' ]
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v6
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
uses: actions/setup-python@v6
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
Expand All @@ -57,12 +56,13 @@ jobs:
needs: lint
runs-on: windows-latest
strategy:
fail-fast: false
matrix:
python-version: [ '3.8','3.9','3.10','3.11','3.12','3.13' ]
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v6
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
uses: actions/setup-python@v6
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
Expand Down
106 changes: 104 additions & 2 deletions AnnotatorCore.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@

oncokb_api_bearer_token = ""

ONCOTREE_API_URL = "https://oncotree.mskcc.org/api/tumorTypes"

# OncoKB also accepts these names (and their underscore-separated enum names).
SPECIAL_TUMOR_TYPES = (
'All Tumors', 'All Solid Tumors', 'All Liquid Tumors', 'Germline Disposition',
'Other Tumor Types', 'Other Solid Tumor Types', 'Other Liquid Tumor Types',
)

# 'U', which no longer has any effect in python 3. 3.11 completely removed the option.
# It will throw error if we don't do condition check.
# https://stackoverflow.com/questions/56791545/what-is-the-non-deprecated-version-of-open-u-mode
Expand Down Expand Up @@ -370,6 +378,99 @@ def makeoncokbgetrequest(url):
return requests_retry_session(allowed_methods=["HEAD", "GET"]).get(url, headers=headers, timeout=REQUEST_TIMEOUT)


class TumorTypeValidationError(ValueError):
pass


def normalize_tumor_type(tumor_type):
return tumor_type.strip() if tumor_type is not None else ''


def validate_tumor_types(input_file, default_cancer_type, cancer_type_map, cna_format=None):
"""Check supplied tumor types before any annotation or output-file writes."""
supplied = {}

def add(tumor_type, source):
tumor_type = normalize_tumor_type(tumor_type)
if tumor_type:
supplied.setdefault(tumor_type, source)

add(default_cancer_type, '-t')
for sample, tumor_type in cancer_type_map.items():
if not sampleidsfilter or sample in sampleidsfilter:
add(tumor_type, 'clinical data for sample %s' % sample)

# GISTIC columns contain samples and numeric calls, not per-row tumor types.
if cna_format != CNA_FILE_FORMAT_GISTIC:
with open(input_file, DEFAULT_READ_FILE_MODE) as infile:
reader = csv.reader(infile, delimiter='\t')
headers = readheaders(reader)
cancer_index = geIndexOfHeader(headers, CANCER_TYPE_HEADERS)
sample_index = geIndexOfHeader(headers, SAMPLE_HEADERS)
if cancer_index >= 0:
for row in reader:
if not row:
continue
sample = row[sample_index] if 0 <= sample_index < len(row) else None
if sampleidsfilter and sample not in sampleidsfilter:
continue
if sample in cancer_type_map:
continue # Clinical data overrides the tumor type in the input row.
if cancer_index >= len(row):
raise TumorTypeValidationError('Missing tumor-type column at input line %s' % reader.line_num)
add(get_cell_content(row, cancer_index), 'input line %s' % reader.line_num)
Comment on lines +419 to +421

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regression here since missing cancer type will stop the script whereas before it will just log a warning and continue. We should maintain the original behavior.


if not supplied:
return

try:
response = makeoncokbgetrequest(oncokb_annotation_api_url + '/info')
response.raise_for_status()
info = response.json()
except (requests.RequestException, ValueError) as error:
raise TumorTypeValidationError(
'Cannot validate tumor types: unable to load OncoKB /info. Check the server, token and connection.'
) from error
version = info.get('oncoTreeVersion') if isinstance(info, dict) else None
if not isinstance(version, str) or not version.strip():
raise TumorTypeValidationError('Cannot validate tumor types: OncoKB /info did not report oncoTreeVersion.')

try:
# Do not forward the OncoKB Authorization header to the OncoTree service.
response = requests_retry_session().get(
ONCOTREE_API_URL, params={'version': version, 'flat': 'true'}, timeout=REQUEST_TIMEOUT)
response.raise_for_status()
tumor_types = response.json()
except (requests.RequestException, ValueError) as error:
raise TumorTypeValidationError(
'Cannot validate tumor types: unable to load OncoTree version %s. Check the connection.' % version
) from error

if not isinstance(tumor_types, list) or not tumor_types:
raise TumorTypeValidationError('Cannot validate tumor types: invalid OncoTree response for %s.' % version)
accepted = set()
for tumor_type in tumor_types:
if not isinstance(tumor_type, dict):
raise TumorTypeValidationError('Cannot validate tumor types: invalid OncoTree entry for %s.' % version)
if tumor_type.get('level') == 0:
continue # The ontology root is not an OncoKB tumor-type code.
values = [tumor_type.get(field) for field in ('code', 'name', 'mainType')]
names = [value.lower() for value in values if isinstance(value, str) and value.strip()]
if not names:
raise TumorTypeValidationError('Cannot validate tumor types: invalid OncoTree entry for %s.' % version)
accepted.update(names)
if not accepted:
raise TumorTypeValidationError('Cannot validate tumor types: empty OncoTree response for %s.' % version)
for tumor_type in SPECIAL_TUMOR_TYPES:
accepted.update((tumor_type.lower(), tumor_type.replace(' ', '_').lower()))

for tumor_type, source in supplied.items():
if tumor_type.lower() not in accepted:
raise TumorTypeValidationError(
"Unknown tumor type %r in %s (OncoTree %s). Use a code, name or main type supported by this release."
% (tumor_type, source, version))


_3dhotspots = None


Expand Down Expand Up @@ -451,6 +552,7 @@ def get_tumor_type_from_row(row, row_index, defaultCancerType, icancertype, canc
cancertype = row_cancer_type
if sample in cancerTypeMap:
cancertype = cancerTypeMap[sample]
cancertype = normalize_tumor_type(cancertype)
if cancertype == "":
log.info(
"Cancer type for the sample should be defined for a more accurate result. \tLine %s" % (row_index))
Expand Down Expand Up @@ -1423,14 +1525,14 @@ def process_gistic_data(outf, gistic_data_file, defaultCancerType, cancerTypeMap
continue
cna_type = get_cna(row[headers[rawsample]], annotate_gain_loss)
if cna_type is not None:
cancer_type = defaultCancerType
cancer_type = normalize_tumor_type(defaultCancerType)
sample = rawsample

if sampleidsfilter and sample not in sampleidsfilter:
continue

if sample in cancerTypeMap:
cancer_type = cancerTypeMap[sample]
cancer_type = normalize_tumor_type(cancerTypeMap[sample])

rows.append([sample, cancer_type, hugo, cna_type])
queries.append(CNAQuery(hugo, cna_type, cancer_type))
Expand Down
9 changes: 9 additions & 0 deletions CnaAnnotator.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from AnnotatorCore import setoncokbapitoken
from AnnotatorCore import readCancerTypes
from AnnotatorCore import validate_oncokb_token
from AnnotatorCore import validate_tumor_types, TumorTypeValidationError
from AnnotatorCore import process_cna_data
from AnnotatorCore import CNA_FILE_FORMAT_GISTIC

Expand All @@ -31,6 +32,8 @@ def main(argv):
' 1) ONCOTREE_CODE in clinical data file\n'
' 2) ONCOTREE_CODE exist in MAF\n'
' 3) default tumor type (-t)\n'
'Nonempty tumor types are validated against the OncoTree release reported by OncoKB.\n'
'Unknown types or unavailable validation metadata stop before output is written (exit 2).\n'
' We do not annotate Gain and Loss by default, add -z to include the analysis. See https://github.com/oncokb/oncokb-annotator/issues/51 for more information.\n'
' Default OncoKB base url is https://www.oncokb.org'
)
Expand Down Expand Up @@ -59,6 +62,12 @@ def main(argv):

validate_oncokb_token()

try:
validate_tumor_types(argv.input_file, argv.default_cancer_type, cancertypemap, argv.cna_file_format.lower())
except TumorTypeValidationError as error:
log.error(str(error))
sys.exit(2)

log.info('annotating %s ...' % argv.input_file)
process_cna_data(argv.input_file, argv.output_file, argv.previous_result_file, argv.default_cancer_type, cancertypemap, argv.include_descriptions, argv.annotate_gain_loss, argv.cna_file_format.lower())

Expand Down
9 changes: 9 additions & 0 deletions FusionAnnotator.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from AnnotatorCore import setoncokbapitoken
from AnnotatorCore import readCancerTypes
from AnnotatorCore import validate_oncokb_token
from AnnotatorCore import validate_tumor_types, TumorTypeValidationError
from AnnotatorCore import process_fusion

logging.basicConfig(level=logging.INFO)
Expand Down Expand Up @@ -37,6 +38,8 @@ def main(argv):
' 1) ONCOTREE_CODE in clinical data file\n'
' 2) ONCOTREE_CODE exist in Fusion\n'
' 3) default tumor type (-t)\n'
'Nonempty tumor types are validated against the OncoTree release reported by OncoKB.\n'
'Unknown types or unavailable validation metadata stop before output is written (exit 2).\n'
' Default OncoKB base url is https://www.oncokb.org'
)
sys.exit()
Expand Down Expand Up @@ -66,6 +69,12 @@ def main(argv):

validate_oncokb_token()

try:
validate_tumor_types(argv.input_file, argv.default_cancer_type, cancertypemap)
except TumorTypeValidationError as error:
log.error(str(error))
sys.exit(2)

log.info('annotating %s ...' % argv.input_file)
process_fusion(argv.input_file, argv.output_file, argv.previous_result_file, argv.default_cancer_type, cancertypemap, argv.structural_variant_name_format, argv.include_descriptions)

Expand Down
9 changes: 9 additions & 0 deletions MafAnnotator.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from AnnotatorCore import setoncokbapitoken
from AnnotatorCore import readCancerTypes
from AnnotatorCore import validate_oncokb_token
from AnnotatorCore import validate_tumor_types, TumorTypeValidationError
from AnnotatorCore import processalterationevents
from AnnotatorCore import QueryType
from AnnotatorCore import ReferenceGenome
Expand Down Expand Up @@ -54,6 +55,8 @@ def main(argv):
' 1) ONCOTREE_CODE in clinical data file\n'
' 2) ONCOTREE_CODE exist in MAF\n'
' 3) default tumor type (-t)\n'
'Nonempty tumor types are validated against the OncoTree release reported by OncoKB.\n'
'Unknown types or unavailable validation metadata stop before output is written (exit 2).\n'
'Query type only allows the following values (case-insensitive):\n'
' - HGVSp_Short\n'
' It reads from column HGVSp_Short or Alteration\n'
Expand Down Expand Up @@ -121,6 +124,12 @@ def main(argv):

validate_oncokb_token()

try:
validate_tumor_types(argv.input_file, argv.default_cancer_type, cancertypemap)
except TumorTypeValidationError as error:
log.error(str(error))
sys.exit(2)

processalterationevents(argv.input_file, argv.output_file, argv.previous_result_file, argv.default_cancer_type,
cancertypemap, argv.annotate_hotspots, user_input_query_type, default_reference_genome,
argv.include_descriptions)
Expand Down
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,30 @@ pip install -r requirements/common.txt -r requirements/pip2.7.txt
## Usage
Example input files are under [data](data). An example script is here: [example.sh](example.sh)

### Tumor-type validation

`MafAnnotator.py`, `CnaAnnotator.py`, `FusionAnnotator.py` and `StructuralVariantAnnotator.py`
validate tumor types before sending annotation requests or creating/overwriting the output file.
They accept OncoTree codes, names and main types case-insensitively, including codes containing
punctuation such as `MDS/MPN`. Surrounding whitespace is removed from the type sent to OncoKB.
OncoKB's special tumor types (for example, `All Solid Tumors` or `ALL_SOLID_TUMORS`) are also accepted.

- A nonempty default supplied with `-t` is checked.
- Nonempty clinical-file types are checked for samples included by `-s`, or all samples if no filter is specified.
- Input-row types are checked for included samples unless clinical data overrides them.
- The existing priority remains clinical data, then the input row, then `-t`. An omitted/empty tumor type remains optional.
GISTIC input uses the clinical file or `-t`, because its columns contain samples rather than tumor types.

Validation uses `oncoTreeVersion` from the selected OncoKB server's `/api/v1/info` endpoint and
downloads that release from `https://oncotree.mskcc.org/api/tumorTypes`. It does not use the latest
ontology release implicitly or forward the OncoKB bearer token to OncoTree. Unknown types,
missing version information and unavailable/malformed metadata stop the command with exit status 2
and an error identifying the source or metadata problem. A custom server supplied with `-u` must
report an OncoTree version available from that service.

Run `python -m pytest` for the test suite. Tumor-type tests use a local mock HTTP server and synthetic
input files; they do not require an OncoKB token. Existing live-annotation tests still require one.

### MAF
Annotates variants in MAF(https://docs.gdc.cancer.gov/Data/File_Formats/MAF_Format/) with OncoKB™ annotation. Supports both python2 and python3.
Get more details on the command line using `python MafAnnotator.py -h`.
Expand Down
9 changes: 9 additions & 0 deletions StructuralVariantAnnotator.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from AnnotatorCore import setoncokbapitoken
from AnnotatorCore import readCancerTypes
from AnnotatorCore import validate_oncokb_token
from AnnotatorCore import validate_tumor_types, TumorTypeValidationError
from AnnotatorCore import process_sv

logging.basicConfig(level=logging.INFO)
Expand All @@ -36,6 +37,8 @@ def main(argv):
' 1) ONCOTREE_CODE in clinical data file\n'
' 2) ONCOTREE_CODE exist in structural variant\n'
' 3) default tumor type (-t)\n'
'Nonempty tumor types are validated against the OncoTree release reported by OncoKB.\n'
'Unknown types or unavailable validation metadata stop before output is written (exit 2).\n'
' Default OncoKB base url is https://www.oncokb.org'
)
sys.exit()
Expand Down Expand Up @@ -65,6 +68,12 @@ def main(argv):

validate_oncokb_token()

try:
validate_tumor_types(argv.input_file, argv.default_cancer_type, cancertypemap)
except TumorTypeValidationError as error:
log.error(str(error))
sys.exit(2)

log.info('annotating %s ...' % argv.input_file)
process_sv(argv.input_file, argv.output_file, argv.previous_result_file, argv.default_cancer_type, cancertypemap,
argv.include_descriptions)
Expand Down
Loading