From 0996dbcc6375038aa7c407ef4c705ef9414547c0 Mon Sep 17 00:00:00 2001 From: Jayaram Kancherla Date: Thu, 26 Mar 2026 21:01:53 -0700 Subject: [PATCH 01/16] update workflows --- .github/workflows/publish-pypi.yml | 52 +++++++++++++++++++++ .github/workflows/run-tests.yml | 73 ++++++++++++++++++++++++++++++ 2 files changed, 125 insertions(+) create mode 100644 .github/workflows/publish-pypi.yml create mode 100644 .github/workflows/run-tests.yml diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml new file mode 100644 index 0000000..405fee0 --- /dev/null +++ b/.github/workflows/publish-pypi.yml @@ -0,0 +1,52 @@ +name: Publish to PyPI + +on: + push: + tags: "*" + +jobs: + build: + runs-on: ubuntu-latest + permissions: + id-token: write + repository-projects: write + contents: write + pages: write + + steps: + - uses: actions/checkout@v4 + + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: 3.12 + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install tox + + - name: Test with tox + run: | + tox + + - name: Build Project and Publish + run: | + python -m tox -e clean,build + + # This uses the trusted publisher workflow so no token is required. + - name: Publish to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 + + - name: Build docs + run: | + tox -e docs + + - run: touch ./docs/_build/html/.nojekyll + + - name: GH Pages Deployment + uses: JamesIves/github-pages-deploy-action@v4 + with: + branch: gh-pages # The branch the action should deploy to. + folder: ./docs/_build/html + clean: true # Automatically remove deleted files from the deploy branch diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml new file mode 100644 index 0000000..01f4e9a --- /dev/null +++ b/.github/workflows/run-tests.yml @@ -0,0 +1,73 @@ +name: Test the library + +on: + push: + branches: + - master # for legacy repos + - main + pull_request: + branches: + - master # for legacy repos + - main + workflow_dispatch: # Allow manually triggering the workflow + schedule: + # Run roughly every 15 days at 00:00 UTC + # (useful to check if updates on dependencies break the package) + - cron: "0 0 1,16 * *" + +permissions: + contents: read + +concurrency: + group: >- + ${{ github.workflow }}-${{ github.ref_type }}- + ${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: true + +jobs: + test: + strategy: + matrix: + python: ["3.10", "3.11", "3.12", "3.13", "3.14"] + platform: + - ubuntu-latest + # - macos-latest + # - windows-latest + runs-on: ${{ matrix.platform }} + name: Python ${{ matrix.python }}, ${{ matrix.platform }} + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + id: setup-python + with: + python-version: ${{ matrix.python }} + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install tox coverage + + - name: Run tests + run: >- + pipx run --python '${{ steps.setup-python.outputs.python-path }}' + tox + -- -rFEx --durations 10 --color yes --cov --cov-branch --cov-report=xml # pytest args + + - name: Check for codecov token availability + id: codecov-check + shell: bash + run: | + if [ ${{ secrets.CODECOV_TOKEN }} != '' ]; then + echo "codecov=true" >> $GITHUB_OUTPUT; + else + echo "codecov=false" >> $GITHUB_OUTPUT; + fi + + - name: Upload coverage reports to Codecov with GitHub Action + uses: codecov/codecov-action@v5 + if: ${{ steps.codecov-check.outputs.codecov == 'true' }} + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + slug: ${{ github.repository }} + flags: ${{ matrix.platform }} - py${{ matrix.python }} From 059ad4582842c8f0c53c0a43839a800a470cd699 Mon Sep 17 00:00:00 2001 From: Jayaram Kancherla Date: Thu, 26 Mar 2026 21:25:29 -0700 Subject: [PATCH 02/16] skip time taking tests --- tests/test_integration.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_integration.py b/tests/test_integration.py index c6c91f5..6e98d46 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -9,8 +9,8 @@ from expressionatlas import ExpressionAtlasClient from expressionatlas.validation import is_valid_accession - @pytest.mark.integration +@pytest.mark.skip("takes too long") class TestExpressionAtlasClientIntegration: """Integration tests for ExpressionAtlasClient.""" From bfa85c8d4a9daf0d309fb85e8efb457857de6fce Mon Sep 17 00:00:00 2001 From: Jayaram Kancherla Date: Thu, 26 Mar 2026 21:26:57 -0700 Subject: [PATCH 03/16] cleaning up imports --- src/expressionatlas/__init__.py | 3 --- src/expressionatlas/client.py | 2 +- src/expressionatlas/download.py | 3 +-- 3 files changed, 2 insertions(+), 6 deletions(-) diff --git a/src/expressionatlas/__init__.py b/src/expressionatlas/__init__.py index ad588c0..abea65e 100644 --- a/src/expressionatlas/__init__.py +++ b/src/expressionatlas/__init__.py @@ -26,7 +26,6 @@ finally: del version, PackageNotFoundError - from expressionatlas.client import ExpressionAtlasClient from expressionatlas.download import ( get_atlas_data, @@ -41,5 +40,3 @@ InvalidAccessionError, ) from expressionatlas.models import SearchResult -from summarizedexperiment import SummarizedExperiment -from biocutils import NamedList diff --git a/src/expressionatlas/client.py b/src/expressionatlas/client.py index a37c612..b694239 100644 --- a/src/expressionatlas/client.py +++ b/src/expressionatlas/client.py @@ -6,11 +6,11 @@ from collections.abc import Sequence import pandas as pd +from biocutils import NamedList from expressionatlas.api import BioStudiesAPI from expressionatlas.download import get_atlas_data, get_atlas_experiment from expressionatlas.models import search_results_to_dataframe -from biocutils import NamedList from expressionatlas.validation import validate_accession logger = logging.getLogger(__name__) diff --git a/src/expressionatlas/download.py b/src/expressionatlas/download.py index 85b7d46..3c59885 100644 --- a/src/expressionatlas/download.py +++ b/src/expressionatlas/download.py @@ -19,9 +19,8 @@ import numpy as np import pandas as pd - -from biocutils import NamedList from biocframe import BiocFrame +from biocutils import NamedList from summarizedexperiment import SummarizedExperiment from expressionatlas.exceptions import DownloadError From c475c46048b382d47ee65f8904a8fe6dfcf65808 Mon Sep 17 00:00:00 2001 From: Jayaram Kancherla Date: Mon, 30 Mar 2026 11:05:25 -0700 Subject: [PATCH 04/16] replace pandas with biocframe --- README.md | 51 ++-- setup.cfg | 1 - src/expressionatlas/client.py | 30 ++- src/expressionatlas/converter.py | 410 ------------------------------- src/expressionatlas/download.py | 123 ++++++---- src/expressionatlas/models.py | 33 ++- tests/test_integration.py | 18 +- tests/test_models.py | 29 +-- 8 files changed, 167 insertions(+), 528 deletions(-) delete mode 100644 src/expressionatlas/converter.py diff --git a/README.md b/README.md index f2ef102..19bb2a7 100644 --- a/README.md +++ b/README.md @@ -37,10 +37,18 @@ results = client.search_experiments( properties=["cancer", "breast"], species="homo sapiens" ) -print(results.head()) -# Accession Species Type ... -# 0 E-MTAB-1624 homo sapiens microarray data ... +print(results) ``` + BiocFrame with 208 rows and 4 columns + Accession Species Type Title + + [0] E-MTAB-8198 Homo sapiens Cell line - High-thr... Functional effect of... + [1] E-MTAB-8532 Homo sapiens Human - One-color mi... DNA microarray studi... + [2] E-GEOD-43306 Homo sapiens RNA-seq of coding RNA Translating transcri... + ... ... ... ... + [205] E-MTAB-779 Homo sapiens transcription profil... OncomiRs like let-7 ... + [206] E-TABM-1118 Homo sapiens transcription profil... Transcrption profili... + [207] E-TABM-601 Homo sapiens transcription profil... Transcription profil... ### Download RNA-seq Data @@ -53,44 +61,35 @@ rnaseq = exp["rnaseq"] counts = rnaseq.assay("counts") # numpy array: genes × samples print(f"Shape: {counts.shape[0]} genes × {counts.shape[1]} samples") -# Shape: 58735 genes × 48 samples +# Shape: 58735 genes × 24 samples # Sample metadata (BiocFrame) sample_info = rnaseq.get_column_data() print(sample_info.get_column_names()) +# ['cell line', 'compound', 'developmental stage', 'disease', 'dose', 'genotype', 'organism', 'organism part'] # Gene annotations (BiocFrame) gene_info = rnaseq.get_row_data() print(gene_info.shape) -``` - -### Download Microarray Data - -```python -exp = client.get_experiment("E-MTAB-1624") - -# Microarray data is keyed by array design -array_design = "A-AFFY-126" -eset = exp[array_design] # This is also a SummarizedExperiment now +# (58735, 1) -# Expression matrix (probes × samples) -intensities = eset.assay("exprs") -print(intensities.shape) -# (54675, 96) - -# Sample metadata (BiocFrame) -sample_annotations = eset.get_column_data() -print(sample_annotations.shape) - -# Feature annotations (BiocFrame) -probe_annotations = eset.get_row_data() +print(rnaseq) ``` + class: SummarizedExperiment + dimensions: (58735, 24) + assays(1): ['counts'] + row_data columns(1): ['Gene Name'] + row_names(58735): ['ENSG00000000003', 'ENSG00000000005', 'ENSG00000000419', ..., 'ENSG00000285992', 'ENSG00000285993', 'ENSG00000285994'] + column_data columns(8): ['cell line', 'compound', 'developmental stage', 'disease', 'dose', 'genotype', 'organism', 'organism part'] + column_names(24): ['ERR3456453', 'ERR3456442', 'ERR3456443', ..., 'ERR3456450', 'ERR3456459', 'ERR3456444'] + metadata(2): accession source + ### Batch Downloads ```python # Download multiple experiments -accessions = results["Accession"].head(10).tolist() +accessions = results.get_column("Accession")[:10] experiments = client.get_experiments(accessions) # Access individual experiments diff --git a/setup.cfg b/setup.cfg index b889390..36c0dfc 100644 --- a/setup.cfg +++ b/setup.cfg @@ -50,7 +50,6 @@ python_requires = >=3.9 install_requires = importlib-metadata; python_version<"3.8" requests - pandas numpy biocframe summarizedexperiment diff --git a/src/expressionatlas/client.py b/src/expressionatlas/client.py index b694239..c4e4c87 100644 --- a/src/expressionatlas/client.py +++ b/src/expressionatlas/client.py @@ -5,12 +5,12 @@ import logging from collections.abc import Sequence -import pandas as pd +from biocframe import BiocFrame from biocutils import NamedList from expressionatlas.api import BioStudiesAPI from expressionatlas.download import get_atlas_data, get_atlas_experiment -from expressionatlas.models import search_results_to_dataframe +from expressionatlas.models import search_results_to_biocframe from expressionatlas.validation import validate_accession logger = logging.getLogger(__name__) @@ -74,7 +74,7 @@ def search_experiments( self, properties: str | Sequence[str], species: str | None = None, - ) -> pd.DataFrame: + ) -> BiocFrame: """ Search for Expression Atlas experiments matching given criteria. @@ -90,8 +90,8 @@ def search_experiments( Returns ------- - pandas.DataFrame - DataFrame with columns: Accession, Species, Type, Title. + BiocFrame + BiocFrame with columns: Accession, Species, Type, Title. Sorted by Species, Type, then Accession. Raises @@ -130,8 +130,8 @@ def search_experiments( results = self.api.search(properties=list(properties), species=species) - # Filter out connection errors and convert to DataFrame - df = search_results_to_dataframe(results) + # Filter out connection errors and convert to BiocFrame + df = search_results_to_biocframe(results) # Log warning if any connection errors occurred error_count = sum(1 for r in results if r.connection_error) @@ -232,16 +232,14 @@ def get_experiments( ... species="homo sapiens", ... ) >>> # Download all RNA-seq experiments from search results - >>> rnaseq_accessions = results[ - ... results[ - ... "Type" - ... ].str.contains( - ... "RNA-seq", - ... na=False, - ... ) - ... ]["Accession"] + >>> types = results.get_column("Type") + >>> accessions = results.get_column("Accession") + >>> rnaseq_accessions = [ + ... acc for acc, typ in zip(accessions, types) + ... if typ and "RNA-seq" in typ + ... ] >>> experiments = client.get_experiments( - ... rnaseq_accessions.tolist() + ... rnaseq_accessions ... ) >>> # Access: experiments["E-MTAB-XXXX"]["rnaseq"].assays["counts"] """ diff --git a/src/expressionatlas/converter.py b/src/expressionatlas/converter.py deleted file mode 100644 index fcad96a..0000000 --- a/src/expressionatlas/converter.py +++ /dev/null @@ -1,410 +0,0 @@ -"""Client for the Expression Atlas RData Converter AWS service.""" - -from __future__ import annotations - -import io -import json -import logging -import os -import tempfile -import zipfile -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any -from urllib.request import Request, urlopen - -import numpy as np -import pandas as pd - -logger = logging.getLogger(__name__) - - -class ConverterError(Exception): - """Error from the converter service.""" - - def __init__(self, message: str, status_code: int | None = None): - super().__init__(message) - self.status_code = status_code - - -@dataclass -class ConvertedBundle: - """Container for converted Expression Atlas data.""" - - # Expression matrix (genes x samples) - matrix: np.ndarray | None = None - - # Gene annotations - genes: pd.DataFrame = field(default_factory=pd.DataFrame) - - # Sample annotations - samples: pd.DataFrame = field(default_factory=pd.DataFrame) - - # Metadata from conversion - meta: dict[str, Any] = field(default_factory=dict) - - # Row names (gene IDs) - rownames: list[str] = field(default_factory=list) - - # Column names (sample IDs) - colnames: list[str] = field(default_factory=list) - - @property - def shape(self) -> tuple[int, int]: - """Return (n_genes, n_samples) shape.""" - if self.matrix is not None: - return self.matrix.shape - return (len(self.rownames), len(self.colnames)) - - -class ConverterClient: - """ - Client for the Expression Atlas RData Converter service (AWS). - - This client calls the AWS App Runner/ECS service to convert .RData files - to portable formats that Python can read without R. - - Parameters - ---------- - service_url : str, optional - URL of the converter service. Defaults to CONVERTER_URL env var. - use_iam_auth : bool - If True, use AWS IAM authentication (SigV4). - If False, use API key from CONVERTER_API_KEY env var. - cache_dir : Path, optional - Directory to cache downloaded bundles. Defaults to temp dir. - timeout : int - Request timeout in seconds. - - Examples - -------- - >>> client = ConverterClient( - ... use_iam_auth=False - ... ) - >>> bundle = client.convert_and_load( - ... "ftp://ftp.ebi.ac.uk/.../E-MTAB-7841-atlasExperimentSummary.Rdata", - ... "E-MTAB-7841", - ... ) - >>> print( - ... bundle.matrix.shape - ... ) - (58735, 48) - """ - - def __init__( - self, - service_url: str | None = None, - use_iam_auth: bool = False, - cache_dir: Path | None = None, - timeout: int = 600, - ): - self.service_url = service_url or os.environ.get("CONVERTER_URL", "") - self.use_iam_auth = use_iam_auth - self.cache_dir = cache_dir or Path(tempfile.gettempdir()) / "atlas_converter_cache" - self.timeout = timeout - - if not self.service_url: - logger.warning( - "CONVERTER_URL not set. Converter client will not work. " - "Set CONVERTER_URL environment variable or pass service_url parameter." - ) - - def _get_auth_headers(self) -> dict[str, str]: - """Get authentication headers for the request.""" - headers = {"Content-Type": "application/json"} - - if self.use_iam_auth: - # Use AWS SigV4 signing for IAM auth - try: - from botocore.auth import SigV4Auth - from botocore.awsrequest import AWSRequest - from botocore.session import Session - - session = Session() - credentials = session.get_credentials() - if credentials: - # Create a request to sign - aws_request = AWSRequest( - method="POST", - url=f"{self.service_url.rstrip('/')}/convert", - headers=headers, - ) - SigV4Auth(credentials, "execute-api", os.environ.get("AWS_REGION", "us-east-1")).add_auth( - aws_request - ) - headers.update(dict(aws_request.headers)) - except ImportError: - logger.warning("botocore not installed. Cannot use IAM auth. " "Install with: pip install botocore") - except Exception as e: - logger.warning(f"Failed to sign request: {e}") - else: - # Use API key - api_key = os.environ.get("CONVERTER_API_KEY", "") - if api_key: - headers["X-API-Key"] = api_key - - return headers - - def convert( - self, - rdata_url: str, - accession: str, - output_format: str = "mtx_bundle", - assay_name: str | None = None, - force: bool = False, - ) -> dict[str, Any]: - """ - Request conversion of an .RData file. - - Parameters - ---------- - rdata_url : str - URL to the .RData file. - accession : str - Experiment accession (e.g., E-MTAB-7841). - output_format : str - Output format (mtx_bundle or tsv_bundle). - assay_name : str, optional - Specific assay to extract. - force : bool - Force re-conversion even if cached. - - Returns - ------- - dict - Response from the converter service including signed_url. - """ - if not self.service_url: - raise ConverterError("CONVERTER_URL not configured") - - endpoint = f"{self.service_url.rstrip('/')}/convert" - - payload = { - "rdata_url": rdata_url, - "accession": accession, - "output_format": output_format, - "force": force, - } - if assay_name: - payload["assay_name"] = assay_name - - headers = self._get_auth_headers() - - logger.info(f"Requesting conversion for {accession}") - - try: - req = Request( - endpoint, - data=json.dumps(payload).encode("utf-8"), - headers=headers, - method="POST", - ) - with urlopen(req, timeout=self.timeout) as response: - result = json.loads(response.read().decode("utf-8")) - - if result.get("status") == "error": - raise ConverterError(result.get("detail", result.get("error", "Unknown error"))) - - logger.info(f"Conversion {'cache hit' if result.get('cache_hit') else 'complete'} " f"for {accession}") - return result - - except Exception as e: - if isinstance(e, ConverterError): - raise - raise ConverterError(f"Request failed: {e}") from e - - def download_bundle(self, signed_url: str, accession: str) -> Path: - """ - Download converted bundle from signed URL. - - Parameters - ---------- - signed_url : str - Signed URL from convert() response. - accession : str - Experiment accession (for cache path). - - Returns - ------- - Path - Path to extracted bundle directory. - """ - # Create cache directory - bundle_dir = self.cache_dir / accession - bundle_dir.mkdir(parents=True, exist_ok=True) - - logger.info(f"Downloading bundle for {accession}") - - try: - with urlopen(signed_url, timeout=self.timeout) as response: - zip_data = response.read() - - # Extract zip - with zipfile.ZipFile(io.BytesIO(zip_data)) as zf: - zf.extractall(bundle_dir) - - logger.info(f"Bundle extracted to {bundle_dir}") - return bundle_dir - - except Exception as e: - raise ConverterError(f"Failed to download bundle: {e}") from e - - def load_bundle(self, bundle_dir: Path) -> dict[str, ConvertedBundle]: - """ - Load converted data from bundle directory. - - Parameters - ---------- - bundle_dir : Path - Path to extracted bundle directory. - - Returns - ------- - dict[str, ConvertedBundle] - Dict mapping dataset name to ConvertedBundle. - """ - results = {} - - # Find all dataset directories - for item in bundle_dir.iterdir(): - if item.is_dir() and item.name.startswith("dataset_"): - dataset_name = item.name.replace("dataset_", "") - results[dataset_name] = self._load_dataset(item) - - # Load metadata - meta_path = bundle_dir / "meta.json" - if meta_path.exists(): - with open(meta_path) as f: - meta = json.load(f) - # Attach to each bundle - for bundle in results.values(): - bundle.meta = meta - - return results - - def _load_dataset(self, dataset_dir: Path) -> ConvertedBundle: - """Load a single dataset from directory.""" - bundle = ConvertedBundle() - - # Load matrix - mtx_path = dataset_dir / "matrix.mtx" - tsv_path = dataset_dir / "counts.tsv.gz" - - if mtx_path.exists(): - bundle.matrix = self._load_mtx(mtx_path) - elif tsv_path.exists(): - df = pd.read_csv(tsv_path, sep="\t", index_col=0, compression="gzip") - bundle.matrix = df.values - bundle.rownames = df.index.tolist() - bundle.colnames = df.columns.tolist() - - # Load row/column names from separate files if MTX format - barcodes_path = dataset_dir / "barcodes.tsv" - features_path = dataset_dir / "features.tsv" - - if barcodes_path.exists(): - bundle.colnames = pd.read_csv(barcodes_path, header=None)[0].tolist() - if features_path.exists(): - bundle.rownames = pd.read_csv(features_path, header=None)[0].tolist() - - # Load genes (rowData) - genes_path = dataset_dir / "genes.csv" - if genes_path.exists(): - bundle.genes = pd.read_csv(genes_path, index_col=0) - if not bundle.rownames: - bundle.rownames = bundle.genes.index.tolist() - - # Load samples (colData) - samples_path = dataset_dir / "samples.csv" - if samples_path.exists(): - bundle.samples = pd.read_csv(samples_path, index_col=0) - if not bundle.colnames: - bundle.colnames = bundle.samples.index.tolist() - - return bundle - - def _load_mtx(self, mtx_path: Path) -> np.ndarray: - """Load Matrix Market file.""" - try: - from scipy.io import mmread - - sparse_matrix = mmread(str(mtx_path)) - return sparse_matrix.toarray() - except ImportError: - logger.warning("scipy not installed, cannot load MTX files efficiently") - # Fallback: manual parsing (slow) - return self._parse_mtx_manual(mtx_path) - - def _parse_mtx_manual(self, mtx_path: Path) -> np.ndarray: - """Parse MTX file manually (fallback if scipy not available).""" - with open(mtx_path) as f: - # Skip comments - line = f.readline() - while line.startswith("%"): - line = f.readline() - - # Read dimensions - parts = line.strip().split() - nrows, ncols, _ = int(parts[0]), int(parts[1]), int(parts[2]) - - # Create dense matrix - matrix = np.zeros((nrows, ncols)) - - # Read entries - for line in f: - parts = line.strip().split() - if len(parts) >= 3: - i, j, val = int(parts[0]) - 1, int(parts[1]) - 1, float(parts[2]) - matrix[i, j] = val - - return matrix - - def convert_and_load( - self, - rdata_url: str, - accession: str, - output_format: str = "mtx_bundle", - assay_name: str | None = None, - force: bool = False, - ) -> dict[str, ConvertedBundle]: - """ - Convert .RData and load the result in one call. - - Parameters - ---------- - rdata_url : str - URL to the .RData file. - accession : str - Experiment accession. - output_format : str - Output format. - assay_name : str, optional - Specific assay to extract. - force : bool - Force re-conversion. - - Returns - ------- - dict[str, ConvertedBundle] - Dict mapping dataset name to ConvertedBundle. - """ - # Check local cache first - bundle_dir = self.cache_dir / accession - meta_path = bundle_dir / "meta.json" - - if not force and meta_path.exists(): - logger.info(f"Loading from local cache: {bundle_dir}") - return self.load_bundle(bundle_dir) - - # Request conversion - result = self.convert(rdata_url, accession, output_format, assay_name, force) - - # Download and extract - bundle_dir = self.download_bundle(result["signed_url"], accession) - - # Load and return - return self.load_bundle(bundle_dir) - - def is_configured(self) -> bool: - """Check if the converter client is properly configured.""" - return bool(self.service_url) diff --git a/src/expressionatlas/download.py b/src/expressionatlas/download.py index 3c59885..1a1c18e 100644 --- a/src/expressionatlas/download.py +++ b/src/expressionatlas/download.py @@ -10,15 +10,16 @@ from __future__ import annotations +import csv import io import logging import tempfile from pathlib import Path from urllib.error import URLError from urllib.request import urlopen +from typing import TypedDict, Dict, List, Optional, Any import numpy as np -import pandas as pd from biocframe import BiocFrame from biocutils import NamedList from summarizedexperiment import SummarizedExperiment @@ -216,15 +217,25 @@ def _download_tsv_fallback(accession: str) -> NamedList: raise DownloadError(accession, "No TSV or RDS data files found.") -def _download_tsv(url: str) -> pd.DataFrame: - """Download and parse a TSV file from URL.""" +def _download_tsv(url: str) -> dict[str, list[str]]: + """Download and parse a TSV file from URL into a column-oriented dictionary.""" logger.debug(f"Downloading: {url}") with urlopen(url, timeout=60) as response: content = response.read().decode("utf-8") - return pd.read_csv(io.StringIO(content), sep="\t") - - -def _try_download_sdrf(url: str) -> pd.DataFrame | None: + + reader = csv.reader(io.StringIO(content), delimiter="\t") + header = next(reader) + data = {h: [] for h in header} + + for row in reader: + for i, h in enumerate(header): + val = row[i] if i < len(row) else None + data[h].append(val) + + return data + + +def _try_download_sdrf(url: str) -> dict[str, dict[str, str]] | None: try: logger.debug(f"Downloading sample annotations: {url}") with urlopen(url, timeout=60) as response: @@ -240,71 +251,100 @@ def _try_download_sdrf(url: str) -> pd.DataFrame | None: else: sample_idx, attr_idx, value_idx = 1, 3, 4 - records: list[tuple[str, str, str]] = [] + records = {} for line in lines: parts = line.split("\t") if len(parts) > max(sample_idx, attr_idx, value_idx): sample_id = parts[sample_idx] attr_name = parts[attr_idx] attr_value = parts[value_idx] - records.append((sample_id, attr_name, attr_value)) - - if not records: - return None - - df = pd.DataFrame(records, columns=["sample_id", "attribute", "value"]) - - result = df.pivot_table( - index="sample_id", - columns="attribute", - values="value", - aggfunc="first", - ) - - result.columns.name = None - result.index.name = "sample_id" - - return result + + if sample_id not in records: + records[sample_id] = {} + + if attr_name not in records[sample_id]: + records[sample_id][attr_name] = attr_value + + return records except Exception as e: logger.debug(f"Could not download sample annotations: {e}") return None def _create_summarized_experiment_from_tsv( - df_data: pd.DataFrame, design_df: pd.DataFrame | None, accession: str, assay_name: str = "counts" + df_data: dict[str, list[str]], design_data: dict[str, dict[str, str]] | None, accession: str, assay_name: str = "counts" ) -> SummarizedExperiment: """Create SummarizedExperiment from TSV data.""" - if df_data.empty: + if not df_data: return SummarizedExperiment() - numeric_cols = df_data.select_dtypes(include=[np.number]).columns.tolist() - annotation_cols = [c for c in df_data.columns if c not in numeric_cols] + all_cols = list(df_data.keys()) + if not all_cols: + return SummarizedExperiment() + + numeric_cols = [] + annotation_cols = [] + + for col in all_cols: + vals = df_data[col] + is_num = True + for v in vals: + if v is not None and v.strip() != "" and v.strip().lower() != "na": + try: + float(v) + except ValueError: + is_num = False + break + if is_num: + numeric_cols.append(col) + else: + annotation_cols.append(col) if not numeric_cols: logger.warning("No numeric columns found in TSV") return SummarizedExperiment() - gene_col = annotation_cols[0] if annotation_cols else df_data.columns[0] + gene_col = annotation_cols[0] if annotation_cols else all_cols[0] sample_cols = numeric_cols - rownames = df_data[gene_col].tolist() + rownames = df_data[gene_col] colnames = sample_cols - assays = {assay_name: df_data[sample_cols].values.astype(np.float64)} + matrix_data = [] + for c in sample_cols: + col_float = [] + for v in df_data[c]: + if v is None or v.strip() == "" or v.strip().lower() == "na": + col_float.append(np.nan) + else: + col_float.append(float(v)) + matrix_data.append(col_float) + + matrix = np.array(matrix_data, dtype=np.float64).T + assays = {assay_name: matrix} row_data = {} for col in annotation_cols: if col != gene_col: - row_data[col] = df_data[col].values.tolist() + row_data[col] = df_data[col] row_bioc = BiocFrame(row_data, row_names=rownames) col_data = {} - if design_df is not None and not design_df.empty: - reindexed_df = design_df.reindex(colnames) - for col in reindexed_df.columns: - col_data[col] = reindexed_df[col].values.tolist() - + if design_data is not None and len(design_data) > 0: + all_attrs = set() + for s in colnames: + if s in design_data: + all_attrs.update(design_data[s].keys()) + + all_attrs = sorted(list(all_attrs)) + + for attr in all_attrs: + col_data[attr] = [] + for s in colnames: + val = design_data.get(s, {}).get(attr, None) + col_data[attr].append(val) + col_bioc = BiocFrame(col_data, row_names=colnames) metadata = {"accession": accession, "source": "tsv"} @@ -328,8 +368,9 @@ def _download_via_converter(rdata_url: str, accession: str) -> NamedList: for name, bundle in bundles.items(): key = name.replace("dataset_", "") if name.startswith("dataset_") else name - row_bioc = BiocFrame(bundle.genes.to_dict("list"), row_names=bundle.rownames) - col_bioc = BiocFrame(bundle.samples.to_dict("list"), row_names=bundle.colnames) + # We need to make sure bundle.genes and bundle.samples return dictionaries of column names mapping to lists of values + row_bioc = BiocFrame(bundle.genes, row_names=bundle.rownames) + col_bioc = BiocFrame(bundle.samples, row_names=bundle.colnames) assays = {} if bundle.matrix is not None: diff --git a/src/expressionatlas/models.py b/src/expressionatlas/models.py index 74ccf84..b0c5d73 100644 --- a/src/expressionatlas/models.py +++ b/src/expressionatlas/models.py @@ -6,7 +6,7 @@ from enum import Enum from typing import Any -import pandas as pd +from biocframe import BiocFrame class ExperimentType(str, Enum): @@ -58,16 +58,27 @@ def to_dict(self) -> dict[str, Any]: } -def search_results_to_dataframe(results: list[SearchResult]) -> pd.DataFrame: - """Convert list of SearchResult objects to a pandas DataFrame.""" +def search_results_to_biocframe(results: list[SearchResult]) -> BiocFrame: + """Convert list of SearchResult objects to a BiocFrame.""" + columns = ["Accession", "Species", "Type", "Title"] if not results: - return pd.DataFrame(columns=["Accession", "Species", "Type", "Title"]) - - data = [r.to_dict() for r in results if not r.connection_error] - df = pd.DataFrame(data) + return BiocFrame({col: [] for col in columns}, column_names=columns) + valid_results = [r for r in results if not r.connection_error] + # Sort by Species, Type, then Accession (matching R package behavior) - if not df.empty: - df = df.sort_values(["Species", "Type", "Accession"]).reset_index(drop=True) - - return df + valid_results.sort( + key=lambda r: ( + r.species if r.species is not None else "", + r.experiment_type if r.experiment_type is not None else "", + r.accession, + ) + ) + + data = {col: [] for col in columns} + for r in valid_results: + d = r.to_dict() + for col in columns: + data[col].append(d[col]) + + return BiocFrame(data, column_names=columns) diff --git a/tests/test_integration.py b/tests/test_integration.py index 6e98d46..4d8cc60 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -10,7 +10,7 @@ from expressionatlas.validation import is_valid_accession @pytest.mark.integration -@pytest.mark.skip("takes too long") +# @pytest.mark.skip("takes too long") class TestExpressionAtlasClientIntegration: """Integration tests for ExpressionAtlasClient.""" @@ -19,14 +19,14 @@ def test_search_cancer_human(self) -> None: client = ExpressionAtlasClient() results = client.search_experiments(properties=["cancer"], species="homo sapiens") - assert len(results) > 0 - assert "Accession" in results.columns - assert "Species" in results.columns - assert "Type" in results.columns - assert "Title" in results.columns + assert results.shape[0] > 0 + columns = results.get_column_names() + assert "Accession" in columns + assert "Species" in columns + assert "Type" in columns + assert "Title" in columns - # All accessions should be valid - for acc in results["Accession"]: + for acc in results.get_column("Accession"): assert is_valid_accession(acc) def test_search_salt_oryza(self) -> None: @@ -34,7 +34,7 @@ def test_search_salt_oryza(self) -> None: client = ExpressionAtlasClient() results = client.search_experiments(properties=["salt"], species="oryza sativa") - assert len(results) > 0 + assert results.shape[0] > 0 def test_download_single_experiment(self) -> None: """Download a single experiment should succeed.""" diff --git a/tests/test_models.py b/tests/test_models.py index bffceb3..e213fec 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -4,7 +4,7 @@ from expressionatlas.models import ( ExperimentType, SearchResult, - search_results_to_dataframe, + search_results_to_biocframe, ) @@ -65,14 +65,14 @@ def test_default_connection_error(self) -> None: assert result.connection_error is False -class TestSearchResultsToDataframe: - """Tests for search_results_to_dataframe function.""" +class TestSearchResultsToBiocframe: + """Tests for search_results_to_biocframe function.""" def test_empty_list(self) -> None: - """Empty list should return empty DataFrame with correct columns.""" - df = search_results_to_dataframe([]) - assert list(df.columns) == ["Accession", "Species", "Type", "Title"] - assert len(df) == 0 + """Empty list should return empty BiocFrame with correct columns.""" + bf = search_results_to_biocframe([]) + assert list(bf.get_column_names()) == ["Accession", "Species", "Type", "Title"] + assert bf.shape[0] == 0 def test_filters_connection_errors(self) -> None: """Should exclude results with connection errors.""" @@ -80,9 +80,9 @@ def test_filters_connection_errors(self) -> None: SearchResult("E-MTAB-1624", "Human", "RNA-seq", "Test 1"), SearchResult("E-MTAB-1625", None, None, None, connection_error=True), ] - df = search_results_to_dataframe(results) - assert len(df) == 1 - assert df.iloc[0]["Accession"] == "E-MTAB-1624" + bf = search_results_to_biocframe(results) + assert bf.shape[0] == 1 + assert bf.get_column("Accession")[0] == "E-MTAB-1624" def test_sorts_by_species_type_accession(self) -> None: """Should sort by Species, Type, then Accession.""" @@ -91,8 +91,9 @@ def test_sorts_by_species_type_accession(self) -> None: SearchResult("E-MTAB-1", "Human", "Array", "Test 1"), SearchResult("E-MTAB-3", "Human", "RNA-seq", "Test 3"), ] - df = search_results_to_dataframe(results) + bf = search_results_to_biocframe(results) # Human Array, Human RNA-seq, Zebra RNA-seq - assert df.iloc[0]["Accession"] == "E-MTAB-1" - assert df.iloc[1]["Accession"] == "E-MTAB-3" - assert df.iloc[2]["Accession"] == "E-MTAB-2" + ids = bf.get_column("Accession") + assert ids[0] == "E-MTAB-1" + assert ids[1] == "E-MTAB-3" + assert ids[2] == "E-MTAB-2" From eb46703be3fba547b418778a7f0a3636217d08c6 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 30 Mar 2026 18:05:37 +0000 Subject: [PATCH 05/16] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- src/expressionatlas/client.py | 18 ++++++++++++++---- src/expressionatlas/download.py | 26 ++++++++++++++------------ src/expressionatlas/models.py | 2 +- 3 files changed, 29 insertions(+), 17 deletions(-) diff --git a/src/expressionatlas/client.py b/src/expressionatlas/client.py index c4e4c87..9a8bcb4 100644 --- a/src/expressionatlas/client.py +++ b/src/expressionatlas/client.py @@ -232,11 +232,21 @@ def get_experiments( ... species="homo sapiens", ... ) >>> # Download all RNA-seq experiments from search results - >>> types = results.get_column("Type") - >>> accessions = results.get_column("Accession") + >>> types = results.get_column( + ... "Type" + ... ) + >>> accessions = results.get_column( + ... "Accession" + ... ) >>> rnaseq_accessions = [ - ... acc for acc, typ in zip(accessions, types) - ... if typ and "RNA-seq" in typ + ... acc + ... for acc, typ in zip( + ... accessions, + ... types, + ... ) + ... if typ + ... and "RNA-seq" + ... in typ ... ] >>> experiments = client.get_experiments( ... rnaseq_accessions diff --git a/src/expressionatlas/download.py b/src/expressionatlas/download.py index 1a1c18e..e57a581 100644 --- a/src/expressionatlas/download.py +++ b/src/expressionatlas/download.py @@ -17,7 +17,6 @@ from pathlib import Path from urllib.error import URLError from urllib.request import urlopen -from typing import TypedDict, Dict, List, Optional, Any import numpy as np from biocframe import BiocFrame @@ -222,16 +221,16 @@ def _download_tsv(url: str) -> dict[str, list[str]]: logger.debug(f"Downloading: {url}") with urlopen(url, timeout=60) as response: content = response.read().decode("utf-8") - + reader = csv.reader(io.StringIO(content), delimiter="\t") header = next(reader) data = {h: [] for h in header} - + for row in reader: for i, h in enumerate(header): val = row[i] if i < len(row) else None data[h].append(val) - + return data @@ -258,10 +257,10 @@ def _try_download_sdrf(url: str) -> dict[str, dict[str, str]] | None: sample_id = parts[sample_idx] attr_name = parts[attr_idx] attr_value = parts[value_idx] - + if sample_id not in records: records[sample_id] = {} - + if attr_name not in records[sample_id]: records[sample_id][attr_name] = attr_value @@ -272,7 +271,10 @@ def _try_download_sdrf(url: str) -> dict[str, dict[str, str]] | None: def _create_summarized_experiment_from_tsv( - df_data: dict[str, list[str]], design_data: dict[str, dict[str, str]] | None, accession: str, assay_name: str = "counts" + df_data: dict[str, list[str]], + design_data: dict[str, dict[str, str]] | None, + accession: str, + assay_name: str = "counts", ) -> SummarizedExperiment: """Create SummarizedExperiment from TSV data.""" if not df_data: @@ -284,7 +286,7 @@ def _create_summarized_experiment_from_tsv( numeric_cols = [] annotation_cols = [] - + for col in all_cols: vals = df_data[col] is_num = True @@ -319,7 +321,7 @@ def _create_summarized_experiment_from_tsv( else: col_float.append(float(v)) matrix_data.append(col_float) - + matrix = np.array(matrix_data, dtype=np.float64).T assays = {assay_name: matrix} @@ -336,15 +338,15 @@ def _create_summarized_experiment_from_tsv( for s in colnames: if s in design_data: all_attrs.update(design_data[s].keys()) - + all_attrs = sorted(list(all_attrs)) - + for attr in all_attrs: col_data[attr] = [] for s in colnames: val = design_data.get(s, {}).get(attr, None) col_data[attr].append(val) - + col_bioc = BiocFrame(col_data, row_names=colnames) metadata = {"accession": accession, "source": "tsv"} diff --git a/src/expressionatlas/models.py b/src/expressionatlas/models.py index b0c5d73..5f937ab 100644 --- a/src/expressionatlas/models.py +++ b/src/expressionatlas/models.py @@ -65,7 +65,7 @@ def search_results_to_biocframe(results: list[SearchResult]) -> BiocFrame: return BiocFrame({col: [] for col in columns}, column_names=columns) valid_results = [r for r in results if not r.connection_error] - + # Sort by Species, Type, then Accession (matching R package behavior) valid_results.sort( key=lambda r: ( From 17149869c6f66d6eaeda1fd323d4d3ff1a0df446 Mon Sep 17 00:00:00 2001 From: Jayaram Kancherla Date: Tue, 11 Aug 2026 22:23:56 -0700 Subject: [PATCH 06/16] Getting the package to work for rnaseq expts. --- .github/publish-pypi.yml | 52 --------- .github/run-tests.yml | 73 ------------ README.md | 40 +++++-- setup.cfg | 2 +- src/expressionatlas/__init__.py | 19 +--- src/expressionatlas/api.py | 95 ++++++++-------- src/expressionatlas/client.py | 148 +++++++++++++------------ src/expressionatlas/download.py | 177 +++++++++++++++++------------- src/expressionatlas/validation.py | 72 +++++------- tests/test_download.py | 23 ++++ 10 files changed, 310 insertions(+), 391 deletions(-) delete mode 100644 .github/publish-pypi.yml delete mode 100644 .github/run-tests.yml create mode 100644 tests/test_download.py diff --git a/.github/publish-pypi.yml b/.github/publish-pypi.yml deleted file mode 100644 index 405fee0..0000000 --- a/.github/publish-pypi.yml +++ /dev/null @@ -1,52 +0,0 @@ -name: Publish to PyPI - -on: - push: - tags: "*" - -jobs: - build: - runs-on: ubuntu-latest - permissions: - id-token: write - repository-projects: write - contents: write - pages: write - - steps: - - uses: actions/checkout@v4 - - - name: Set up Python 3.12 - uses: actions/setup-python@v5 - with: - python-version: 3.12 - - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install tox - - - name: Test with tox - run: | - tox - - - name: Build Project and Publish - run: | - python -m tox -e clean,build - - # This uses the trusted publisher workflow so no token is required. - - name: Publish to PyPI - uses: pypa/gh-action-pypi-publish@release/v1 - - - name: Build docs - run: | - tox -e docs - - - run: touch ./docs/_build/html/.nojekyll - - - name: GH Pages Deployment - uses: JamesIves/github-pages-deploy-action@v4 - with: - branch: gh-pages # The branch the action should deploy to. - folder: ./docs/_build/html - clean: true # Automatically remove deleted files from the deploy branch diff --git a/.github/run-tests.yml b/.github/run-tests.yml deleted file mode 100644 index 01f4e9a..0000000 --- a/.github/run-tests.yml +++ /dev/null @@ -1,73 +0,0 @@ -name: Test the library - -on: - push: - branches: - - master # for legacy repos - - main - pull_request: - branches: - - master # for legacy repos - - main - workflow_dispatch: # Allow manually triggering the workflow - schedule: - # Run roughly every 15 days at 00:00 UTC - # (useful to check if updates on dependencies break the package) - - cron: "0 0 1,16 * *" - -permissions: - contents: read - -concurrency: - group: >- - ${{ github.workflow }}-${{ github.ref_type }}- - ${{ github.event.pull_request.number || github.sha }} - cancel-in-progress: true - -jobs: - test: - strategy: - matrix: - python: ["3.10", "3.11", "3.12", "3.13", "3.14"] - platform: - - ubuntu-latest - # - macos-latest - # - windows-latest - runs-on: ${{ matrix.platform }} - name: Python ${{ matrix.python }}, ${{ matrix.platform }} - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-python@v5 - id: setup-python - with: - python-version: ${{ matrix.python }} - - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install tox coverage - - - name: Run tests - run: >- - pipx run --python '${{ steps.setup-python.outputs.python-path }}' - tox - -- -rFEx --durations 10 --color yes --cov --cov-branch --cov-report=xml # pytest args - - - name: Check for codecov token availability - id: codecov-check - shell: bash - run: | - if [ ${{ secrets.CODECOV_TOKEN }} != '' ]; then - echo "codecov=true" >> $GITHUB_OUTPUT; - else - echo "codecov=false" >> $GITHUB_OUTPUT; - fi - - - name: Upload coverage reports to Codecov with GitHub Action - uses: codecov/codecov-action@v5 - if: ${{ steps.codecov-check.outputs.codecov == 'true' }} - env: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} - slug: ${{ github.repository }} - flags: ${{ matrix.platform }} - py${{ matrix.python }} diff --git a/README.md b/README.md index 19bb2a7..0138163 100644 --- a/README.md +++ b/README.md @@ -24,10 +24,13 @@ Expression Atlas is a comprehensive resource of gene and protein expression data - **Download**: Retrieve experiment data with automatic format handling - **Analyze**: Work with R-compatible data structures in Python +> [!WARNING] +> This package only supports downloading data from the bulk **Expression Atlas**. It does not support downloading data from the **Single Cell Expression Atlas**. Accessions for single-cell experiments (e.g., `E-MTAB-7041`) will fail to download. + ### Basic Usage ```python -from expression_atlas import ExpressionAtlasClient +from expressionatlas import ExpressionAtlasClient # Initialize client client = ExpressionAtlasClient() @@ -42,19 +45,34 @@ print(results) BiocFrame with 208 rows and 4 columns Accession Species Type Title - [0] E-MTAB-8198 Homo sapiens Cell line - High-thr... Functional effect of... - [1] E-MTAB-8532 Homo sapiens Human - One-color mi... DNA microarray studi... - [2] E-GEOD-43306 Homo sapiens RNA-seq of coding RNA Translating transcri... + [0] E-MTAB-8198 None None Functional effect of... + [1] E-MTAB-8532 None None DNA microarray studi... + [2] E-GEOD-43306 None None Translating transcri... ... ... ... ... - [205] E-MTAB-779 Homo sapiens transcription profil... OncomiRs like let-7 ... - [206] E-TABM-1118 Homo sapiens transcription profil... Transcrption profili... - [207] E-TABM-601 Homo sapiens transcription profil... Transcription profil... + [205] E-MTAB-779 None None OncomiRs like let-7 ... + [206] E-TABM-1118 None None Transcrption profili... + [207] E-TABM-601 None None Transcription profil... + +### Fetch Full Metadata + +The initial search is optimized for speed and does not fetch full metadata. To retrieve complete details (including `Species` and `Type`), use `fetch_experiment_metadata`: + +```python +# Fetch full metadata for specific experiments +metadata = client.fetch_experiment_metadata(["E-MTAB-8198", "E-MTAB-8532"]) +print(metadata) +``` + BiocFrame with 2 rows and 4 columns + Accession Species Type Title + + [0] E-MTAB-8198 Homo sapiens Cell line - High-thr... Functional effect of... + [1] E-MTAB-8532 Homo sapiens Human - One-color mi... DNA microarray studi... ### Download RNA-seq Data ```python # Download a single experiment -exp = client.get_experiment("E-MTAB-7041") +exp = client.get_experiment("E-MTAB-1625") # Access RNA-seq data (SummarizedExperiment) rnaseq = exp["rnaseq"] @@ -98,6 +116,12 @@ for acc, exp in experiments.items(): print(f"{acc}: {exp['rnaseq'].shape if 'rnaseq' in exp else 'microarray'}") ``` +### Direct RData / rda Support + +The client automatically downloads and parses both `.rds` and `.Rdata` / `.rda` files directly without relying on a cloud converter service: +- Tries downloading and parsing `.rds` file using `rds2py.read_rds`. +- If the `.rds` file is not available, falls back to direct download and loading of the `.Rdata` file using `rds2py.read_rda`. + ## Note diff --git a/setup.cfg b/setup.cfg index 36c0dfc..cfda80e 100644 --- a/setup.cfg +++ b/setup.cfg @@ -16,7 +16,7 @@ url = https://github.com/biocpy/expressionatlas # Add here related links, for example: project_urls = Documentation = https://github.com/biocpy/expressionatlas -# Source = https://github.com/pyscaffold/pyscaffold/ + Source = https://github.com/biocpy/expressionatlas # Changelog = https://pyscaffold.org/en/latest/changelog.html # Tracker = https://github.com/pyscaffold/pyscaffold/issues # Conda-Forge = https://anaconda.org/conda-forge/pyscaffold diff --git a/src/expressionatlas/__init__.py b/src/expressionatlas/__init__.py index abea65e..b0d9ae6 100644 --- a/src/expressionatlas/__init__.py +++ b/src/expressionatlas/__init__.py @@ -1,14 +1,3 @@ -""" -Expression Atlas Python Client - -A Python client for searching and downloading gene expression datasets -from EMBL-EBI Expression Atlas. - -Full BiocPy compatibility: Data structures use BiocPy ecosystem: -- SummarizedExperiment for RNA-seq and microarray (genes × samples matrix) -- NamedList for experiment containers -""" - import sys if sys.version_info[:2] >= (3, 8): @@ -26,17 +15,17 @@ finally: del version, PackageNotFoundError -from expressionatlas.client import ExpressionAtlasClient -from expressionatlas.download import ( +from .client import ExpressionAtlasClient +from .download import ( get_atlas_data, get_atlas_experiment, has_converter_available, has_tsv_files, ) -from expressionatlas.exceptions import ( +from .exceptions import ( APIError, DownloadError, ExpressionAtlasError, InvalidAccessionError, ) -from expressionatlas.models import SearchResult +from .models import SearchResult diff --git a/src/expressionatlas/api.py b/src/expressionatlas/api.py index 7cef8b8..39daeda 100644 --- a/src/expressionatlas/api.py +++ b/src/expressionatlas/api.py @@ -8,8 +8,8 @@ import requests -from expressionatlas.exceptions import APIError -from expressionatlas.models import ExperimentType, SearchResult +from .exceptions import APIError +from .models import ExperimentType, SearchResult logger = logging.getLogger(__name__) @@ -26,13 +26,11 @@ class BioStudiesAPI: """Client for BioStudies API to search Expression Atlas experiments.""" def __init__(self, timeout: int = 30) -> None: - """ - Initialize BioStudies API client. + """Initialize BioStudies API client. - Parameters - ---------- - timeout : int - Request timeout in seconds (default: 30). + Args: + timeout: + Request timeout in seconds (default: 30). """ self.timeout = timeout self.session = requests.Session() @@ -43,31 +41,28 @@ def search( species: str | None = None, page_size: int = DEFAULT_PAGE_SIZE, ) -> list[SearchResult]: - """ - Search for Expression Atlas experiments. - - Parameters - ---------- - properties : list[str] - Search terms (e.g., ["cancer", "breast"]). - species : str, optional - Species to filter by (e.g., "homo sapiens"). - page_size : int - Number of results per page (default: 100). - - Returns - ------- - list[SearchResult] + """Search for Expression Atlas experiments. + + Args: + properties: + Search terms (e.g., ["cancer", "breast"]). + + species: + Species to filter by (e.g., "homo sapiens"). + + page_size: + Number of results per page (default: 100). + + Returns: List of search results with experiment metadata. - Raises - ------ - APIError - If the API request fails. + Raises: + APIError: + If the API request fails. """ # Build query URL - query_terms = "".join(quote(p) for p in properties) - url = f"{BIOSTUDIES_SEARCH_URL}?query={query_terms}&gxa=TRUE&pageSize={page_size}" + query_terms = ",".join(quote(p) for p in properties) + url = f"{BIOSTUDIES_SEARCH_URL}?query={query_terms}&link_type=gxa&pageSize={page_size}" if species: url += f"&organism={quote(species)}" @@ -94,21 +89,26 @@ def search( logger.warning("Total hits count from BioStudies is not exact.") # Paginate through all results - all_accessions = self._paginate_results(url, total_hits, page_size) + hits = self._paginate_results(url, total_hits, page_size) - if len(all_accessions) != total_hits: - logger.warning(f"Expected {total_hits} accessions, got {len(all_accessions)}.") + if len(hits) != total_hits: + logger.warning(f"Expected {total_hits} hits, got {len(hits)}.") - # Fetch metadata for each experiment - logger.info(f"Retrieving metadata for {len(all_accessions)} experiments...") - results = self._fetch_experiment_metadata(all_accessions) - logger.info("Metadata retrieval completed.") + results = [] + for hit in hits: + results.append(SearchResult( + accession=hit.get("accession"), + species=None, + experiment_type=None, + title=hit.get("title"), + connection_error=False, + )) return results - def _paginate_results(self, base_url: str, total_hits: int, page_size: int) -> list[str]: - """Paginate through search results to collect all accessions.""" - all_accessions: list[str] = [] + def _paginate_results(self, base_url: str, total_hits: int, page_size: int) -> list[dict[str, Any]]: + """Paginate through search results to collect all hits.""" + all_hits = [] # Calculate number of pages num_pages = (total_hits + page_size - 1) // page_size @@ -118,20 +118,17 @@ def _paginate_results(self, base_url: str, total_hits: int, page_size: int) -> l response = self._request(page_url) data = response.json() - accessions = data.get("hits", []) - if isinstance(accessions, list) and accessions: - # Extract accession from each hit - for hit in accessions: + hits = data.get("hits", []) + if isinstance(hits, list) and hits: + for hit in hits: if isinstance(hit, dict): - acc = hit.get("accession") + all_hits.append(hit) else: - acc = hit - if acc: - all_accessions.append(acc) + all_hits.append({"accession": hit}) - return all_accessions + return all_hits - def _fetch_experiment_metadata(self, accessions: list[str]) -> list[SearchResult]: + def fetch_experiment_metadata(self, accessions: list[str]) -> list[SearchResult]: """Fetch detailed metadata for each experiment.""" results: list[SearchResult] = [] diff --git a/src/expressionatlas/client.py b/src/expressionatlas/client.py index 9a8bcb4..3922b95 100644 --- a/src/expressionatlas/client.py +++ b/src/expressionatlas/client.py @@ -8,10 +8,10 @@ from biocframe import BiocFrame from biocutils import NamedList -from expressionatlas.api import BioStudiesAPI -from expressionatlas.download import get_atlas_data, get_atlas_experiment -from expressionatlas.models import search_results_to_biocframe -from expressionatlas.validation import validate_accession +from .api import BioStudiesAPI +from .download import get_atlas_data, get_atlas_experiment +from .models import search_results_to_biocframe +from .validation import validate_accession logger = logging.getLogger(__name__) @@ -43,22 +43,18 @@ class ExpressionAtlasClient: ... "E-MTAB-1624" ... ) >>> # Download multiple experiments - >>> exps = client.get_experiments( - ... [ - ... "E-MTAB-1624", - ... "E-MTAB-1625", - ... ] - ... ) + >>> exps = client.get_experiments([ + ... "E-MTAB-1624", + ... "E-MTAB-1625", + ... ]) """ def __init__(self, timeout: int = 30) -> None: - """ - Initialize Expression Atlas client. + """Initialize Expression Atlas client. - Parameters - ---------- - timeout : int - Request timeout in seconds (default: 30). + Args: + timeout: + Request timeout in seconds (default: 30). """ self.timeout = timeout self._api: BioStudiesAPI | None = None @@ -75,34 +71,31 @@ def search_experiments( properties: str | Sequence[str], species: str | None = None, ) -> BiocFrame: - """ - Search for Expression Atlas experiments matching given criteria. + """Search for Expression Atlas experiments matching given criteria. Equivalent to R function: searchAtlasExperiments() - Parameters - ---------- - properties : str or list of str - Search terms (e.g., "cancer" or ["cancer", "breast"]). - species : str, optional - Species to filter by (e.g., "homo sapiens", "mus musculus"). - If not provided, searches across all species. - - Returns - ------- - BiocFrame + Args: + properties: + Search terms (e.g., "cancer" or ["cancer", "breast"]). + + species: + Species to filter by (e.g., "homo sapiens", "mus musculus"). + If not provided, searches across all species. + + Returns: BiocFrame with columns: Accession, Species, Type, Title. Sorted by Species, Type, then Accession. + Note: Species and Type will initially be None. Use `fetch_experiment_metadata` + to retrieve full metadata for specific accessions. - Raises - ------ - ValueError - If no search properties provided. - APIError - If the BioStudies API request fails. + Raises: + ValueError: + If no search properties provided. + APIError: + If the BioStudies API request fails. - Examples - -------- + Examples: >>> client = ExpressionAtlasClient() >>> # Search for salt stress experiments in rice >>> results = client.search_experiments( @@ -140,31 +133,45 @@ def search_experiments( return df - def get_experiment(self, accession: str) -> NamedList | None: + def fetch_experiment_metadata(self, accession: str | Sequence[str]) -> BiocFrame: + """Fetch full metadata for one or more experiment accessions. + + Args: + accession: + A single accession string or a sequence of accession strings. + + Returns: + A BiocFrame containing the full metadata. """ - Download a single Expression Atlas experiment. + if isinstance(accession, str): + accessions = [accession] + else: + accessions = list(accession) + + results = self.api.fetch_experiment_metadata(accessions) + return search_results_to_biocframe(results) + + def get_experiment(self, accession: str) -> NamedList | None: + """Download a single Expression Atlas experiment. Equivalent to R function: getAtlasExperiment() - Parameters - ---------- - accession : str - ArrayExpress/BioStudies experiment accession (e.g., "E-MTAB-1624"). + Args: + accession: + ArrayExpress/BioStudies experiment accession (e.g., "E-MTAB-1624"). + Note: This client only supports bulk Expression Atlas experiments. + Single-cell experiment accessions (e.g., "E-MTAB-7041") are not supported. - Returns - ------- - NamedList or None + Returns: The downloaded experiment data, or None if download fails. For RNA-seq: access via ["rnaseq"] to get SummarizedExperiment For microarray: access via array design (e.g., ["A-AFFY-126"]) to get SummarizedExperiment - Raises - ------ - InvalidAccessionError - If the accession format is invalid. + Raises: + InvalidAccessionError: + If the accession format is invalid. - Examples - -------- + Examples: >>> client = ExpressionAtlasClient() >>> # RNA-seq experiment >>> exp = client.get_experiment( @@ -198,34 +205,29 @@ def get_experiments( accessions: Sequence[str], skip_invalid: bool = True, ) -> NamedList: - """ - Download multiple Expression Atlas experiments. + """Download multiple Expression Atlas experiments. Equivalent to R function: getAtlasData() - Parameters - ---------- - accessions : list of str - List of experiment accessions to download. - skip_invalid : bool - If True (default), skip invalid accessions with a warning. - If False, raise an error on invalid accessions. - - Returns - ------- - NamedList + Args: + accessions: + List of experiment accessions to download. + + skip_invalid: + If True (default), skip invalid accessions with a warning. + If False, raise an error on invalid accessions. + + Returns: Dictionary-like object mapping accession to experiment data (NamedList). Failed downloads are excluded from the result. - Raises - ------ - ValueError - If no valid accessions provided. - InvalidAccessionError - If skip_invalid is False and an invalid accession is found. + Raises: + ValueError: + If no valid accessions provided. + InvalidAccessionError: + If skip_invalid is False and an invalid accession is found. - Examples - -------- + Examples: >>> client = ExpressionAtlasClient() >>> results = client.search_experiments( ... "cancer", diff --git a/src/expressionatlas/download.py b/src/expressionatlas/download.py index e57a581..8811ffb 100644 --- a/src/expressionatlas/download.py +++ b/src/expressionatlas/download.py @@ -23,8 +23,8 @@ from biocutils import NamedList from summarizedexperiment import SummarizedExperiment -from expressionatlas.exceptions import DownloadError -from expressionatlas.validation import validate_accession +from .exceptions import DownloadError +from .validation import validate_accession logger = logging.getLogger(__name__) @@ -33,34 +33,22 @@ def has_tsv_files(accession: str) -> bool: - """ - Check if an experiment has TSV files available for download. + """Check if an experiment has TSV files available for download. - Parameters - ---------- - accession : str - Valid ArrayExpress/BioStudies accession (e.g., "E-MTAB-1624"). + Args: + accession: + Valid ArrayExpress/BioStudies accession (e.g., "E-MTAB-1624"). - Returns - ------- - bool + Returns: True if TSV files are available, False otherwise. """ validate_accession(accession) - base_url = f"{FTP_BASE_URL}/{accession}" - - counts_url = f"{base_url}/{accession}-raw-counts.tsv" - norm_url = f"{base_url}/{accession}-normalized-expressions.tsv" - - for url in [counts_url, norm_url]: - try: - with urlopen(url, timeout=10) as response: - response.read(100) - return True - except Exception: - continue - - return False + try: + with urlopen(f"{FTP_BASE_URL}/{accession}/", timeout=10) as response: + content = response.read().decode("utf-8") + return any(x in content for x in ["-raw-counts.tsv", "-tpms.tsv", "-fpkms.tsv", "-normalized-expressions.tsv"]) + except Exception: + return False def has_converter_available() -> bool: @@ -71,17 +59,15 @@ def has_converter_available() -> bool: def get_atlas_experiment(experiment_accession: str) -> NamedList | None: - """ - Download and return the data representing a single Expression Atlas experiment. + """Download and return the data representing a single Expression Atlas experiment. - Parameters - ---------- - experiment_accession : str - Valid ArrayExpress/BioStudies accession (e.g., "E-MTAB-1624"). + Args: + experiment_accession: + Valid ArrayExpress/BioStudies accession (e.g., "E-MTAB-1624"). + Note: This function only supports bulk Expression Atlas experiments. + Single-cell experiment accessions are not supported. - Returns - ------- - NamedList or None + Returns: For RNA-seq: NamedList with key "rnaseq" containing SummarizedExperiment For microarray: NamedList with array design accessions as keys, each containing SummarizedExperiment Returns None if download fails. @@ -97,18 +83,25 @@ def get_atlas_experiment(experiment_accession: str) -> NamedList | None: try: experiment_summary = _download_and_load_rds(full_url, experiment_accession) except DownloadError: - logger.info("RDS not available, trying TSV fallback...") try: - experiment_summary = _download_tsv_fallback(experiment_accession) + rdata_file = f"{experiment_accession}-atlasExperimentSummary.Rdata" + rdata_url = f"{FTP_BASE_URL}/{experiment_accession}/{rdata_file}" + logger.info(f"RDS not available, trying direct RData download from:\n {rdata_url}") + experiment_summary = _download_and_load_rds(rdata_url, experiment_accession) except DownloadError: - if has_converter_available(): - logger.info("TSV not available, trying cloud converter service...") - experiment_summary = _download_via_converter( - f"{FTP_BASE_URL}/{experiment_accession}/{experiment_accession}-atlasExperimentSummary.Rdata", - experiment_accession, - ) - else: - raise + logger.info("RData not available, trying TSV fallback...") + + try: + experiment_summary = _download_tsv_fallback(experiment_accession) + except DownloadError: + if has_converter_available(): + logger.info("TSV not available, trying cloud converter service...") + experiment_summary = _download_via_converter( + f"{FTP_BASE_URL}/{experiment_accession}/{experiment_accession}-atlasExperimentSummary.Rdata", + experiment_accession, + ) + else: + raise if experiment_summary: logger.info(f"Successfully downloaded experiment summary object for {experiment_accession}") @@ -126,17 +119,13 @@ def get_atlas_experiment(experiment_accession: str) -> NamedList | None: def get_atlas_data(experiment_accessions: list[str]) -> NamedList: - """ - Download NamedList objects for one or more Expression Atlas experiments. + """Download NamedList objects for one or more Expression Atlas experiments. - Parameters - ---------- - experiment_accessions : list[str] - List of experiment accessions to download. + Args: + experiment_accessions: + List of experiment accessions to download. - Returns - ------- - NamedList + Returns: Dictionary-like object mapping accession to experiment data. """ from expressionatlas.validation import filter_valid_accessions @@ -159,10 +148,18 @@ def get_atlas_data(experiment_accessions: list[str]) -> NamedList: def _download_and_load_rds(url: str, accession: str) -> NamedList: - """Download and load RDS file using rds2py.""" + """Download and load RDS or RData/rda file using rds2py.""" import rds2py - with tempfile.NamedTemporaryFile(suffix=".rds", delete=False) as tmp: + parsed_url = url.split("?")[0] + suffix = ".rds" + + if parsed_url.lower().endswith(".rdata"): + suffix = ".rdata" + elif parsed_url.lower().endswith(".rda"): + suffix = ".rda" + + with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp: try: with urlopen(url, timeout=120) as response: tmp.write(response.read()) @@ -171,14 +168,19 @@ def _download_and_load_rds(url: str, accession: str) -> NamedList: tmp_path = Path(tmp.name) try: - data = rds2py.read_rds(str(tmp_path)) + try: + if suffix in [".rdata", ".rda"]: + data = rds2py.read_rda(str(tmp_path)) + else: + data = rds2py.read_rds(str(tmp_path)) + except Exception as e: + raise DownloadError(accession, f"Failed to parse {suffix} file: {e}") from e result = NamedList() if isinstance(data, dict): for k, v in data.items(): result[k] = v else: - # Fallback if the top level object is not a dict result["data"] = data return result @@ -191,29 +193,50 @@ def _download_tsv_fallback(accession: str) -> NamedList: result = NamedList() base_url = f"{FTP_BASE_URL}/{accession}" - sdrf_url = f"{base_url}/{accession}.condensed-sdrf.tsv" - design_df = _try_download_sdrf(sdrf_url) - - counts_url = f"{base_url}/{accession}-raw-counts.tsv" try: - counts_df = _download_tsv(counts_url) - result["rnaseq"] = _create_summarized_experiment_from_tsv(counts_df, design_df, accession, "counts") - logger.info(f"Downloaded RNA-seq data from TSV for {accession}") - return result - except URLError: - logger.debug(f"No raw counts TSV for {accession}") + with urlopen(f"{base_url}/", timeout=20) as response: + ftp_listing = response.read().decode("utf-8") + except Exception as e: + raise DownloadError(accession, f"FTP directory not accessible: {e}") from e - norm_url = f"{base_url}/{accession}-normalized-expressions.tsv" - try: - norm_df = _download_tsv(norm_url) - # mapped to SummarizedExperiment as per instructions - result["normalized"] = _create_summarized_experiment_from_tsv(norm_df, design_df, accession, "exprs") - logger.info(f"Downloaded normalized data from TSV for {accession}") - return result - except URLError: - logger.debug(f"No normalized TSV for {accession}") + files = [line.split()[-1] for line in ftp_listing.strip().split("\n") if line] + + sdrf_file = next((f for f in files if f.endswith(".condensed-sdrf.tsv")), f"{accession}.condensed-sdrf.tsv") + design_df = _try_download_sdrf(f"{base_url}/{sdrf_file}") - raise DownloadError(accession, "No TSV or RDS data files found.") + rnaseq_files = [] + for suffix, assay_name in [("-raw-counts.tsv", "counts"), ("-raw-counts.tsv.undecorated", "counts"), ("-tpms.tsv", "tpms"), ("-fpkms.tsv", "fpkms")]: + for f in files: + if f == f"{accession}{suffix}": + rnaseq_files.append((f, assay_name)) + + if rnaseq_files: + f, assay_name = rnaseq_files[0] + try: + df = _download_tsv(f"{base_url}/{f}") + result["rnaseq"] = _create_summarized_experiment_from_tsv(df, design_df, accession, assay_name) + logger.info(f"Downloaded RNA-seq data ({assay_name}) from TSV for {accession}") + except Exception as e: + logger.debug(f"Failed to download or parse {f}: {e}") + + microarray_files = [] + for f in files: + if f.startswith(f"{accession}_") and f.endswith("-normalized-expressions.tsv"): + design = f[len(accession)+1 :].split("-normalized-expressions")[0] + microarray_files.append((f, design)) + + for f, design in microarray_files: + try: + df = _download_tsv(f"{base_url}/{f}") + result[design] = _create_summarized_experiment_from_tsv(df, design_df, accession, "exprs") + logger.info(f"Downloaded microarray data ({design}) from TSV for {accession}") + except Exception as e: + logger.debug(f"Failed to download or parse {f}: {e}") + + if len(result) == 0: + raise DownloadError(accession, "No TSV data files found in FTP directory.") + + return result def _download_tsv(url: str) -> dict[str, list[str]]: diff --git a/src/expressionatlas/validation.py b/src/expressionatlas/validation.py index 080937d..47f7a01 100644 --- a/src/expressionatlas/validation.py +++ b/src/expressionatlas/validation.py @@ -3,30 +3,25 @@ import re from collections.abc import Sequence -from expressionatlas.exceptions import InvalidAccessionError +from .exceptions import InvalidAccessionError # Pattern: E-XXXX-#### where XXXX is 4 word characters and #### is one or more digits ACCESSION_PATTERN = re.compile(r"^E-\w{4}-\d+$") def is_valid_accession(accession: str) -> bool: - """ - Check if experiment accession matches expected ArrayExpress/BioStudies format. + """Check if experiment accession matches expected ArrayExpress/BioStudies format. Valid format: E-XXXX-#### (e.g., E-MTAB-1624, E-GEOD-11175) - Parameters - ---------- - accession : str - The experiment accession to validate. + Args: + accession: + The experiment accession to validate. - Returns - ------- - bool + Returns: True if valid, False otherwise. - Examples - -------- + Examples: >>> is_valid_accession( ... "E-MTAB-1624" ... ) @@ -50,23 +45,18 @@ def is_valid_accession(accession: str) -> bool: def validate_accession(accession: str) -> str: - """ - Validate accession and raise error if invalid. + """Validate accession and raise error if invalid. - Parameters - ---------- - accession : str - The experiment accession to validate. + Args: + accession: + The experiment accession to validate. - Returns - ------- - str + Returns: The validated accession (unchanged if valid). - Raises - ------ - InvalidAccessionError - If the accession format is invalid. + Raises: + InvalidAccessionError: + If the accession format is invalid. """ if not is_valid_accession(accession): raise InvalidAccessionError(accession) @@ -77,26 +67,22 @@ def filter_valid_accessions( accessions: Sequence[str], raise_on_invalid: bool = False, ) -> list[str]: - """ - Filter a list of accessions to only include valid ones. - - Parameters - ---------- - accessions : Sequence[str] - List of experiment accessions to filter. - raise_on_invalid : bool, optional - If True, raise error on first invalid accession. - If False (default), silently skip invalid accessions. - - Returns - ------- - list[str] + """Filter a list of accessions to only include valid ones. + + Args: + accessions: + List of experiment accessions to filter. + + raise_on_invalid: + If True, raise error on first invalid accession. + If False (default), silently skip invalid accessions. + + Returns: List containing only valid accessions. - Raises - ------ - InvalidAccessionError - If raise_on_invalid is True and an invalid accession is found. + Raises: + InvalidAccessionError: + If raise_on_invalid is True and an invalid accession is found. """ valid = [] for acc in accessions: diff --git a/tests/test_download.py b/tests/test_download.py new file mode 100644 index 0000000..c658e16 --- /dev/null +++ b/tests/test_download.py @@ -0,0 +1,23 @@ +import pytest +import rds2py +from expressionatlas.download import _download_and_load_rds + +def test_download_and_load_r_files(tmp_path): + # Test rds loading + rds_path = tmp_path / "test.rds" + rds2py.write_rds({"value": [1, 2, 3]}, str(rds_path)) + + # Test loading via local file URL + file_url = rds_path.as_uri() + res = _download_and_load_rds(file_url, "dummy") + assert res.names is not None and "value" in list(res.names) + assert [list(x)[0] for x in res["value"]] == [1, 2, 3] + + # Test rda loading + rdata_path = tmp_path / "test.Rdata" + rds2py.write_rda({"value": [4, 5, 6]}, str(rdata_path)) + + file_url_rdata = rdata_path.as_uri() + res_rdata = _download_and_load_rds(file_url_rdata, "dummy") + assert res_rdata.names is not None and "value" in list(res_rdata.names) + assert [list(x)[0] for x in res_rdata["value"]] == [4, 5, 6] From 842a4eef5bd9ed13157955ea423bd5e522de1eb6 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 12 Aug 2026 06:38:36 +0000 Subject: [PATCH 07/16] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- src/expressionatlas/api.py | 16 +++++++++------- src/expressionatlas/client.py | 12 +++++++----- src/expressionatlas/download.py | 18 ++++++++++++------ tests/test_download.py | 4 ++-- 4 files changed, 30 insertions(+), 20 deletions(-) diff --git a/src/expressionatlas/api.py b/src/expressionatlas/api.py index 39daeda..cd3c6fe 100644 --- a/src/expressionatlas/api.py +++ b/src/expressionatlas/api.py @@ -96,13 +96,15 @@ def search( results = [] for hit in hits: - results.append(SearchResult( - accession=hit.get("accession"), - species=None, - experiment_type=None, - title=hit.get("title"), - connection_error=False, - )) + results.append( + SearchResult( + accession=hit.get("accession"), + species=None, + experiment_type=None, + title=hit.get("title"), + connection_error=False, + ) + ) return results diff --git a/src/expressionatlas/client.py b/src/expressionatlas/client.py index 3922b95..a92a4ef 100644 --- a/src/expressionatlas/client.py +++ b/src/expressionatlas/client.py @@ -43,10 +43,12 @@ class ExpressionAtlasClient: ... "E-MTAB-1624" ... ) >>> # Download multiple experiments - >>> exps = client.get_experiments([ - ... "E-MTAB-1624", - ... "E-MTAB-1625", - ... ]) + >>> exps = client.get_experiments( + ... [ + ... "E-MTAB-1624", + ... "E-MTAB-1625", + ... ] + ... ) """ def __init__(self, timeout: int = 30) -> None: @@ -147,7 +149,7 @@ def fetch_experiment_metadata(self, accession: str | Sequence[str]) -> BiocFrame accessions = [accession] else: accessions = list(accession) - + results = self.api.fetch_experiment_metadata(accessions) return search_results_to_biocframe(results) diff --git a/src/expressionatlas/download.py b/src/expressionatlas/download.py index 8811ffb..af81966 100644 --- a/src/expressionatlas/download.py +++ b/src/expressionatlas/download.py @@ -15,7 +15,6 @@ import logging import tempfile from pathlib import Path -from urllib.error import URLError from urllib.request import urlopen import numpy as np @@ -46,7 +45,9 @@ def has_tsv_files(accession: str) -> bool: try: with urlopen(f"{FTP_BASE_URL}/{accession}/", timeout=10) as response: content = response.read().decode("utf-8") - return any(x in content for x in ["-raw-counts.tsv", "-tpms.tsv", "-fpkms.tsv", "-normalized-expressions.tsv"]) + return any( + x in content for x in ["-raw-counts.tsv", "-tpms.tsv", "-fpkms.tsv", "-normalized-expressions.tsv"] + ) except Exception: return False @@ -205,11 +206,16 @@ def _download_tsv_fallback(accession: str) -> NamedList: design_df = _try_download_sdrf(f"{base_url}/{sdrf_file}") rnaseq_files = [] - for suffix, assay_name in [("-raw-counts.tsv", "counts"), ("-raw-counts.tsv.undecorated", "counts"), ("-tpms.tsv", "tpms"), ("-fpkms.tsv", "fpkms")]: + for suffix, assay_name in [ + ("-raw-counts.tsv", "counts"), + ("-raw-counts.tsv.undecorated", "counts"), + ("-tpms.tsv", "tpms"), + ("-fpkms.tsv", "fpkms"), + ]: for f in files: if f == f"{accession}{suffix}": rnaseq_files.append((f, assay_name)) - + if rnaseq_files: f, assay_name = rnaseq_files[0] try: @@ -222,9 +228,9 @@ def _download_tsv_fallback(accession: str) -> NamedList: microarray_files = [] for f in files: if f.startswith(f"{accession}_") and f.endswith("-normalized-expressions.tsv"): - design = f[len(accession)+1 :].split("-normalized-expressions")[0] + design = f[len(accession) + 1 :].split("-normalized-expressions")[0] microarray_files.append((f, design)) - + for f, design in microarray_files: try: df = _download_tsv(f"{base_url}/{f}") diff --git a/tests/test_download.py b/tests/test_download.py index c658e16..0c36f2d 100644 --- a/tests/test_download.py +++ b/tests/test_download.py @@ -6,7 +6,7 @@ def test_download_and_load_r_files(tmp_path): # Test rds loading rds_path = tmp_path / "test.rds" rds2py.write_rds({"value": [1, 2, 3]}, str(rds_path)) - + # Test loading via local file URL file_url = rds_path.as_uri() res = _download_and_load_rds(file_url, "dummy") @@ -16,7 +16,7 @@ def test_download_and_load_r_files(tmp_path): # Test rda loading rdata_path = tmp_path / "test.Rdata" rds2py.write_rda({"value": [4, 5, 6]}, str(rdata_path)) - + file_url_rdata = rdata_path.as_uri() res_rdata = _download_and_load_rds(file_url_rdata, "dummy") assert res_rdata.names is not None and "value" in list(res_rdata.names) From 22708b1c15dd15c9134f5921b08d1cb047357fc5 Mon Sep 17 00:00:00 2001 From: Jayaram Kancherla Date: Wed, 12 Aug 2026 00:07:44 -0700 Subject: [PATCH 08/16] support single-cell experiment accession numbers --- README.md | 3 - docs/index.md | 1 + docs/tutorial.md | 108 ++++++++++++++++++++++++++++++++ setup.cfg | 1 + src/expressionatlas/client.py | 7 +-- src/expressionatlas/download.py | 83 ++++++++++++++++++++---- tests/test_api.py | 11 +++- tests/test_integration.py | 27 ++++++++ 8 files changed, 220 insertions(+), 21 deletions(-) create mode 100644 docs/tutorial.md diff --git a/README.md b/README.md index 0138163..bdf848c 100644 --- a/README.md +++ b/README.md @@ -24,9 +24,6 @@ Expression Atlas is a comprehensive resource of gene and protein expression data - **Download**: Retrieve experiment data with automatic format handling - **Analyze**: Work with R-compatible data structures in Python -> [!WARNING] -> This package only supports downloading data from the bulk **Expression Atlas**. It does not support downloading data from the **Single Cell Expression Atlas**. Accessions for single-cell experiments (e.g., `E-MTAB-7041`) will fail to download. - ### Basic Usage ```python diff --git a/docs/index.md b/docs/index.md index f1c1144..3005551 100644 --- a/docs/index.md +++ b/docs/index.md @@ -20,6 +20,7 @@ Python client for searching and downloading gene expression datasets from EMBL-E :maxdepth: 2 Overview +Tutorial Contributions & Help License Authors diff --git a/docs/tutorial.md b/docs/tutorial.md new file mode 100644 index 0000000..c5f982d --- /dev/null +++ b/docs/tutorial.md @@ -0,0 +1,108 @@ +# Tutorial + +The `expressionatlas` package bridges the gap between Python and the [EMBL-EBI Expression Atlas](https://www.ebi.ac.uk/gxa), making it simple to search, download, and analyze curated gene expression datasets in Python. This client mirrors the [Bioconductor package](https://www.bioconductor.org/packages/release/data/experiment/html/ExpressionAtlas.html), and plugs right into the BiocPy ecosystem (`BiocFrame`, `SummarizedExperiment`, and `SingleCellExperiment`). + +--- + +## Getting Started + +First, make sure you have the package installed: + +```bash +pip install expressionatlas +``` + +Then, import the client: + +```python +from expressionatlas import ExpressionAtlasClient + +# Initialize the client. You can optionally set a custom timeout. +client = ExpressionAtlasClient(timeout=30) +``` + +## Searching for Datasets + +Expression Atlas hosts thousands of curated experiments. You can search for terms related to diseases, cell lines, developmental stages, and more. + +Let's say we're looking for breast cancer datasets in humans: + +```python +results = client.search_experiments( + properties=["breast", "cancer"], + species="homo sapiens" +) + +print(results) +``` + +This returns a `BiocFrame` containing all matches. + +If you want the complete metadata for your hits, you can fetch it on-demand: + +```python +# Grab the first 5 accessions from our search +accessions = results.get_column("Accession")[:5] + +# Fetch complete metadata for just these experiments +metadata = client.fetch_experiment_metadata(accessions) +print(metadata) +``` + +## Downloading Bulk Experiments + +Let's download `E-MTAB-1625` as an example. When you download a bulk experiment, it usually comes back as a `NamedList` containing `SummarizedExperiment` objects (since an accession might contain multiple array designs or assays). + +```python +exp = client.get_experiment("E-MTAB-1625") + +# For RNA-seq datasets, the data lives under the "rnaseq" key +rnaseq = exp["rnaseq"] +print(rnaseq) +``` + +This is a `SummarizedExperiment` object. You can access the count matrix, sample annotations, and gene annotations using standard accessors: + +```python +# The expression matrix (numpy array: genes x samples) +counts = rnaseq.assay("counts") + +# The sample annotations (BiocFrame) +sample_metadata = rnaseq.get_column_data() + +# The gene annotations (BiocFrame) +gene_metadata = rnaseq.get_row_data() +``` + +It works exactly the same for Microarray data, except the keys in the `NamedList` will correspond to the array design (e.g., `A-AFFY-126`), and the assay is usually called `"exprs"`. + +## Downloading Single-Cell Experiments + +If you pass an accession from the **Single Cell Expression Atlas**, the client automatically detects it, falls back to the single-cell FTP, and grabs the Matrix Market components. It returns a `SingleCellExperiment` object. + +```python +# Let's download a single-cell dataset +sc_exp = client.get_experiment("E-MTAB-6945") + +print(type(sc_exp)) +# + +print(sc_exp) +``` + +You can interact with `sc_exp` exactly like a bulk `SummarizedExperiment`. + +## Batch Downloads + +If you're doing meta-analysis across dozens of experiments, grabbing them one by one is tedious. Use `get_experiments` to download a whole batch at once: + +```python +# Download a batch of accessions +batch_results = client.get_experiments(["E-MTAB-1624", "E-MTAB-1625", "E-MTAB-6945"]) + +# Iterate through the downloaded objects +for accession, data in batch_results.items(): + print(f"Loaded {accession} successfully!") +``` + +And that's it! You're ready to start pulling down Expression Atlas data and throwing it straight into your Python pipelines. Happy analyzing! diff --git a/setup.cfg b/setup.cfg index cfda80e..fcae9e1 100644 --- a/setup.cfg +++ b/setup.cfg @@ -56,6 +56,7 @@ install_requires = singlecellexperiment biocutils rds2py + scipy [options.packages.find] diff --git a/src/expressionatlas/client.py b/src/expressionatlas/client.py index 3922b95..ce47e53 100644 --- a/src/expressionatlas/client.py +++ b/src/expressionatlas/client.py @@ -159,13 +159,12 @@ def get_experiment(self, accession: str) -> NamedList | None: Args: accession: ArrayExpress/BioStudies experiment accession (e.g., "E-MTAB-1624"). - Note: This client only supports bulk Expression Atlas experiments. - Single-cell experiment accessions (e.g., "E-MTAB-7041") are not supported. Returns: The downloaded experiment data, or None if download fails. - For RNA-seq: access via ["rnaseq"] to get SummarizedExperiment - For microarray: access via array design (e.g., ["A-AFFY-126"]) to get SummarizedExperiment + For RNA-seq (bulk): access via ["rnaseq"] to get SummarizedExperiment + For microarray (bulk): access via array design (e.g., ["A-AFFY-126"]) to get SummarizedExperiment + For Single-cell: returns a SingleCellExperiment object Raises: InvalidAccessionError: diff --git a/src/expressionatlas/download.py b/src/expressionatlas/download.py index 8811ffb..718d94d 100644 --- a/src/expressionatlas/download.py +++ b/src/expressionatlas/download.py @@ -19,8 +19,11 @@ from urllib.request import urlopen import numpy as np +import gzip +import scipy.io from biocframe import BiocFrame from biocutils import NamedList +from singlecellexperiment import SingleCellExperiment from summarizedexperiment import SummarizedExperiment from .exceptions import DownloadError @@ -30,6 +33,7 @@ # FTP base URL for Expression Atlas experiment data FTP_BASE_URL = "ftp://ftp.ebi.ac.uk/pub/databases/microarray/data/atlas/experiments" +FTP_SC_BASE_URL = "ftp://ftp.ebi.ac.uk/pub/databases/microarray/data/atlas/sc_experiments" def has_tsv_files(accession: str) -> bool: @@ -63,13 +67,12 @@ def get_atlas_experiment(experiment_accession: str) -> NamedList | None: Args: experiment_accession: - Valid ArrayExpress/BioStudies accession (e.g., "E-MTAB-1624"). - Note: This function only supports bulk Expression Atlas experiments. - Single-cell experiment accessions are not supported. + Valid ArrayExpress/BioStudies accession (e.g., "E-MTAB-1624" or "E-MTAB-6945"). Returns: - For RNA-seq: NamedList with key "rnaseq" containing SummarizedExperiment - For microarray: NamedList with array design accessions as keys, each containing SummarizedExperiment + For RNA-seq (bulk): NamedList with key "rnaseq" containing SummarizedExperiment + For microarray (bulk): NamedList with array design accessions as keys, each containing SummarizedExperiment + For Single-cell: SingleCellExperiment object Returns None if download fails. """ validate_accession(experiment_accession) @@ -94,14 +97,18 @@ def get_atlas_experiment(experiment_accession: str) -> NamedList | None: try: experiment_summary = _download_tsv_fallback(experiment_accession) except DownloadError: - if has_converter_available(): - logger.info("TSV not available, trying cloud converter service...") - experiment_summary = _download_via_converter( - f"{FTP_BASE_URL}/{experiment_accession}/{experiment_accession}-atlasExperimentSummary.Rdata", - experiment_accession, - ) - else: - raise + logger.info("Bulk RData/TSV not available, trying single cell endpoint...") + try: + experiment_summary = _download_sc_experiment(experiment_accession) + except DownloadError: + if has_converter_available(): + logger.info("TSV/SC not available, trying cloud converter service on RData...") + experiment_summary = _download_via_converter( + f"{FTP_BASE_URL}/{experiment_accession}/{experiment_accession}-atlasExperimentSummary.Rdata", + experiment_accession, + ) + else: + raise if experiment_summary: logger.info(f"Successfully downloaded experiment summary object for {experiment_accession}") @@ -410,5 +417,55 @@ def _download_via_converter(rdata_url: str, accession: str) -> NamedList: return result +def _download_sc_experiment(accession: str) -> SingleCellExperiment: + """Download and construct a SingleCellExperiment from SC Expression Atlas.""" + base_url = f"{FTP_SC_BASE_URL}/{accession}" + logger.info(f"Trying single cell FTP for {accession}: {base_url}/") + + try: + mtx_url = f"{base_url}/{accession}.aggregated_filtered_counts.mtx.gz" + logger.debug(f"Downloading mtx.gz: {mtx_url}") + with urlopen(mtx_url, timeout=60) as res: + mtx_data = res.read() + + logger.debug("Parsing mtx...") + matrix = scipy.io.mmread(io.BytesIO(gzip.decompress(mtx_data))) + + logger.debug("Downloading mtx rows and cols...") + with urlopen(f"{base_url}/{accession}.aggregated_filtered_counts.mtx_rows", timeout=30) as res: + rows = [line.split()[-1] for line in res.read().decode('utf-8').strip().split('\n')] + + with urlopen(f"{base_url}/{accession}.aggregated_filtered_counts.mtx_cols", timeout=30) as res: + cols = [line.strip() for line in res.read().decode('utf-8').strip().split('\n')] + + except Exception as e: + raise DownloadError(accession, f"Failed to download single cell MTX components: {e}") from e + + design_data = _try_download_sdrf(f"{base_url}/{accession}.condensed-sdrf.tsv") + col_data = {} + if design_data is not None and len(design_data) > 0: + all_attrs = set() + for s in cols: + if s in design_data: + all_attrs.update(design_data[s].keys()) + all_attrs = sorted(list(all_attrs)) + for attr in all_attrs: + col_data[attr] = [] + for s in cols: + val = design_data.get(s, {}).get(attr, None) + col_data[attr].append(val) + + row_bioc = BiocFrame({}, row_names=rows) + col_bioc = BiocFrame(col_data, row_names=cols) + metadata = {"accession": accession, "source": "sc_mtx"} + + return SingleCellExperiment( + assays={"counts": matrix}, + row_data=row_bioc, + column_data=col_bioc, + metadata=metadata, + ) + + download_experiment = get_atlas_experiment download_experiments = get_atlas_data diff --git a/tests/test_api.py b/tests/test_api.py index cdb4d08..193c253 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -54,6 +54,15 @@ def test_search_single_result(self) -> None: status=200, ) + api = BioStudiesAPI() + results = api.search(properties=["test"]) + + assert len(results) == 1 + assert results[0].accession == "E-MTAB-1624" + + @responses.activate + def test_fetch_experiment_metadata(self) -> None: + """Should fetch metadata for given accessions.""" # Mock study details endpoint responses.add( responses.GET, @@ -72,7 +81,7 @@ def test_search_single_result(self) -> None: ) api = BioStudiesAPI() - results = api.search(properties=["test"]) + results = api.fetch_experiment_metadata(["E-MTAB-1624"]) assert len(results) == 1 assert results[0].accession == "E-MTAB-1624" diff --git a/tests/test_integration.py b/tests/test_integration.py index 4d8cc60..1346c0a 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -47,3 +47,30 @@ def test_download_single_experiment(self) -> None: if exp is not None: # SimpleList is dict-like, check it has data assert len(exp) > 0, "Expected at least one dataset in result" + + def test_download_experiment_types(self) -> None: + """Download different experiment types to verify data structures.""" + client = ExpressionAtlasClient() + from biocutils import NamedList + from summarizedexperiment import SummarizedExperiment + from singlecellexperiment import SingleCellExperiment + + # 1. Bulk RNA-Seq + bulk_rnaseq = client.get_experiment("E-MTAB-1625") + if bulk_rnaseq is not None: + assert isinstance(bulk_rnaseq, NamedList) + assert list(bulk_rnaseq.names) == ["rnaseq"] + assert isinstance(bulk_rnaseq["rnaseq"], SummarizedExperiment) + + # 2. Bulk Microarray + bulk_microarray = client.get_experiment("E-GEOD-46817") + if bulk_microarray is not None: + assert isinstance(bulk_microarray, NamedList) + # Keys are typically array design names, let's just check the first one is a SummarizedExperiment + assert len(bulk_microarray) > 0 + assert isinstance(list(bulk_microarray.values())[0], SummarizedExperiment) + + # 3. Single Cell + sc_experiment = client.get_experiment("E-MTAB-6945") + if sc_experiment is not None: + assert isinstance(sc_experiment, SingleCellExperiment) From b9c7561a00e39f0379a857eafca0dbbd4844eb5d Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 12 Aug 2026 07:08:57 +0000 Subject: [PATCH 09/16] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- src/expressionatlas/download.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/expressionatlas/download.py b/src/expressionatlas/download.py index facd51d..7951c96 100644 --- a/src/expressionatlas/download.py +++ b/src/expressionatlas/download.py @@ -427,23 +427,23 @@ def _download_sc_experiment(accession: str) -> SingleCellExperiment: """Download and construct a SingleCellExperiment from SC Expression Atlas.""" base_url = f"{FTP_SC_BASE_URL}/{accession}" logger.info(f"Trying single cell FTP for {accession}: {base_url}/") - + try: mtx_url = f"{base_url}/{accession}.aggregated_filtered_counts.mtx.gz" logger.debug(f"Downloading mtx.gz: {mtx_url}") with urlopen(mtx_url, timeout=60) as res: mtx_data = res.read() - + logger.debug("Parsing mtx...") matrix = scipy.io.mmread(io.BytesIO(gzip.decompress(mtx_data))) - + logger.debug("Downloading mtx rows and cols...") with urlopen(f"{base_url}/{accession}.aggregated_filtered_counts.mtx_rows", timeout=30) as res: - rows = [line.split()[-1] for line in res.read().decode('utf-8').strip().split('\n')] - + rows = [line.split()[-1] for line in res.read().decode("utf-8").strip().split("\n")] + with urlopen(f"{base_url}/{accession}.aggregated_filtered_counts.mtx_cols", timeout=30) as res: - cols = [line.strip() for line in res.read().decode('utf-8').strip().split('\n')] - + cols = [line.strip() for line in res.read().decode("utf-8").strip().split("\n")] + except Exception as e: raise DownloadError(accession, f"Failed to download single cell MTX components: {e}") from e From ad3a4a9f38e6083969a3461268fbc2dccc18775c Mon Sep 17 00:00:00 2001 From: Jayaram Kancherla Date: Wed, 12 Aug 2026 00:26:28 -0700 Subject: [PATCH 10/16] use bfc to cache files --- .github/workflows/publish-pypi.yml | 8 ++ .github/workflows/run-tests.yml | 8 ++ README.md | 11 +- docs/tutorial.md | 6 +- setup.cfg | 1 + src/expressionatlas/client.py | 9 +- src/expressionatlas/download.py | 159 ++++++++++++++++++++--------- 7 files changed, 150 insertions(+), 52 deletions(-) diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index 405fee0..c2d2ff7 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -16,6 +16,14 @@ jobs: steps: - uses: actions/checkout@v4 + - name: Cache Expression Atlas data + uses: actions/cache@v4 + with: + path: ~/.cache/expressionatlas_bfc + key: ${{ runner.os }}-expressionatlas-bfc-${{ hashFiles('tests/**') }} + restore-keys: | + ${{ runner.os }}-expressionatlas-bfc- + - name: Set up Python 3.12 uses: actions/setup-python@v5 with: diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 01f4e9a..99f6670 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -38,6 +38,14 @@ jobs: steps: - uses: actions/checkout@v4 + - name: Cache Expression Atlas data + uses: actions/cache@v4 + with: + path: ~/.cache/expressionatlas_bfc + key: ${{ runner.os }}-expressionatlas-bfc-${{ hashFiles('tests/**') }} + restore-keys: | + ${{ runner.os }}-expressionatlas-bfc- + - uses: actions/setup-python@v5 id: setup-python with: diff --git a/README.md b/README.md index bdf848c..b9f3f8f 100644 --- a/README.md +++ b/README.md @@ -29,8 +29,8 @@ Expression Atlas is a comprehensive resource of gene and protein expression data ```python from expressionatlas import ExpressionAtlasClient -# Initialize client -client = ExpressionAtlasClient() +# Initialize client (optionally specify a custom cache directory) +client = ExpressionAtlasClient(cache_dir="~/.cache/my_custom_cache") # Search for experiments results = client.search_experiments( @@ -113,6 +113,13 @@ for acc, exp in experiments.items(): print(f"{acc}: {exp['rnaseq'].shape if 'rnaseq' in exp else 'microarray'}") ``` +### Caching Mechanism + +To optimize performance and reduce load on the FTP servers, all data downloads are automatically cached locally using `pyBiocFileCache`. + +- By default, the cache is stored at `~/.cache/expressionatlas_bfc`. +- You can customize this location when initializing the client by passing the `cache_dir` argument: `client = ExpressionAtlasClient(cache_dir="/path/to/custom/cache")`. + ### Direct RData / rda Support The client automatically downloads and parses both `.rds` and `.Rdata` / `.rda` files directly without relying on a cloud converter service: diff --git a/docs/tutorial.md b/docs/tutorial.md index c5f982d..5687926 100644 --- a/docs/tutorial.md +++ b/docs/tutorial.md @@ -17,8 +17,10 @@ Then, import the client: ```python from expressionatlas import ExpressionAtlasClient -# Initialize the client. You can optionally set a custom timeout. -client = ExpressionAtlasClient(timeout=30) +# Initialize the client. +# By default, files are cached in ~/.cache/expressionatlas_bfc. +# You can customize this directory by passing the cache_dir parameter: +client = ExpressionAtlasClient(timeout=30, cache_dir="/my/custom/cache/path") ``` ## Searching for Datasets diff --git a/setup.cfg b/setup.cfg index fcae9e1..c866482 100644 --- a/setup.cfg +++ b/setup.cfg @@ -57,6 +57,7 @@ install_requires = biocutils rds2py scipy + pyBiocFileCache [options.packages.find] diff --git a/src/expressionatlas/client.py b/src/expressionatlas/client.py index 0f71d42..560e6b7 100644 --- a/src/expressionatlas/client.py +++ b/src/expressionatlas/client.py @@ -4,6 +4,7 @@ import logging from collections.abc import Sequence +from pathlib import Path from biocframe import BiocFrame from biocutils import NamedList @@ -51,16 +52,22 @@ class ExpressionAtlasClient: ... ) """ - def __init__(self, timeout: int = 30) -> None: + def __init__(self, timeout: int = 30, cache_dir: str | Path | None = None) -> None: """Initialize Expression Atlas client. Args: timeout: Request timeout in seconds (default: 30). + cache_dir: + Custom path to store downloaded dataset files (default: ~/.cache/expressionatlas_bfc). """ self.timeout = timeout self._api: BioStudiesAPI | None = None + if cache_dir is not None: + from .download import set_cache_dir + set_cache_dir(cache_dir) + @property def api(self) -> BioStudiesAPI: """Lazy-loaded BioStudies API client.""" diff --git a/src/expressionatlas/download.py b/src/expressionatlas/download.py index facd51d..2b5db29 100644 --- a/src/expressionatlas/download.py +++ b/src/expressionatlas/download.py @@ -13,13 +13,17 @@ import csv import io import logging +import os import tempfile from pathlib import Path +from typing import Any from urllib.request import urlopen -import numpy as np import gzip +import numpy as np import scipy.io +from pybiocfilecache import BiocFileCache + from biocframe import BiocFrame from biocutils import NamedList from singlecellexperiment import SingleCellExperiment @@ -58,11 +62,73 @@ def has_tsv_files(accession: str) -> bool: def has_converter_available() -> bool: """Check if the cloud converter service is configured.""" - import os - return bool(os.environ.get("CONVERTER_URL", "")) +_BFC_INSTANCE: BiocFileCache | None = None + +def _get_cache() -> BiocFileCache: + """Get or create the BiocFileCache instance for Expression Atlas downloads.""" + global _BFC_INSTANCE + if _BFC_INSTANCE is None: + cache_dir = Path.home() / ".cache" / "expressionatlas_bfc" + cache_dir.mkdir(parents=True, exist_ok=True) + _BFC_INSTANCE = BiocFileCache(cache_dir) + return _BFC_INSTANCE + +def set_cache_dir(cache_dir: str | Path) -> None: + """Set the BiocFileCache directory globally. + + Args: + cache_dir: Path to the new cache directory. + """ + global _BFC_INSTANCE + cache_path = Path(cache_dir) + cache_path.mkdir(parents=True, exist_ok=True) + _BFC_INSTANCE = BiocFileCache(cache_path) + +def _get_filepath(bfc: BiocFileCache, resource: Any) -> str: + """Extract file path from BiocFileCache resource record.""" + if hasattr(resource, "rpath"): + rel_path = str(resource.rpath) + elif hasattr(resource, "get"): + rel_path = str(resource.get("rpath")) + else: + raise RuntimeError("Failed to resolve cache path.") + return str(Path(bfc.config.cache_dir) / rel_path) + +def _cached_download(url: str, key: str) -> str: + """Download a URL and store it in BiocFileCache, or return cached path.""" + if url.startswith("file://"): + from urllib.request import url2pathname + return url2pathname(url[7:]) + + bfc = _get_cache() + try: + existing = bfc.get(key) + if existing: + path = _get_filepath(bfc, existing) + if os.path.exists(path) and os.path.getsize(path) > 0: + logger.debug(f"Using cached file for {key}: {path}") + return path + except Exception: + pass + + logger.info(f"Downloading {url} to cache...") + resource = bfc.add(key, url, rtype="web", download=True) + path = _get_filepath(bfc, resource) + + if not os.path.exists(path) or os.path.getsize(path) == 0: + try: + bfc.remove(key) + except Exception: + pass + raise RuntimeError(f"Download failed for {url}") + + return path + + + def get_atlas_experiment(experiment_accession: str) -> NamedList | None: """Download and return the data representing a single Expression Atlas experiment. @@ -167,33 +233,27 @@ def _download_and_load_rds(url: str, accession: str) -> NamedList: elif parsed_url.lower().endswith(".rda"): suffix = ".rda" - with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp: - try: - with urlopen(url, timeout=120) as response: - tmp.write(response.read()) - except Exception as e: - raise DownloadError(accession, str(e)) from e - tmp_path = Path(tmp.name) - try: - try: - if suffix in [".rdata", ".rda"]: - data = rds2py.read_rda(str(tmp_path)) - else: - data = rds2py.read_rds(str(tmp_path)) - except Exception as e: - raise DownloadError(accession, f"Failed to parse {suffix} file: {e}") from e + path = _cached_download(url, url) + except Exception as e: + raise DownloadError(accession, str(e)) from e - result = NamedList() - if isinstance(data, dict): - for k, v in data.items(): - result[k] = v + try: + if suffix in [".rdata", ".rda"]: + data = rds2py.read_rda(path) else: - result["data"] = data + data = rds2py.read_rds(path) + except Exception as e: + raise DownloadError(accession, f"Failed to parse {suffix} file: {e}") from e + + result = NamedList() + if isinstance(data, dict): + for k, v in data.items(): + result[k] = v + else: + result["data"] = data - return result - finally: - tmp_path.unlink() + return result def _download_tsv_fallback(accession: str) -> NamedList: @@ -254,27 +314,28 @@ def _download_tsv_fallback(accession: str) -> NamedList: def _download_tsv(url: str) -> dict[str, list[str]]: """Download and parse a TSV file from URL into a column-oriented dictionary.""" - logger.debug(f"Downloading: {url}") - with urlopen(url, timeout=60) as response: - content = response.read().decode("utf-8") - - reader = csv.reader(io.StringIO(content), delimiter="\t") - header = next(reader) - data = {h: [] for h in header} + path = _cached_download(url, url) + logger.debug(f"Reading: {path}") + + with open(path, "r", encoding="utf-8") as f: + reader = csv.reader(f, delimiter="\t") + header = next(reader) + data = {h: [] for h in header} - for row in reader: - for i, h in enumerate(header): - val = row[i] if i < len(row) else None - data[h].append(val) + for row in reader: + for i, h in enumerate(header): + val = row[i] if i < len(row) else None + data[h].append(val) return data def _try_download_sdrf(url: str) -> dict[str, dict[str, str]] | None: try: - logger.debug(f"Downloading sample annotations: {url}") - with urlopen(url, timeout=60) as response: - content = response.read().decode("utf-8") + path = _cached_download(url, url) + logger.debug(f"Reading sample annotations: {path}") + with open(path, "r", encoding="utf-8") as f: + content = f.read() lines = content.strip().split("\n") if not lines: @@ -431,18 +492,22 @@ def _download_sc_experiment(accession: str) -> SingleCellExperiment: try: mtx_url = f"{base_url}/{accession}.aggregated_filtered_counts.mtx.gz" logger.debug(f"Downloading mtx.gz: {mtx_url}") - with urlopen(mtx_url, timeout=60) as res: - mtx_data = res.read() + mtx_path = _cached_download(mtx_url, mtx_url) logger.debug("Parsing mtx...") - matrix = scipy.io.mmread(io.BytesIO(gzip.decompress(mtx_data))) + with open(mtx_path, "rb") as f: + matrix = scipy.io.mmread(io.BytesIO(gzip.decompress(f.read()))) logger.debug("Downloading mtx rows and cols...") - with urlopen(f"{base_url}/{accession}.aggregated_filtered_counts.mtx_rows", timeout=30) as res: - rows = [line.split()[-1] for line in res.read().decode('utf-8').strip().split('\n')] + rows_url = f"{base_url}/{accession}.aggregated_filtered_counts.mtx_rows" + rows_path = _cached_download(rows_url, rows_url) + with open(rows_path, "r", encoding="utf-8") as f: + rows = [line.split()[-1] for line in f.read().strip().split('\n')] - with urlopen(f"{base_url}/{accession}.aggregated_filtered_counts.mtx_cols", timeout=30) as res: - cols = [line.strip() for line in res.read().decode('utf-8').strip().split('\n')] + cols_url = f"{base_url}/{accession}.aggregated_filtered_counts.mtx_cols" + cols_path = _cached_download(cols_url, cols_url) + with open(cols_path, "r", encoding="utf-8") as f: + cols = [line.strip() for line in f.read().strip().split('\n')] except Exception as e: raise DownloadError(accession, f"Failed to download single cell MTX components: {e}") from e From 47f74712b96dc804e46bcc4a634097d99ff37140 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 12 Aug 2026 07:27:57 +0000 Subject: [PATCH 11/16] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- README.md | 2 +- src/expressionatlas/client.py | 1 + src/expressionatlas/download.py | 27 +++++++++++++++------------ 3 files changed, 17 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index b9f3f8f..f105a0a 100644 --- a/README.md +++ b/README.md @@ -115,7 +115,7 @@ for acc, exp in experiments.items(): ### Caching Mechanism -To optimize performance and reduce load on the FTP servers, all data downloads are automatically cached locally using `pyBiocFileCache`. +To optimize performance and reduce load on the FTP servers, all data downloads are automatically cached locally using `pyBiocFileCache`. - By default, the cache is stored at `~/.cache/expressionatlas_bfc`. - You can customize this location when initializing the client by passing the `cache_dir` argument: `client = ExpressionAtlasClient(cache_dir="/path/to/custom/cache")`. diff --git a/src/expressionatlas/client.py b/src/expressionatlas/client.py index 560e6b7..e1a767d 100644 --- a/src/expressionatlas/client.py +++ b/src/expressionatlas/client.py @@ -66,6 +66,7 @@ def __init__(self, timeout: int = 30, cache_dir: str | Path | None = None) -> No if cache_dir is not None: from .download import set_cache_dir + set_cache_dir(cache_dir) @property diff --git a/src/expressionatlas/download.py b/src/expressionatlas/download.py index 6dce395..98810ea 100644 --- a/src/expressionatlas/download.py +++ b/src/expressionatlas/download.py @@ -14,7 +14,6 @@ import io import logging import os -import tempfile from pathlib import Path from typing import Any from urllib.request import urlopen @@ -67,6 +66,7 @@ def has_converter_available() -> bool: _BFC_INSTANCE: BiocFileCache | None = None + def _get_cache() -> BiocFileCache: """Get or create the BiocFileCache instance for Expression Atlas downloads.""" global _BFC_INSTANCE @@ -76,9 +76,10 @@ def _get_cache() -> BiocFileCache: _BFC_INSTANCE = BiocFileCache(cache_dir) return _BFC_INSTANCE + def set_cache_dir(cache_dir: str | Path) -> None: """Set the BiocFileCache directory globally. - + Args: cache_dir: Path to the new cache directory. """ @@ -87,6 +88,7 @@ def set_cache_dir(cache_dir: str | Path) -> None: cache_path.mkdir(parents=True, exist_ok=True) _BFC_INSTANCE = BiocFileCache(cache_path) + def _get_filepath(bfc: BiocFileCache, resource: Any) -> str: """Extract file path from BiocFileCache resource record.""" if hasattr(resource, "rpath"): @@ -97,10 +99,12 @@ def _get_filepath(bfc: BiocFileCache, resource: Any) -> str: raise RuntimeError("Failed to resolve cache path.") return str(Path(bfc.config.cache_dir) / rel_path) + def _cached_download(url: str, key: str) -> str: """Download a URL and store it in BiocFileCache, or return cached path.""" if url.startswith("file://"): from urllib.request import url2pathname + return url2pathname(url[7:]) bfc = _get_cache() @@ -117,16 +121,15 @@ def _cached_download(url: str, key: str) -> str: logger.info(f"Downloading {url} to cache...") resource = bfc.add(key, url, rtype="web", download=True) path = _get_filepath(bfc, resource) - + if not os.path.exists(path) or os.path.getsize(path) == 0: try: bfc.remove(key) except Exception: pass raise RuntimeError(f"Download failed for {url}") - - return path + return path def get_atlas_experiment(experiment_accession: str) -> NamedList | None: @@ -316,7 +319,7 @@ def _download_tsv(url: str) -> dict[str, list[str]]: """Download and parse a TSV file from URL into a column-oriented dictionary.""" path = _cached_download(url, url) logger.debug(f"Reading: {path}") - + with open(path, "r", encoding="utf-8") as f: reader = csv.reader(f, delimiter="\t") header = next(reader) @@ -493,22 +496,22 @@ def _download_sc_experiment(accession: str) -> SingleCellExperiment: mtx_url = f"{base_url}/{accession}.aggregated_filtered_counts.mtx.gz" logger.debug(f"Downloading mtx.gz: {mtx_url}") mtx_path = _cached_download(mtx_url, mtx_url) - + logger.debug("Parsing mtx...") with open(mtx_path, "rb") as f: matrix = scipy.io.mmread(io.BytesIO(gzip.decompress(f.read()))) - + logger.debug("Downloading mtx rows and cols...") rows_url = f"{base_url}/{accession}.aggregated_filtered_counts.mtx_rows" rows_path = _cached_download(rows_url, rows_url) with open(rows_path, "r", encoding="utf-8") as f: - rows = [line.split()[-1] for line in f.read().strip().split('\n')] - + rows = [line.split()[-1] for line in f.read().strip().split("\n")] + cols_url = f"{base_url}/{accession}.aggregated_filtered_counts.mtx_cols" cols_path = _cached_download(cols_url, cols_url) with open(cols_path, "r", encoding="utf-8") as f: - cols = [line.strip() for line in f.read().strip().split('\n')] - + cols = [line.strip() for line in f.read().strip().split("\n")] + except Exception as e: raise DownloadError(accession, f"Failed to download single cell MTX components: {e}") from e From b0d7d57e8733e69ca5463962cbdcc62f101c2db4 Mon Sep 17 00:00:00 2001 From: Jayaram Kancherla Date: Wed, 12 Aug 2026 00:31:46 -0700 Subject: [PATCH 12/16] update ruff config --- .pre-commit-config.yaml | 31 +++++++++++++++++++++++++++---- pyproject.toml | 12 +++++++----- setup.cfg | 2 +- 3 files changed, 35 insertions(+), 10 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a832683..863ce2d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,7 +2,7 @@ exclude: '^docs/conf.py' repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v5.0.0 + rev: v6.0.0 hooks: - id: trailing-whitespace - id: check-added-large-files @@ -17,14 +17,37 @@ repos: - id: mixed-line-ending args: ['--fix=auto'] # replace 'auto' with 'lf' to enforce Linux/Mac line endings or 'crlf' for Windows +# - repo: https://github.com/PyCQA/docformatter +# rev: master +# hooks: +# - id: docformatter +# additional_dependencies: [tomli] +# args: [--in-place, --wrap-descriptions=120, --wrap-summaries=120] +# # --config, ./pyproject.toml + +# - repo: https://github.com/psf/black +# rev: 24.8.0 +# hooks: +# - id: black +# language_version: python3 + - repo: https://github.com/astral-sh/ruff-pre-commit # Ruff version. - rev: v0.8.2 + rev: v0.16.2 hooks: - - id: ruff - args: [--fix, --exit-non-zero-on-fix] + # Run the linter. + - id: ruff-check + args: [--fix, --exit-zero] + # Run the formatter. - id: ruff-format +## If like to embrace black styles even in the docs: +# - repo: https://github.com/asottile/blacken-docs +# rev: v1.13.0 +# hooks: +# - id: blacken-docs +# additional_dependencies: [black] + ## Check for misspells in documentation files: # - repo: https://github.com/codespell-project/codespell # rev: v2.2.5 diff --git a/pyproject.toml b/pyproject.toml index 086f90c..2d3e09b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,15 +11,17 @@ version_scheme = "no-guess-dev" [tool.ruff] line-length = 120 src = ["src"] -exclude = ["tests"] -lint.extend-ignore = ["F821"] +exclude = ["tests", "docs"] + +[tool.ruff.lint] +extend-ignore = ["F821"] [tool.ruff.lint.pydocstyle] convention = "google" +[tool.ruff.lint.per-file-ignores] +"__init__.py" = ["E402", "F401"] + [tool.ruff.format] docstring-code-format = true docstring-code-line-length = 20 - -[tool.ruff.lint.per-file-ignores] -"__init__.py" = ["E402", "F401"] diff --git a/setup.cfg b/setup.cfg index c866482..af78907 100644 --- a/setup.cfg +++ b/setup.cfg @@ -5,7 +5,7 @@ [metadata] name = expressionatlas -description = Python client for searching and downloading gene expression datasets from EMBL-EBI Expression Atlas +description = Python client for searching and downloading datasets from EMBL-EBI Expression Atlas author = Jayaram Kancherla author_email = jayaram.kancherla@gmail.com license = MIT From 50f89751707b9d41e2c22fb338a485fa72d13b59 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 12 Aug 2026 07:33:08 +0000 Subject: [PATCH 13/16] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- setup.py | 2 +- src/expressionatlas/api.py | 2 +- src/expressionatlas/download.py | 5 ++--- src/expressionatlas/exceptions.py | 2 -- 4 files changed, 4 insertions(+), 7 deletions(-) diff --git a/setup.py b/setup.py index 6f43bf0..d7db81e 100644 --- a/setup.py +++ b/setup.py @@ -12,7 +12,7 @@ if __name__ == "__main__": try: setup(use_scm_version={"version_scheme": "no-guess-dev"}) - except: # noqa + except: print( "\n\nAn error occurred while building the project, " "please ensure you have the most updated version of setuptools, " diff --git a/src/expressionatlas/api.py b/src/expressionatlas/api.py index cd3c6fe..74538b8 100644 --- a/src/expressionatlas/api.py +++ b/src/expressionatlas/api.py @@ -221,5 +221,5 @@ def close(self) -> None: def __enter__(self) -> BioStudiesAPI: return self - def __exit__(self, *args: Any) -> None: + def __exit__(self, *args: object) -> None: self.close() diff --git a/src/expressionatlas/download.py b/src/expressionatlas/download.py index 98810ea..9cd9155 100644 --- a/src/expressionatlas/download.py +++ b/src/expressionatlas/download.py @@ -11,6 +11,7 @@ from __future__ import annotations import csv +import gzip import io import logging import os @@ -18,13 +19,11 @@ from typing import Any from urllib.request import urlopen -import gzip import numpy as np import scipy.io -from pybiocfilecache import BiocFileCache - from biocframe import BiocFrame from biocutils import NamedList +from pybiocfilecache import BiocFileCache from singlecellexperiment import SingleCellExperiment from summarizedexperiment import SummarizedExperiment diff --git a/src/expressionatlas/exceptions.py b/src/expressionatlas/exceptions.py index 79eac05..0e0f67f 100644 --- a/src/expressionatlas/exceptions.py +++ b/src/expressionatlas/exceptions.py @@ -6,8 +6,6 @@ class ExpressionAtlasError(Exception): """Base exception for Expression Atlas errors.""" - pass - class InvalidAccessionError(ExpressionAtlasError): """Raised when an experiment accession is invalid.""" From 14cbb53ecb2320904dd35f689c74aaf467e53315 Mon Sep 17 00:00:00 2001 From: Jayaram Kancherla Date: Wed, 12 Aug 2026 01:02:30 -0700 Subject: [PATCH 14/16] rename package to pyexpressionatlas --- .coveragerc | 2 +- .github/workflows/publish-pypi.yml | 6 +- .github/workflows/run-tests.yml | 6 +- CHANGELOG.md | 7 +- CONTRIBUTING.md | 26 +- LICENSE.txt | 696 +----------------- README.md | 12 +- docs/conf.py | 10 +- docs/index.md | 2 +- docs/tutorial.md | 8 +- setup.cfg | 18 +- setup.py | 10 +- .../__init__.py | 2 +- .../api.py | 0 .../client.py | 0 .../download.py | 4 +- .../exceptions.py | 0 .../models.py | 0 .../validation.py | 0 tests/conftest.py | 2 +- tests/test_api.py | 4 +- tests/test_download.py | 2 +- tests/test_integration.py | 4 +- tests/test_models.py | 2 +- tests/test_validation.py | 4 +- 25 files changed, 86 insertions(+), 741 deletions(-) rename src/{expressionatlas => pyexpressionatlas}/__init__.py (95%) rename src/{expressionatlas => pyexpressionatlas}/api.py (100%) rename src/{expressionatlas => pyexpressionatlas}/client.py (100%) rename src/{expressionatlas => pyexpressionatlas}/download.py (99%) rename src/{expressionatlas => pyexpressionatlas}/exceptions.py (100%) rename src/{expressionatlas => pyexpressionatlas}/models.py (100%) rename src/{expressionatlas => pyexpressionatlas}/validation.py (100%) diff --git a/.coveragerc b/.coveragerc index 8a6c99a..122f459 100644 --- a/.coveragerc +++ b/.coveragerc @@ -1,7 +1,7 @@ # .coveragerc to control coverage.py [run] branch = True -source = expressionatlas +source = pyexpressionatlas # omit = bad_file.py [paths] diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index c2d2ff7..539b4ca 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -19,10 +19,10 @@ jobs: - name: Cache Expression Atlas data uses: actions/cache@v4 with: - path: ~/.cache/expressionatlas_bfc - key: ${{ runner.os }}-expressionatlas-bfc-${{ hashFiles('tests/**') }} + path: ~/.cache/pyexpressionatlas_bfc + key: ${{ runner.os }}-pyexpressionatlas-bfc-${{ hashFiles('tests/**') }} restore-keys: | - ${{ runner.os }}-expressionatlas-bfc- + ${{ runner.os }}-pyexpressionatlas-bfc- - name: Set up Python 3.12 uses: actions/setup-python@v5 diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 99f6670..ebb5167 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -41,10 +41,10 @@ jobs: - name: Cache Expression Atlas data uses: actions/cache@v4 with: - path: ~/.cache/expressionatlas_bfc - key: ${{ runner.os }}-expressionatlas-bfc-${{ hashFiles('tests/**') }} + path: ~/.cache/pyexpressionatlas_bfc + key: ${{ runner.os }}-pyexpressionatlas-bfc-${{ hashFiles('tests/**') }} restore-keys: | - ${{ runner.os }}-expressionatlas-bfc- + ${{ runner.os }}-pyexpressionatlas-bfc- - uses: actions/setup-python@v5 id: setup-python diff --git a/CHANGELOG.md b/CHANGELOG.md index 205cc5e..0072608 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,6 @@ # Changelog -## Version 0.1 (development) +## Version 0.0.1 -- Feature A added -- FIX: nasty bug #1729 fixed -- add your changes here! +- Initial version of the package to support access to datasets from expression atlas. +- Uses `rd2py` to read RDS files and supports bulk RNA-seq, and single-cell RNA-seq datasets. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index af34fa8..393b876 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,7 +27,7 @@ # Contributing -Welcome to `expressionatlas` contributor's guide. +Welcome to `pyexpressionatlas` contributor's guide. This document focuses on getting any potential contributor familiarized with the development processes, but [other kinds of contributions] are also appreciated. @@ -43,7 +43,7 @@ behavior guidelines. ## Issue Reports -If you experience bugs or general issues with `expressionatlas`, please have a look +If you experience bugs or general issues with `pyexpressionatlas`, please have a look on the [issue tracker]. If you don't see anything useful there, please feel free to fire an issue report. @@ -61,10 +61,10 @@ you help us to identify the root cause of the issue. ## Documentation Improvements -You can help improve `expressionatlas` docs by making them more readable and coherent, or +You can help improve `pyexpressionatlas` docs by making them more readable and coherent, or by adding missing information and correcting mistakes. -`expressionatlas` documentation uses [Sphinx] as its main documentation compiler. +`pyexpressionatlas` documentation uses [Sphinx] as its main documentation compiler. This means that the docs are kept in the same repository as the project code, and that any documentation update is done in the same way was a code contribution. @@ -77,7 +77,7 @@ that any documentation update is done in the same way was a code contribution. :::{tip} Please notice that the [GitHub web interface] provides a quick way of - propose changes in `expressionatlas`'s files. While this mechanism can + propose changes in `pyexpressionatlas`'s files. While this mechanism can be tricky for normal code contributions, it works perfectly fine for contributing to the docs, and can be quite handy. @@ -134,8 +134,8 @@ source /bin/activate or [Miniconda]: ``` -conda create -n expressionatlas python=3 six virtualenv pytest pytest-cov -conda activate expressionatlas +conda create -n pyexpressionatlas python=3 six virtualenv pytest pytest-cov +conda activate pyexpressionatlas ``` ### Clone the repository @@ -148,8 +148,8 @@ conda activate expressionatlas 3. Clone this copy to your local disk: ``` - git clone git@github.com:YourLogin/expressionatlas.git - cd expressionatlas + git clone git@github.com:YourLogin/pyexpressionatlas.git + cd pyexpressionatlas ``` 4. You should run: @@ -170,7 +170,7 @@ conda activate expressionatlas pre-commit install ``` - `expressionatlas` comes with a lot of hooks configured to automatically help the + `pyexpressionatlas` comes with a lot of hooks configured to automatically help the developer to check the code being written. ### Implement your changes @@ -314,7 +314,7 @@ package: If you are part of the group of maintainers and have correct user permissions on [PyPI], the following steps can be used to release a new version for -`expressionatlas`: +`pyexpressionatlas`: 1. Make sure all unit tests are successful. 2. Tag the current commit on the main branch with a release tag, e.g., `v1.2.3`. @@ -367,5 +367,5 @@ on [PyPI], the following steps can be used to release a new version for ```{todo} Please review and change the following definitions: ``` -[repository]: https://github.com//expressionatlas -[issue tracker]: https://github.com//expressionatlas/issues +[repository]: https://github.com//pyexpressionatlas +[issue tracker]: https://github.com//pyexpressionatlas/issues diff --git a/LICENSE.txt b/LICENSE.txt index fecf79f..f4b2bef 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,675 +1,21 @@ -GNU GENERAL PUBLIC LICENSE -Version 3, 29 June 2007 - -Copyright (C) 2007 Free Software Foundation, Inc. -Everyone is permitted to copy and distribute verbatim copies -of this license document, but changing it is not allowed. - - Preamble - -The GNU General Public License is a free, copyleft license for -software and other kinds of works. - -The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - -When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - -To protect your rights, we need to prevent others from denying you these -rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - -For example, if you distribute copies of such a program, whether gratis -or for a fee, you must pass on to the recipients the same freedoms that -you received. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - -Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - -For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - -Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - -Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - -The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - -0. Definitions. - -"This License" refers to version 3 of the GNU General Public License. - -"Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - -"The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - -To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - -A "covered work" means either the unmodified Program or a work based -on the Program. - -To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - -To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - -An interactive user interface displays "Appropriate Legal Notices" to -the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If the -interface presents a list of user commands or options, such as a menu, -a prominent item in the list meets this criterion. - -1. Source Code. - -The "source code" for a work means the preferred form of the work for -making modifications to it. "Object code" means any non-source form of -a work. - -A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that is -widely used among developers working in that language. - -The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that Major -Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system (if -any) on which the executable work runs, or a compiler used to produce -the work, or an object code interpreter used to run it. - -The "Corresponding Source" for a work in object code form means all the -source code needed to generate, install, and (for an executable work) -run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - -The Corresponding Source need not include anything that users can -regenerate automatically from other parts of the Corresponding Source. - -The Corresponding Source for a work in source code form is that same -work. - -2. Basic Permissions. - -All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - -You may make, run and propagate covered works that you do not convey, -without conditions so long as your license otherwise remains in force. -You may convey covered works to others for the sole purpose of having -them make modifications exclusively for you, or provide you with -facilities for running those works, provided that you comply with the -terms of this License in conveying all material for which you do not -control copyright. Those thus making or running the covered works for -you must do so exclusively on your behalf, under your direction and -control, on terms that prohibit them from making any copies of your -copyrighted material outside their relationship with you. - -Conveying under any other circumstances is permitted solely under the -conditions stated below. Sublicensing is not allowed; section 10 makes -it unnecessary. - -3. Protecting Users' Legal Rights From Anti-Circumvention Law. - -No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or similar -laws prohibiting or restricting circumvention of such measures. - -When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such -circumvention is effected by exercising rights under this License with -respect to the covered work, and you disclaim any intention to limit -operation or modification of the work as a means of enforcing, against -the work's users, your or third parties' legal rights to forbid -circumvention of technological measures. - -4. Conveying Verbatim Copies. - -You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - -You may charge any price or no price for each copy that you convey, and -you may offer support or warranty protection for a fee. - -5. Conveying Modified Source Versions. - -You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under - section 7. This requirement modifies the requirement in section 4 - to "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - -A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - -6. Conveying Non-Source Forms. - -You may convey a covered work in object code form under the terms of -sections 4 and 5, provided that you also convey the machine-readable -Corresponding Source under the terms of this License, in one of these -ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the Corresponding - Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - -A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - -A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, -family, or household purposes, or (2) anything designed or sold for -incorporation into a dwelling. In determining whether a product is a -consumer product, doubtful cases shall be resolved in favor of -coverage. For a particular product received by a particular user, -"normally used" refers to a typical or common use of that class of -product, regardless of the status of the particular user or of the way -in which the particular user actually uses, or expects or is expected -to use, the product. A product is a consumer product regardless of -whether the product has substantial commercial, industrial or -non-consumer uses, unless such uses represent the only significant mode -of use of the product. - -"Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to -install and execute modified versions of a covered work in that User -Product from a modified version of its Corresponding Source. The -information must suffice to ensure that the continued functioning of -the modified object code is in no case prevented or interfered with -solely because modification has been made. - -If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply if -neither you nor any third party retains the ability to install modified -object code on the User Product (for example, the work has been -installed in ROM). - -The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or -updates for a work that has been modified or installed by the -recipient, or for the User Product in which it has been modified or -installed. Access to a network may be denied when the modification -itself materially and adversely affects the operation of the network or -violates the rules and protocols for communication across the network. - -Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - -7. Additional Terms. - -"Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - -When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - -Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders -of that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - -All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains a -further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - -If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - -Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; the -above requirements apply either way. - -8. Termination. - -You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - -However, if you cease all violation of this License, then your license -from a particular copyright holder is reinstated (a) provisionally, -unless and until the copyright holder explicitly and finally -terminates your license, and (b) permanently, if the copyright holder -fails to notify you of the violation by some reasonable means prior to -60 days after the cessation. - -Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - -Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - -9. Acceptance Not Required for Having Copies. - -You are not required to accept this License in order to receive or run -a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do not -accept this License. Therefore, by modifying or propagating a covered -work, you indicate your acceptance of this License to do so. - -10. Automatic Licensing of Downstream Recipients. - -Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - -An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - -You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may not -impose a license fee, royalty, or other charge for exercise of rights -granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - -11. Patents. - -A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - -A contributor's "essential patent claims" are all patent claims owned -or controlled by the contributor, whether already acquired or hereafter -acquired, that would be infringed by some manner, permitted by this -License, of making, using, or selling its contributor version, but do -not include claims that would be infringed only as a consequence of -further modification of the contributor version. For purposes of this -definition, "control" includes the right to grant patent sublicenses in -a manner consistent with the requirements of this License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to make, -use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - -In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - -If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone to -copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - -A patent license is "discriminatory" if it does not include within the -scope of its coverage, prohibits the exercise of, or is conditioned on -the non-exercise of one or more of the rights that are specifically -granted under this License. You may not convey a covered work if you -are a party to an arrangement with a third party that is in the -business of distributing software, under which you make payment to the -third party based on the extent of your activity of conveying the work, -and under which the third party grants, to any of the parties who would -receive the covered work from you, a discriminatory patent license (a) -in connection with copies of the covered work conveyed by you (or copies -made from those copies), or (b) primarily for and in connection with -specific products or compilations that contain the covered work, unless -you entered into that arrangement, or that patent license was granted, -prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting any -implied license or other defenses to infringement that may otherwise be -available to you under applicable patent law. - -12. No Surrender of Others' Freedom. - -If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under -this License and any other pertinent obligations, then as a -consequence you may not convey it at all. For example, if you agree to -terms that obligate you to collect a royalty for further conveying from -those to whom you convey the Program, the only way you could satisfy -both those terms and this License would be to refrain entirely from -conveying the Program. - -13. Use with the GNU Affero General Public License. - -Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - -14. Revised Versions of this License. - -The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies that a certain numbered version of the GNU General Public -License "or any later version" applies to it, you have the option of -following the terms and conditions either of that numbered version or -of any later version published by the Free Software Foundation. If the -Program does not specify a version number of the GNU General Public -License, you may choose any version ever published by the Free Software -Foundation. - -If the Program specifies that a proxy can decide which future versions -of the GNU General Public License can be used, that proxy's public -statement of acceptance of a version permanently authorizes you to -choose that version for the Program. - -Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - -15. Disclaimer of Warranty. - -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT -WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE -OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU -ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -16. Limitation of Liability. - -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR -CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES -ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT -NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR -LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO -OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY -HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -17. Interpretation of Sections 15 and 16. - -If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - -If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these -terms. - -To do so, attach the following notices to the program. It is safest to -attach them to the start of each source file to most effectively state -the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - -If the program does terminal interaction, make it output a short notice -like this when it starts in an interactive mode: - - Expression Atlas Python Client Copyright (C) 2026 Expression Atlas Team - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the -appropriate parts of the General Public License. Of course, your -program's commands might be different; for a GUI interface, you would -use an "about box". - -You should also get your employer (if you work as a programmer) or -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. For more information on this, and how to apply and follow -the GNU GPL, see . - -The GNU General Public License does not permit incorporating your -program into proprietary programs. If your program is a subroutine -library, you may consider it more useful to permit linking proprietary -applications with the library. If this is what you want to do, use the -GNU Lesser General Public License instead of this License. But first, -please read . +The MIT License (MIT) + +Copyright (c) 2026 Jayaram Kancherla + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index f105a0a..9dc249e 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ -[![PyPI-Server](https://img.shields.io/pypi/v/expressionatlas.svg)](https://pypi.org/project/expressionatlas/) -![Unit tests](https://github.com/biocpy/expressionatlas/actions/workflows/run-tests.yml/badge.svg) +[![PyPI-Server](https://img.shields.io/pypi/v/pyexpressionatlas.svg)](https://pypi.org/project/pyexpressionatlas/) +![Unit tests](https://github.com/biocpy/pyexpressionatlas/actions/workflows/run-tests.yml/badge.svg) -# expressionatlas +# pyexpressionatlas A Python client for searching and downloading gene expression datasets from [EMBL-EBI Expression Atlas](https://www.ebi.ac.uk/gxa), providing full compatibility with the [R Bioconductor package](https://bioconductor.org/packages/ExpressionAtlas/). @@ -10,10 +10,10 @@ A Python client for searching and downloading gene expression datasets from [EMB ## Install -To get started, install the package from [PyPI](https://pypi.org/project/expressionatlas/) +To get started, install the package from [PyPI](https://pypi.org/project/pyexpressionatlas/) ```bash -pip install expressionatlas +pip install pyexpressionatlas ``` ## Get Started @@ -27,7 +27,7 @@ Expression Atlas is a comprehensive resource of gene and protein expression data ### Basic Usage ```python -from expressionatlas import ExpressionAtlasClient +from pyexpressionatlas import ExpressionAtlasClient # Initialize client (optionally specify a custom cache directory) client = ExpressionAtlasClient(cache_dir="~/.cache/my_custom_cache") diff --git a/docs/conf.py b/docs/conf.py index 2b55d97..684ad2f 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -34,7 +34,7 @@ from sphinx import apidoc output_dir = os.path.join(__location__, "api") -module_dir = os.path.join(__location__, "../src/expressionatlas") +module_dir = os.path.join(__location__, "../src/pyexpressionatlas") try: shutil.rmtree(output_dir) except FileNotFoundError: @@ -105,7 +105,7 @@ master_doc = "index" # General information about the project. -project = "expressionatlas" +project = "pyexpressionatlas" copyright = "2026, Jayaram Kancherla" # The version info for the project you're documenting, acts as replacement for @@ -117,7 +117,7 @@ # If you don’t need the separation provided between version and release, # just set them both to the same value. try: - from expressionatlas import __version__ as version + from pyexpressionatlas import __version__ as version except ImportError: version = "" @@ -247,7 +247,7 @@ # html_file_suffix = None # Output file base name for HTML help builder. -htmlhelp_basename = "expressionatlas-doc" +htmlhelp_basename = "pyexpressionatlas-doc" # -- Options for LaTeX output ------------------------------------------------ @@ -264,7 +264,7 @@ # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ - ("index", "user_guide.tex", "expressionatlas Documentation", "Jayaram Kancherla", "manual") + ("index", "user_guide.tex", "pyexpressionatlas Documentation", "Jayaram Kancherla", "manual") ] # The name of an image file (relative to this directory) to place at the top of diff --git a/docs/index.md b/docs/index.md index 3005551..5133f06 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,4 +1,4 @@ -# expressionatlas +# pyexpressionatlas Python client for searching and downloading gene expression datasets from EMBL-EBI Expression Atlas diff --git a/docs/tutorial.md b/docs/tutorial.md index 5687926..f660fa6 100644 --- a/docs/tutorial.md +++ b/docs/tutorial.md @@ -1,6 +1,6 @@ # Tutorial -The `expressionatlas` package bridges the gap between Python and the [EMBL-EBI Expression Atlas](https://www.ebi.ac.uk/gxa), making it simple to search, download, and analyze curated gene expression datasets in Python. This client mirrors the [Bioconductor package](https://www.bioconductor.org/packages/release/data/experiment/html/ExpressionAtlas.html), and plugs right into the BiocPy ecosystem (`BiocFrame`, `SummarizedExperiment`, and `SingleCellExperiment`). +The `pyexpressionatlas` package bridges the gap between Python and the [EMBL-EBI Expression Atlas](https://www.ebi.ac.uk/gxa), making it simple to search, download, and analyze curated gene expression datasets in Python. This client mirrors the [Bioconductor package](https://www.bioconductor.org/packages/release/data/experiment/html/ExpressionAtlas.html), and plugs right into the BiocPy ecosystem (`BiocFrame`, `SummarizedExperiment`, and `SingleCellExperiment`). --- @@ -9,16 +9,16 @@ The `expressionatlas` package bridges the gap between Python and the [EMBL-EBI E First, make sure you have the package installed: ```bash -pip install expressionatlas +pip install pyexpressionatlas ``` Then, import the client: ```python -from expressionatlas import ExpressionAtlasClient +from pyexpressionatlas import ExpressionAtlasClient # Initialize the client. -# By default, files are cached in ~/.cache/expressionatlas_bfc. +# By default, files are cached in ~/.cache/pyexpressionatlas_bfc. # You can customize this directory by passing the cache_dir parameter: client = ExpressionAtlasClient(timeout=30, cache_dir="/my/custom/cache/path") ``` diff --git a/setup.cfg b/setup.cfg index af78907..1399a46 100644 --- a/setup.cfg +++ b/setup.cfg @@ -4,7 +4,7 @@ # https://setuptools.pypa.io/en/latest/references/keywords.html [metadata] -name = expressionatlas +name = pyexpressionatlas description = Python client for searching and downloading datasets from EMBL-EBI Expression Atlas author = Jayaram Kancherla author_email = jayaram.kancherla@gmail.com @@ -12,11 +12,11 @@ license = MIT license_files = LICENSE.txt long_description = file: README.md long_description_content_type = text/markdown; charset=UTF-8; variant=GFM -url = https://github.com/biocpy/expressionatlas +url = https://github.com/biocpy/pyexpressionatlas # Add here related links, for example: project_urls = - Documentation = https://github.com/biocpy/expressionatlas - Source = https://github.com/biocpy/expressionatlas + Documentation = https://github.com/biocpy/pyexpressionatlas + Source = https://github.com/biocpy/pyexpressionatlas # Changelog = https://pyscaffold.org/en/latest/changelog.html # Tracker = https://github.com/pyscaffold/pyscaffold/issues # Conda-Forge = https://anaconda.org/conda-forge/pyscaffold @@ -67,7 +67,7 @@ exclude = [options.extras_require] # Add here additional requirements for extra features, to install with: -# `pip install expressionatlas[PDF]` like: +# `pip install pyexpressionatlas[PDF]` like: # PDF = ReportLab; RXP # Add here test requirements (semicolon/line-separated) @@ -80,10 +80,10 @@ testing = [options.entry_points] # Add here console scripts like: # console_scripts = -# script_name = expressionatlas.module:function +# script_name = pyexpressionatlas.module:function # For example: # console_scripts = -# fibonacci = expressionatlas.skeleton:run +# fibonacci = pyexpressionatlas.skeleton:run # And any other entry points, for example: # pyscaffold.cli = # awesome = pyscaffoldext.awesome.extension:AwesomeExtension @@ -95,7 +95,7 @@ testing = # CAUTION: --cov flags may prohibit setting breakpoints while debugging. # Comment those flags to avoid this pytest issue. addopts = - --cov expressionatlas --cov-report term-missing + --cov pyexpressionatlas --cov-report term-missing --verbose norecursedirs = dist @@ -130,6 +130,6 @@ exclude = # PyScaffold's parameters when the project was created. # This will be used when updating. Do not change! version = 4.6 -package = expressionatlas +package = pyexpressionatlas extensions = markdown diff --git a/setup.py b/setup.py index 6f43bf0..7df56bc 100644 --- a/setup.py +++ b/setup.py @@ -1,10 +1,10 @@ """ -Setup file for expressionatlas. -Use setup.cfg to configure your project. + Setup file for pyexpressionatlas. + Use setup.cfg to configure your project. -This file was generated with PyScaffold 4.6. -PyScaffold helps you to put up the scaffold of your new Python project. -Learn more under: https://pyscaffold.org/ + This file was generated with PyScaffold 4.6. + PyScaffold helps you to put up the scaffold of your new Python project. + Learn more under: https://pyscaffold.org/ """ from setuptools import setup diff --git a/src/expressionatlas/__init__.py b/src/pyexpressionatlas/__init__.py similarity index 95% rename from src/expressionatlas/__init__.py rename to src/pyexpressionatlas/__init__.py index b0d9ae6..ef2cc75 100644 --- a/src/expressionatlas/__init__.py +++ b/src/pyexpressionatlas/__init__.py @@ -8,7 +8,7 @@ try: # Change here if project is renamed and does not equal the package name - dist_name = __name__ + dist_name = "pyexpressionatlas" __version__ = version(dist_name) except PackageNotFoundError: # pragma: no cover __version__ = "unknown" diff --git a/src/expressionatlas/api.py b/src/pyexpressionatlas/api.py similarity index 100% rename from src/expressionatlas/api.py rename to src/pyexpressionatlas/api.py diff --git a/src/expressionatlas/client.py b/src/pyexpressionatlas/client.py similarity index 100% rename from src/expressionatlas/client.py rename to src/pyexpressionatlas/client.py diff --git a/src/expressionatlas/download.py b/src/pyexpressionatlas/download.py similarity index 99% rename from src/expressionatlas/download.py rename to src/pyexpressionatlas/download.py index 98810ea..de3df35 100644 --- a/src/expressionatlas/download.py +++ b/src/pyexpressionatlas/download.py @@ -205,7 +205,7 @@ def get_atlas_data(experiment_accessions: list[str]) -> NamedList: Returns: Dictionary-like object mapping accession to experiment data. """ - from expressionatlas.validation import filter_valid_accessions + from pyexpressionatlas.validation import filter_valid_accessions if not experiment_accessions: raise ValueError("Please provide a vector of experiment accessions to download.") @@ -456,7 +456,7 @@ def _create_summarized_experiment_from_tsv( def _download_via_converter(rdata_url: str, accession: str) -> NamedList: """Download experiment data via cloud converter.""" - from expressionatlas.converter import ConverterClient, ConverterError + from pyexpressionatlas.converter import ConverterClient, ConverterError client = ConverterClient() diff --git a/src/expressionatlas/exceptions.py b/src/pyexpressionatlas/exceptions.py similarity index 100% rename from src/expressionatlas/exceptions.py rename to src/pyexpressionatlas/exceptions.py diff --git a/src/expressionatlas/models.py b/src/pyexpressionatlas/models.py similarity index 100% rename from src/expressionatlas/models.py rename to src/pyexpressionatlas/models.py diff --git a/src/expressionatlas/validation.py b/src/pyexpressionatlas/validation.py similarity index 100% rename from src/expressionatlas/validation.py rename to src/pyexpressionatlas/validation.py diff --git a/tests/conftest.py b/tests/conftest.py index 60b8caf..4517236 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,5 +1,5 @@ """ - Dummy conftest.py for expressionatlas. + Dummy conftest.py for pyexpressionatlas. If you don't know what this is for, just leave it empty. Read more about conftest.py under: diff --git a/tests/test_api.py b/tests/test_api.py index 193c253..c9ad20b 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -3,8 +3,8 @@ import pytest import responses -from expressionatlas.api import BIOSTUDIES_SEARCH_URL, BIOSTUDIES_STUDY_URL, BioStudiesAPI -from expressionatlas.exceptions import APIError +from pyexpressionatlas.api import BIOSTUDIES_SEARCH_URL, BIOSTUDIES_STUDY_URL, BioStudiesAPI +from pyexpressionatlas.exceptions import APIError class TestBioStudiesAPI: diff --git a/tests/test_download.py b/tests/test_download.py index 0c36f2d..2580898 100644 --- a/tests/test_download.py +++ b/tests/test_download.py @@ -1,6 +1,6 @@ import pytest import rds2py -from expressionatlas.download import _download_and_load_rds +from pyexpressionatlas.download import _download_and_load_rds def test_download_and_load_r_files(tmp_path): # Test rds loading diff --git a/tests/test_integration.py b/tests/test_integration.py index 1346c0a..1ee8fc1 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -6,8 +6,8 @@ import pytest -from expressionatlas import ExpressionAtlasClient -from expressionatlas.validation import is_valid_accession +from pyexpressionatlas import ExpressionAtlasClient +from pyexpressionatlas.validation import is_valid_accession @pytest.mark.integration # @pytest.mark.skip("takes too long") diff --git a/tests/test_models.py b/tests/test_models.py index e213fec..ac53990 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -1,7 +1,7 @@ """Tests for data models.""" -from expressionatlas.models import ( +from pyexpressionatlas.models import ( ExperimentType, SearchResult, search_results_to_biocframe, diff --git a/tests/test_validation.py b/tests/test_validation.py index c542008..d5775f9 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -2,8 +2,8 @@ import pytest -from expressionatlas.exceptions import InvalidAccessionError -from expressionatlas.validation import ( +from pyexpressionatlas.exceptions import InvalidAccessionError +from pyexpressionatlas.validation import ( filter_valid_accessions, is_valid_accession, validate_accession, From d39e9b9e6ba2d0fc91c426297c243b388b5999e2 Mon Sep 17 00:00:00 2001 From: Jayaram Kancherla Date: Wed, 12 Aug 2026 01:02:56 -0700 Subject: [PATCH 15/16] remove references to cloud convert --- src/pyexpressionatlas/__init__.py | 1 - src/pyexpressionatlas/download.py | 46 +------------------------------ 2 files changed, 1 insertion(+), 46 deletions(-) diff --git a/src/pyexpressionatlas/__init__.py b/src/pyexpressionatlas/__init__.py index ef2cc75..93a4bb6 100644 --- a/src/pyexpressionatlas/__init__.py +++ b/src/pyexpressionatlas/__init__.py @@ -19,7 +19,6 @@ from .download import ( get_atlas_data, get_atlas_experiment, - has_converter_available, has_tsv_files, ) from .exceptions import ( diff --git a/src/pyexpressionatlas/download.py b/src/pyexpressionatlas/download.py index de3df35..3ef6019 100644 --- a/src/pyexpressionatlas/download.py +++ b/src/pyexpressionatlas/download.py @@ -59,11 +59,6 @@ def has_tsv_files(accession: str) -> bool: return False -def has_converter_available() -> bool: - """Check if the cloud converter service is configured.""" - return bool(os.environ.get("CONVERTER_URL", "")) - - _BFC_INSTANCE: BiocFileCache | None = None @@ -171,14 +166,7 @@ def get_atlas_experiment(experiment_accession: str) -> NamedList | None: try: experiment_summary = _download_sc_experiment(experiment_accession) except DownloadError: - if has_converter_available(): - logger.info("TSV/SC not available, trying cloud converter service on RData...") - experiment_summary = _download_via_converter( - f"{FTP_BASE_URL}/{experiment_accession}/{experiment_accession}-atlasExperimentSummary.Rdata", - experiment_accession, - ) - else: - raise + raise if experiment_summary: logger.info(f"Successfully downloaded experiment summary object for {experiment_accession}") @@ -454,38 +442,6 @@ def _create_summarized_experiment_from_tsv( return SummarizedExperiment(assays=assays, row_data=row_bioc, column_data=col_bioc, metadata=metadata) -def _download_via_converter(rdata_url: str, accession: str) -> NamedList: - """Download experiment data via cloud converter.""" - from pyexpressionatlas.converter import ConverterClient, ConverterError - - client = ConverterClient() - - try: - bundles = client.convert_and_load(rdata_url, accession) - except ConverterError as e: - raise DownloadError(accession, f"Cloud converter failed: {e}") from e - - result = NamedList() - - for name, bundle in bundles.items(): - key = name.replace("dataset_", "") if name.startswith("dataset_") else name - - # We need to make sure bundle.genes and bundle.samples return dictionaries of column names mapping to lists of values - row_bioc = BiocFrame(bundle.genes, row_names=bundle.rownames) - col_bioc = BiocFrame(bundle.samples, row_names=bundle.colnames) - - assays = {} - if bundle.matrix is not None: - assays["counts" if key == "rnaseq" else "exprs"] = bundle.matrix - - meta = bundle.meta.copy() - meta["source"] = "converter" - - se = SummarizedExperiment(assays=assays, row_data=row_bioc, column_data=col_bioc, metadata=meta) - result[key] = se - - return result - def _download_sc_experiment(accession: str) -> SingleCellExperiment: """Download and construct a SingleCellExperiment from SC Expression Atlas.""" From 0313bbe1dd08aa391d7f93834cb8fdfb0d83d06a Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 12 Aug 2026 08:03:18 +0000 Subject: [PATCH 16/16] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- CHANGELOG.md | 4 ++-- setup.py | 10 +++++----- src/pyexpressionatlas/download.py | 1 - 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0072608..ac51dd6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,5 +2,5 @@ ## Version 0.0.1 -- Initial version of the package to support access to datasets from expression atlas. -- Uses `rd2py` to read RDS files and supports bulk RNA-seq, and single-cell RNA-seq datasets. +- Initial version of the package to support access to datasets from expression atlas. +- Uses `rd2py` to read RDS files and supports bulk RNA-seq, and single-cell RNA-seq datasets. diff --git a/setup.py b/setup.py index 8bf7435..ab23ef3 100644 --- a/setup.py +++ b/setup.py @@ -1,10 +1,10 @@ """ - Setup file for pyexpressionatlas. - Use setup.cfg to configure your project. +Setup file for pyexpressionatlas. +Use setup.cfg to configure your project. - This file was generated with PyScaffold 4.6. - PyScaffold helps you to put up the scaffold of your new Python project. - Learn more under: https://pyscaffold.org/ +This file was generated with PyScaffold 4.6. +PyScaffold helps you to put up the scaffold of your new Python project. +Learn more under: https://pyscaffold.org/ """ from setuptools import setup diff --git a/src/pyexpressionatlas/download.py b/src/pyexpressionatlas/download.py index 8a45cb5..e358e9a 100644 --- a/src/pyexpressionatlas/download.py +++ b/src/pyexpressionatlas/download.py @@ -441,7 +441,6 @@ def _create_summarized_experiment_from_tsv( return SummarizedExperiment(assays=assays, row_data=row_bioc, column_data=col_bioc, metadata=metadata) - def _download_sc_experiment(accession: str) -> SingleCellExperiment: """Download and construct a SingleCellExperiment from SC Expression Atlas.""" base_url = f"{FTP_SC_BASE_URL}/{accession}"