|
| 1 | +"""COSMOS PKN fetch and convenience functions.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import logging |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +from omnipath_client._download import Downloader |
| 9 | +from omnipath_client._session import get_logger |
| 10 | + |
| 11 | +logger = get_logger(__name__) |
| 12 | + |
| 13 | +DEFAULT_METABO_URL = 'https://metabo.omnipathdb.org' |
| 14 | + |
| 15 | +_metabo_url: str = DEFAULT_METABO_URL |
| 16 | +_downloader: Downloader | None = None |
| 17 | + |
| 18 | + |
| 19 | +def set_url(url: str) -> None: |
| 20 | + """Override the metabo service base URL.""" |
| 21 | + |
| 22 | + global _metabo_url |
| 23 | + _metabo_url = url |
| 24 | + |
| 25 | + |
| 26 | +def _dl() -> Downloader: |
| 27 | + """Lazy-initialised shared downloader.""" |
| 28 | + |
| 29 | + global _downloader |
| 30 | + |
| 31 | + if _downloader is None: |
| 32 | + _downloader = Downloader(use_cache=False) |
| 33 | + |
| 34 | + return _downloader |
| 35 | + |
| 36 | + |
| 37 | +def _resolve_organism(organism: int | str) -> int: |
| 38 | + """Resolve organism to NCBI taxonomy ID via the utils service.""" |
| 39 | + |
| 40 | + if isinstance(organism, int): |
| 41 | + return organism |
| 42 | + |
| 43 | + # Try parsing as int first (e.g. '9606') |
| 44 | + try: |
| 45 | + return int(organism) |
| 46 | + except (ValueError, TypeError): |
| 47 | + pass |
| 48 | + |
| 49 | + from omnipath_client.utils import ensure_ncbi_tax_id |
| 50 | + |
| 51 | + result = ensure_ncbi_tax_id(organism) |
| 52 | + |
| 53 | + if result is None: |
| 54 | + raise ValueError(f'Could not resolve organism: {organism!r}') |
| 55 | + |
| 56 | + return result |
| 57 | + |
| 58 | + |
| 59 | +def get_pkn( |
| 60 | + organism: int | str = 9606, |
| 61 | + categories: str | list[str] = 'all', |
| 62 | + resources: str | list[str] | None = None, |
| 63 | + format: str = 'dataframe', |
| 64 | +) -> Any: |
| 65 | + """Fetch COSMOS PKN from the metabo service. |
| 66 | +
|
| 67 | + Args: |
| 68 | + organism: |
| 69 | + Organism identifier — any form accepted by omnipath-utils |
| 70 | + taxonomy: NCBI ID (``9606``), common name (``'human'``), |
| 71 | + Latin (``'Homo sapiens'``), Ensembl (``'hsapiens'``), |
| 72 | + KEGG (``'hsa'``), etc. |
| 73 | + categories: |
| 74 | + Category names or ``'all'``. Available categories: |
| 75 | + ``transporters``, ``receptors``, ``allosteric``, |
| 76 | + ``enzyme_metabolite``, ``ppi``, ``grn``. |
| 77 | + resources: |
| 78 | + Optional resource filter (comma-separated string or list). |
| 79 | + format: |
| 80 | + Output format: ``'dataframe'`` (default), ``'parquet'``, |
| 81 | + ``'dict'``, or ``'annnet'``. |
| 82 | +
|
| 83 | + Returns: |
| 84 | + DataFrame (polars/pandas), raw dict, bytes (parquet), or |
| 85 | + AnnNet Graph depending on *format*. |
| 86 | +
|
| 87 | + Example:: |
| 88 | +
|
| 89 | + import omnipath_client as oc |
| 90 | +
|
| 91 | + # All human transporters |
| 92 | + df = oc.cosmos.get_pkn('human', categories='transporters') |
| 93 | +
|
| 94 | + # Full mouse PKN as AnnNet graph |
| 95 | + g = oc.cosmos.get_pkn('mouse', format='annnet') |
| 96 | + """ |
| 97 | + |
| 98 | + ncbi_tax_id = _resolve_organism(organism) |
| 99 | + |
| 100 | + if isinstance(categories, list): |
| 101 | + categories = ','.join(categories) |
| 102 | + |
| 103 | + if isinstance(resources, list): |
| 104 | + resources = ','.join(resources) |
| 105 | + |
| 106 | + params: dict[str, Any] = { |
| 107 | + 'organism': ncbi_tax_id, |
| 108 | + 'categories': categories, |
| 109 | + } |
| 110 | + |
| 111 | + if resources: |
| 112 | + params['resources'] = resources |
| 113 | + |
| 114 | + if format == 'parquet': |
| 115 | + params['format'] = 'parquet' |
| 116 | + |
| 117 | + url = f'{_metabo_url}/cosmos/pkn' |
| 118 | + data = _dl().fetch_json(url, params=params) |
| 119 | + |
| 120 | + if format == 'dict': |
| 121 | + return data |
| 122 | + |
| 123 | + if format == 'annnet': |
| 124 | + df = _network_to_dataframe(data['network']) |
| 125 | + from omnipath_client.cosmos._annnet import to_annnet |
| 126 | + return to_annnet(df) |
| 127 | + |
| 128 | + # Default: DataFrame |
| 129 | + return _network_to_dataframe(data['network']) |
| 130 | + |
| 131 | + |
| 132 | +def _network_to_dataframe(records: list[dict]) -> Any: |
| 133 | + """Convert network records to a DataFrame. |
| 134 | +
|
| 135 | + Uses polars if available, falls back to pandas. |
| 136 | + """ |
| 137 | + |
| 138 | + if not records: |
| 139 | + try: |
| 140 | + import polars as pl |
| 141 | + return pl.DataFrame() |
| 142 | + except ImportError: |
| 143 | + import pandas as pd |
| 144 | + return pd.DataFrame() |
| 145 | + |
| 146 | + try: |
| 147 | + import polars as pl |
| 148 | + return pl.DataFrame(records) |
| 149 | + except ImportError: |
| 150 | + pass |
| 151 | + |
| 152 | + try: |
| 153 | + import pandas as pd |
| 154 | + return pd.DataFrame(records) |
| 155 | + except ImportError: |
| 156 | + pass |
| 157 | + |
| 158 | + raise ImportError( |
| 159 | + 'Either polars or pandas is required for DataFrame output. ' |
| 160 | + 'Install with: pip install polars' |
| 161 | + ) |
| 162 | + |
| 163 | + |
| 164 | +def categories() -> list[str]: |
| 165 | + """List available PKN categories.""" |
| 166 | + |
| 167 | + url = f'{_metabo_url}/cosmos/categories' |
| 168 | + return _dl().fetch_json(url) |
| 169 | + |
| 170 | + |
| 171 | +def organisms() -> list[int]: |
| 172 | + """List organisms with pre-built PKNs.""" |
| 173 | + |
| 174 | + url = f'{_metabo_url}/cosmos/organisms' |
| 175 | + return _dl().fetch_json(url) |
| 176 | + |
| 177 | + |
| 178 | +def resources(organism: int | str = 9606) -> dict[str, list[str]]: |
| 179 | + """List resources available per category. |
| 180 | +
|
| 181 | + Args: |
| 182 | + organism: Organism identifier (any form). |
| 183 | + """ |
| 184 | + |
| 185 | + ncbi_tax_id = _resolve_organism(organism) |
| 186 | + url = f'{_metabo_url}/cosmos/resources' |
| 187 | + return _dl().fetch_json(url, params={'organism': ncbi_tax_id}) |
| 188 | + |
| 189 | + |
| 190 | +def status() -> dict: |
| 191 | + """Get cache status from the metabo service.""" |
| 192 | + |
| 193 | + url = f'{_metabo_url}/cosmos/status' |
| 194 | + return _dl().fetch_json(url) |
0 commit comments