pax_global_header00006660000000000000000000000064152655247710014530gustar00rootroot0000000000000052 comment=55624b6f26d42802d3ba01fbe8539202c4093773 openvax-sercol-55624b6/000077500000000000000000000000001526552477100147545ustar00rootroot00000000000000openvax-sercol-55624b6/.github/000077500000000000000000000000001526552477100163145ustar00rootroot00000000000000openvax-sercol-55624b6/.github/workflows/000077500000000000000000000000001526552477100203515ustar00rootroot00000000000000openvax-sercol-55624b6/.github/workflows/documentation.yml000066400000000000000000000021271526552477100237470ustar00rootroot00000000000000name: Documentation on: pull_request: push: branches: [master] workflow_dispatch: permissions: contents: read jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: '3.12' - run: python -m pip install -r requirements-docs.txt - run: ./docs.sh - uses: actions/upload-artifact@v4 with: name: documentation path: site/ publish: needs: build if: github.ref == 'refs/heads/master' && github.event_name != 'pull_request' runs-on: ubuntu-latest permissions: contents: write steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - uses: actions/download-artifact@v4 with: name: documentation path: site/ - run: | python -m pip install 'ghp-import>=2.1,<3' git config user.name github-actions[bot] git config user.email 41898282+github-actions[bot]@users.noreply.github.com ghp-import --no-jekyll --push --force site/ openvax-sercol-55624b6/.github/workflows/tests.yml000066400000000000000000000043301526552477100222360ustar00rootroot00000000000000# This workflow will install Python dependencies, run tests and lint with a variety of Python versions # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python name: Tests on: [push, pull_request] jobs: build: runs-on: ubuntu-latest strategy: fail-fast: true matrix: include: - python-version: "3.11" pandas-version: "pandas>=2,<3" - python-version: "3.11" pandas-version: "pandas>=3,<4" - python-version: "3.12" pandas-version: "pandas>=3,<4" - python-version: "3.13" pandas-version: "pandas>=3,<4" - python-version: "3.14" pandas-version: "pandas>=3,<4" steps: - name: Checkout repository uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} cache: "pip" - name: Install dependencies run: | python -m pip install --upgrade pip python -m pip install flake8 pytest pytest-cov coveralls ruff pip install -r requirements.txt pip install '${{ matrix.pandas-version }}' pip install . - name: Lint with flake8 run: | # stop the build if there are Python syntax errors or undefined names flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics - name: Run default linting script run: | ./lint.sh - name: Run unit tests run: | ./test.sh - name: Publish coverage to Coveralls uses: coverallsapp/github-action@v2.2.3 with: flag-name: python-${{ matrix.python-version }} parallel: true finish-coverage: needs: build if: ${{ always() }} runs-on: ubuntu-latest steps: - name: Finalize parallel coverage uses: coverallsapp/github-action@v2.2.3 with: parallel-finished: true openvax-sercol-55624b6/.gitignore000066400000000000000000000020331526552477100167420ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover .hypothesis/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # IPython Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # dotenv .env # virtualenv venv/ ENV/ # Spyder project settings .spyderproject # Rope project settings .ropeproject site/ openvax-sercol-55624b6/LICENSE000066400000000000000000000261351526552477100157700ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. openvax-sercol-55624b6/README.md000066400000000000000000000023061526552477100162340ustar00rootroot00000000000000[![Tests](https://github.com/openvax/sercol/actions/workflows/tests.yml/badge.svg)](https://github.com/openvax/sercol/actions/workflows/tests.yml) Coverage Status PyPI # sercol Filter and group a collection while keeping its collection type and source metadata. `Collection` is the base class for `varcode.VariantCollection`, `varcode.EffectCollection` and `mhctools.BindingPredictionCollection`. ## Install and filter ```sh python -m pip install sercol ``` Python 3.11 or later is required. ```python from sercol import Collection values = Collection([5, 2, 3, 2]) print(list(values.filter(lambda value: value >= 3))) # [5, 3] ``` ## Documentation - [Group values, save and reload](docs/index.md) - [Select, order and track values](docs/guides/collections.md) - [API reference](docs/reference.md) To build the documentation locally, run `python -m pip install -r requirements-docs.txt` and `./docs.sh`. openvax-sercol-55624b6/deploy.sh000077500000000000000000000002751526552477100166130ustar00rootroot00000000000000./lint.sh && \ ./test.sh && \ python3 -m pip install --upgrade build && \ python3 -m pip install --upgrade twine && \ rm -rf dist && \ python3 -m build && \ python3 -m twine upload dist/* openvax-sercol-55624b6/develop.sh000077500000000000000000000000311526552477100167430ustar00rootroot00000000000000set -e pip install -e . openvax-sercol-55624b6/docs.sh000077500000000000000000000001511526552477100162400ustar00rootroot00000000000000#!/usr/bin/env bash set -euo pipefail python -m mkdocs build --strict python scripts/check_docs_links.py openvax-sercol-55624b6/docs/000077500000000000000000000000001526552477100157045ustar00rootroot00000000000000openvax-sercol-55624b6/docs/dev/000077500000000000000000000000001526552477100164625ustar00rootroot00000000000000openvax-sercol-55624b6/docs/dev/documentation-style.md000066400000000000000000000027471526552477100230250ustar00rootroot00000000000000# Documentation style Follow the [PyEnsembl writing guide](https://github.com/openvax/pyensembl/blob/edd183d/docs/dev/documentation-style.md) and the [mhctools example](https://github.com/openvax/mhctools/tree/master/docs). Put installation and the first useful example on the home page. Give complete imports and concrete inputs, explain the result, and state prerequisites before the reader runs a command. Show output only when it has been checked. Label replaceable paths and templates. Order guides by common tasks before advanced setup and implementation details. Keep desktop sidebar groups expanded initially and individually collapsible. Split a page when a substantial task or reference needs its own explanation. Preserve useful old links and anchors when moving content. Use ordinary text for concepts and library names; reserve inline code for literal commands, API names, parameters, paths and values. Keep qualifications, experimental status and scientific limitations beside the claims they qualify. Use system fonts, a readable line length and restrained headings. Let wide tables and code blocks scroll inside their containers. Avoid repetitive navigation lists in prose and excessive callouts. Install requirements-docs.txt and run ./docs.sh before opening a PR. Review the home page and a reference page at desktop and narrow widths. Run the repository's required lint and test commands and execute complete examples. Documentation dependencies are separate from runtime dependencies. openvax-sercol-55624b6/docs/guides/000077500000000000000000000000001526552477100171645ustar00rootroot00000000000000openvax-sercol-55624b6/docs/guides/collections.md000066400000000000000000000040051526552477100220230ustar00rootroot00000000000000# Select, order and track values ## Remove duplicates and sort ```python from sercol import Collection values = Collection([5, 2, 3, 2], distinct=True, sort_key=abs) print(list(values)) ``` ```text [2, 3, 5] ``` `distinct=True` uses a set, so elements must be hashable and their input order is not retained. Supply `sort_key` when you need a predictable order. ## Select by a value lookup ```python scores = {"alpha": 2.0, "beta": 0.5} names = Collection(["alpha", "beta", "unknown"]) selected = names.filter_above_threshold( key_fn=lambda name: name, value_dict=scores, threshold=1.0, ) print(list(selected)) ``` ```text ['alpha'] ``` The comparison is strictly greater than the threshold. Missing keys receive `default_value`, which defaults to zero. Use `filter_any_above_threshold()` when each element supplies several lookup keys and any one may qualify. ## Put an element in several groups ```python words = Collection(["ab", "bc"]) groups = words.multi_groupby(lambda word: set(word)) print({key: list(groups[key]) for key in sorted(groups)}) ``` ```text {'a': ['ab'], 'b': ['ab', 'bc'], 'c': ['bc']} ``` `multi_groupby()` accepts an iterable of keys for each element. Return distinct keys for each element when it should appear only once in each group. ## Keep source metadata ```python values = Collection([1, 2, 3], sources={"results.csv"}) selected = values.filter(lambda value: value > 1) print(selected.source) print(selected.filenames) ``` ```text results.csv ['results.csv'] ``` `sources` labels where values came from; it does not open those files. `source` requires exactly one source. `filenames` strips directory components. ## Extend the collection A subclass should accept the state passed by `clone_with_new_elements()`: `elements`, `distinct`, `sort_key` and `sources`, or override that cloning operation. Implement its own `to_dict()` with constructor-compatible keys to support serialization. `Collection.to_dict()` deliberately rejects subclasses that have not supplied their own implementation. openvax-sercol-55624b6/docs/index.md000066400000000000000000000026121526552477100173360ustar00rootroot00000000000000# sercol Filter and group a collection while keeping its collection type and source metadata. `Collection` is also the base class used by several OpenVax libraries for variants, effects and predictions. ## Install ```sh python -m pip install sercol ``` Python 3.11 or later is required. ## Filter and group values ```python from sercol import Collection values = Collection([5, 2, 3, 2]) selected = values.filter(lambda value: value >= 3) groups = values.groupby(lambda value: value % 2) print(list(selected)) print({key: list(group) for key, group in groups.items()}) ``` ```text [5, 3] {1: [5, 3], 0: [2, 2]} ``` `filter()` returns a collection; `groupby()` returns a dictionary of collections. Both preserve the original collection class and constructor state. The original collection is unchanged. ## Save and reload Continuing with `values` above: ```python restored = Collection.from_json(values.to_json()) print(list(restored)) print(restored == values) ``` ```text [5, 2, 3, 2] True ``` Serialization uses [serializable](https://github.com/openvax/serializable). Elements and constructor state must be supported by that format; callable sorting keys need to be importable when reconstructing the collection. See [select, order and track values](guides/collections.md) for thresholds, multiple grouping keys and source metadata. The [API reference](reference.md) lists all collection operations. openvax-sercol-55624b6/docs/reference.md000066400000000000000000000012741526552477100201700ustar00rootroot00000000000000# Collection reference | Task | Method | | --- | --- | | Keep matching elements | `filter()` | | Group under one or several keys | `groupby()`, `multi_groupby()` | | Apply lookup thresholds | `filter_above_threshold()`, `filter_any_above_threshold()` | | Preserve metadata while replacing elements | `clone_with_new_elements()` | | Write record-shaped elements to a table | `to_dataframe()`, `to_csv()` | | Save or reload supported objects | Inherited `to_json()`, `from_json()` | Table conversion expects elements that the serialization helper can turn into field dictionaries. A collection of primitive integers is useful for filtering examples, but is not a record table. ::: sercol.Collection openvax-sercol-55624b6/docs/stylesheets/000077500000000000000000000000001526552477100202605ustar00rootroot00000000000000openvax-sercol-55624b6/docs/stylesheets/docs.css000066400000000000000000000026441526552477100217300ustar00rootroot00000000000000/* A quiet reading surface for scientific guides and API reference. */ :root { --md-text-font: "Helvetica Neue", Arial, sans-serif; --md-code-font: "SFMono-Regular", Consolas, "Liberation Mono", monospace; } body[data-md-color-scheme="default"] { --md-default-bg-color: #ffffff; --md-default-fg-color: #263238; --md-default-fg-color--light: #59636b; --md-typeset-a-color: #1769aa; --md-code-bg-color: #f5f7f9; } .md-header { box-shadow: none; border-bottom: 1px solid #e2e6ea; } .md-content__inner { max-width: 76ch; } .md-typeset { font-size: 0.85rem; line-height: 1.65; } .md-typeset h1, .md-typeset h2, .md-typeset h3 { color: var(--md-default-fg-color); font-weight: 600; letter-spacing: normal; } .md-typeset h1 { font-size: 1.8rem; } .md-typeset h2 { font-size: 1.25rem; } /* Inline identifiers read as part of a sentence, rather than little badges. */ .md-typeset :not(pre) > code { background: transparent; border-radius: 0; padding: 0; font-size: 0.88em; color: inherit; box-shadow: none; } .md-typeset table:not([class]) { font-size: 0.8rem; line-height: 1.5; } /* Keep an identifier intact; wide reference tables can scroll. */ .md-typeset table code { white-space: nowrap; } .md-typeset h3 { font-size: 1.05rem; } .md-typeset pre { overflow-x: auto; } /* Keep the repository link without unrelated GitHub release/star counters. */ .md-source__facts { display: none; } openvax-sercol-55624b6/lint.sh000077500000000000000000000001201526552477100162520ustar00rootroot00000000000000#!/bin/bash set -o errexit ruff check sercol/ tests/ echo 'Passes ruff check' openvax-sercol-55624b6/mkdocs.yml000066400000000000000000000022231526552477100167560ustar00rootroot00000000000000site_name: sercol site_description: Filter, group and serialize Python collections site_url: https://openvax.github.io/sercol/ repo_url: https://github.com/openvax/sercol repo_name: openvax/sercol edit_uri: edit/master/docs/ strict: true theme: name: material font: false palette: primary: white accent: blue features: - navigation.indexes - navigation.expand - content.code.copy validation: links: not_found: warn unrecognized_links: warn anchors: warn plugins: - search - mkdocstrings: handlers: python: paths: - . options: docstring_style: numpy show_root_heading: true show_root_full_path: false show_source: false separate_signature: true heading_level: 2 docstring_section_style: list members_order: source markdown_extensions: - tables - toc: permalink: true - pymdownx.superfences extra_css: - stylesheets/docs.css nav: - Home: index.md - Common tasks: - Select, order and track values: guides/collections.md - API reference: reference.md - Contributing: - Documentation style: dev/documentation-style.md openvax-sercol-55624b6/pyproject.toml000066400000000000000000000022741526552477100176750ustar00rootroot00000000000000[build-system] requires = ["setuptools>=64"] build-backend = "setuptools.build_meta" [project] name = "sercol" requires-python = ">=3.11" authors = [{name="Alex Rubinsteyn", email="alex.rubinsteyn@unc.edu"}] description = "Rich collection class with grouping and filtering helpers" classifiers = [ "Development Status :: 4 - Beta", "Environment :: Console", "Operating System :: OS Independent", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", ] readme = "README.md" dynamic = ["version", "dependencies"] [tool.setuptools.dynamic] version = {attr = "sercol.__version__"} dependencies = {file = ["requirements.txt"]} [tool.setuptools] packages = ["sercol"] [project.urls] "Homepage" = "https://github.com/openvax/sercol" "Bug Tracker" = "https://github.com/openvax/sercol/issues" [tool.ruff.lint] select = ["E", "F"] ignore = ["F821", "E501", "F841", "E731", "E741", "E722", "E721"] [tool.ruff.lint.per-file-ignores] "__init__.py" = ["F401"] "test*/*" = ["F401"] openvax-sercol-55624b6/requirements-docs.txt000066400000000000000000000001061526552477100211630ustar00rootroot00000000000000mkdocs>=1.6,<2 mkdocs-material>=9.5,<10 mkdocstrings[python]>=0.27,<2 openvax-sercol-55624b6/requirements.txt000066400000000000000000000000601526552477100202340ustar00rootroot00000000000000serializable>=1.0.0,<2.0.0 pandas>=2.0.0,<4.0.0 openvax-sercol-55624b6/scripts/000077500000000000000000000000001526552477100164435ustar00rootroot00000000000000openvax-sercol-55624b6/scripts/check_docs_examples.py000066400000000000000000000021751526552477100230050ustar00rootroot00000000000000"""Execute documentation examples and compare the printed output.""" import contextlib import io from pathlib import Path import re import sys import types def main(): count = 0 for path in sorted(Path("docs").rglob("*.md")): module = types.ModuleType("docs_example_" + path.stem.replace("-", "_")) sys.modules[module.__name__] = module blocks = list(re.finditer(r"```(python|text)\n(.*?)\n```", path.read_text(), re.S)) for index, match in enumerate(blocks): if match[1] != "python": continue output = io.StringIO() with contextlib.redirect_stdout(output): exec(compile(match[2], str(path), "exec"), module.__dict__) if index + 1 < len(blocks) and blocks[index + 1][1] == "text": expected = blocks[index + 1][2].rstrip() actual = output.getvalue().rstrip() if actual != expected: raise AssertionError(f"{path}: {actual!r} != {expected!r}") count += 1 print(f"Executed {count} documentation examples.") if __name__ == "__main__": main() openvax-sercol-55624b6/scripts/check_docs_links.py000066400000000000000000000036111526552477100223030ustar00rootroot00000000000000"""Check rendered internal links and fragment targets.""" from html.parser import HTMLParser from pathlib import Path from urllib.parse import unquote, urlsplit import yaml class Page(HTMLParser): def __init__(self, text): super().__init__() self.ids = set() self.links = [] self.feed(text) def handle_starttag(self, tag, attrs): attrs = dict(attrs) if attrs.get("id"): self.ids.add(attrs["id"]) if tag == "a" and attrs.get("href"): self.links.append(attrs["href"]) def main(): root = Path("site").resolve() base = urlsplit(yaml.safe_load(Path("mkdocs.yml").read_text())["site_url"]).path.rstrip("/") pages = {p.resolve(): Page(p.read_text()) for p in root.rglob("*.html")} failures = [] count = 0 for source, page in pages.items(): for href in page.links: url = urlsplit(href) if url.scheme or url.netloc: continue path = unquote(url.path) if path.startswith("/"): if not (path == base or path.startswith(base + "/")): continue target = (root / path[len(base):].lstrip("/")).resolve() else: target = (source.parent / path).resolve() if path else source if target.is_dir(): target /= "index.html" count += 1 if not target.is_relative_to(root) or not target.exists(): failures.append(f"{source.relative_to(root)}: missing {href}") elif url.fragment and target in pages and unquote(url.fragment) not in pages[target].ids: failures.append(f"{source.relative_to(root)}: missing fragment {href}") if failures: raise SystemExit("\n".join(failures)) print(f"Checked {len(pages)} pages and {count} internal links.") if __name__ == "__main__": main() openvax-sercol-55624b6/sercol/000077500000000000000000000000001526552477100162435ustar00rootroot00000000000000openvax-sercol-55624b6/sercol/__init__.py000066400000000000000000000012051526552477100203520ustar00rootroot00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .collection import Collection __version__ = "1.0.5" __all__ = ["Collection", "__version__"] openvax-sercol-55624b6/sercol/collection.py000066400000000000000000000217161526552477100207570ustar00rootroot00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os.path from collections import defaultdict import pandas as pd import serializable class Collection(serializable.Serializable): """ Collection base class with grouping and filtering functions. """ def __init__( self, elements, distinct=False, sort_key=None, sources=set([])): """ Parameters ---------- elements : list Collection of any class which is compatible with the sort key distinct : bool Only keep distinct entries or allow duplicates. sort_key : fn Function which maps each element to a sorting criterion. sources : set Set of files from which this collection was generated. """ self.distinct = distinct if distinct: elements = set(elements) self.sort_key = sort_key if self.sort_key is None: self.elements = elements else: self.elements = sorted(elements, key=sort_key) self.sources = sources def to_dict(self): if self.__class__ is not Collection: raise ValueError( "Derived class %s should implement own to_dict()" % ( self.__class__.__name__,)) return dict( elements=self.elements, distinct=self.distinct, sort_key=self.sort_key, sources=self.sources) def to_dataframe(self): return pd.DataFrame.from_records([serializable.to_dict(x) for x in self]) def to_csv(self, path): return self.to_dataframe().to_csv(path) def clone_with_new_elements( self, new_elements, drop_keywords=set([]), rename_dict={}, extra_kwargs={}): """ Create another Collection of the same class and with same state but possibly different entries. Extra parameters to control which keyword arguments get passed to the initializer are necessary since derived classes have different constructors than the base class. """ kwargs = dict( elements=new_elements, distinct=self.distinct, sort_key=self.sort_key, sources=self.sources) for name in drop_keywords: kwargs.pop(name) for old_name, new_name in rename_dict.items(): kwargs[new_name] = kwargs.pop(old_name) kwargs.update(extra_kwargs) return self.__class__(**kwargs) @property def source(self): """ Returns the single source name for a variant collection if it is unique, otherwise raises an error. """ if len(self.sources) == 0: raise ValueError("No source associated with %s" % self.__class__.__name__) elif len(self.sources) > 1: raise ValueError("Multiple sources for %s" % self.__class__.__name__) return list(self.sources)[0] @property def path(self): """ Alternative name for VariantCollection.source maintained for backward compatibility. """ return self.source @property def filenames(self): """ Assuming sources are paths to VCF or MAF files, trim their directory path and return just the file names. """ return [os.path.basename(source) for source in self.sources if source] @property def filename(self): """ Return single filename if there is a single non-empty source. Keeping this property for backward compatibility. """ return self.filenames[0] def short_string(self): """ Compact string representation which doesn't print any of the collection elements. """ source_str = "" if self.sources: source_str = " from '%s'" % ",".join(self.sources) return "<%s%s with %d elements>" % ( self.__class__.__name__, source_str, len(self)) def to_string(self, limit=None): """ Create a string representation of this collection, showing up to `limit` items. """ header = self.short_string() if len(self) == 0: return header contents = "" element_lines = [ " -- %s" % (element,) for element in self.elements[:limit] ] contents = "\n".join(element_lines) if limit is not None and len(self.elements) > limit: contents += "\n ... and %d more" % (len(self) - limit) return "%s\n%s" % (header, contents) def __str__(self): return self.to_string(limit=50) def __len__(self): return len(self.elements) def __iter__(self): return iter(self.elements) def __hash__(self): return hash(len(self)) def __getitem__(self, idx): return self.elements[idx] def __eq__(self, other): if self is other: return True return ( self.__class__ == other.__class__ and len(self) == len(other) and all(x == y for (x, y) in zip(self, other))) def filter(self, filter_fn): return self.clone_with_new_elements([ element for element in self.elements if filter_fn(element)]) def groupby(self, key_fn): """ Parameters ---------- key_fn : function Takes an effect or variant, returns a grouping key. """ result_dict = defaultdict(list) for x in self: result_dict[key_fn(x)].append(x) # convert result lists into same Collection type as this one return { k: self.clone_with_new_elements(elements) for (k, elements) in result_dict.items() } def multi_groupby(self, key_fn): """ Like a groupby but expect the key_fn to return multiple keys for each element. """ result_dict = defaultdict(list) for x in self: for key in key_fn(x): result_dict[key].append(x) # convert result lists into same Collection type as this one return { k: self.clone_with_new_elements(elements) for (k, elements) in result_dict.items() } def filter_above_threshold( self, key_fn, value_dict, threshold, default_value=0.0): """The code for filtering by gene or transcript expression was pretty much identical aside from which identifier you pull off an effect. So, factored out the common operations for filtering an effect collection into this helper method. Parameters ---------- key_fn : callable Given an element of this collection, returns a key into `value_dict` value_dict : dict Dict from keys returned by `extract_key_fn` to float values threshold : float Only keep elements whose value in `value_dict` is above this threshold. default_value : float Value to use for elements whose key is not in `value_dict` """ def filter_fn(x): key = key_fn(x) value = value_dict.get(key, default_value) return value > threshold return self.filter(filter_fn) def filter_any_above_threshold( self, multi_key_fn, value_dict, threshold, default_value=0.0): """Like filter_above_threshold but `multi_key_fn` returns multiple keys and the element is kept if any of them have a value above the given threshold. Parameters ---------- multi_key_fn : callable Given an element of this collection, returns multiple keys into `value_dict` value_dict : dict Dict from keys returned by `extract_key_fn` to float values threshold : float Only keep elements whose value in `value_dict` is above this threshold. default_value : float Value to use for elements whose key is not in `value_dict` """ def filter_fn(x): for key in multi_key_fn(x): value = value_dict.get(key, default_value) if value > threshold: return True return False return self.filter(filter_fn) openvax-sercol-55624b6/tasks/000077500000000000000000000000001526552477100161015ustar00rootroot00000000000000openvax-sercol-55624b6/tasks/todo.md000066400000000000000000000050461526552477100173750ustar00rootroot00000000000000# Release sercol 1.0.2: compatible dependency metadata ## Specification Complete and release existing PR #5 for issue #4. Keep its compatible `serializable>=1.0.0,<2.0.0` bound and serialization regression tests, and remove the unused direct simplejson requirement. Serializable owns its own JSON dependency. Preserve the existing pandas range and collection behavior. Bump the current source version 1.0.1 to 1.0.2; PyPI currently has 1.0.0. The current PR has a failed Coveralls upload despite passing installation, lint, and tests. File this workflow defect and coordinate the matrix uploads using Coveralls' documented parallel flags and a single finalization job. Keep coverage failures visible and preserve the existing test matrix. Validate both the supported serializable 1.0.0 floor and the current local development checkout, including actual package resolution with current varcode. Inspect built wheel and sdist dependency metadata, review the final diff, and require green CI before merging. Deploy using the repository script from clean master, then verify downloaded PyPI artifacts against local builds. ## Plan - [x] Inspect the issue, existing PR, source dependencies, and CI failure. - [x] Record the CI defect (#6) and complete the version/workflow changes. - [x] Run lint and tests with serializable 1.0.0 and current development sources. - [x] Verify clean dependency resolution and wheel/sdist metadata. - [ ] Review the complete diff, update PR #5, and verify CI. - [ ] Merge, deploy 1.0.2 from clean master, and record publication verification on PR #5 after the release occurs. ## Review The dependency and three regression-test changes originated in PR #5; this release preserves that work instead of creating a competing fix. The shared sercol checkout remains on master while preparation uses an isolated worktree. All eight tests pass with both serializable 1.0.0 and the remote-verified local development checkout of 1.1.0 (19c38ce). Lint passes and `pip check` reports no broken requirements. Reproduced the old source-install conflict; the corrected source resolves together with current local serializable, varcode, pyensembl, datacache, and gtfparse without overriding dependency bounds. Both built distributions identify version 1.0.2 and declare exactly `serializable>=1.0.0,<2.0.0` and `pandas>=2.0.0,<3.0.0`; no direct simplejson requirement remains. Twine metadata checks pass. The pinned Coveralls action supports both parallel upload and finalization inputs. The final workflow preserves Python 3.9–3.11 and keeps upload failures visible. openvax-sercol-55624b6/test.sh000077500000000000000000000001271526552477100162720ustar00rootroot00000000000000#!/bin/bash set -o errexit pytest --cov=sercol/ --cov-report=term-missing tests "$@" openvax-sercol-55624b6/tests/000077500000000000000000000000001526552477100161165ustar00rootroot00000000000000openvax-sercol-55624b6/tests/__init__.py000066400000000000000000000000001526552477100202150ustar00rootroot00000000000000openvax-sercol-55624b6/tests/common.py000066400000000000000000000025201526552477100177570ustar00rootroot00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def ok_(a, s=None): if s is None: assert a else: assert a, s def eq_(a, b, s=None): if s is None: assert a == b else: assert a == b, s def neq_(a, b, s=None): if s is None: assert a != b else: assert a != b, s def gt_(a, b, s=None): if s is None: assert a > b else: assert a > b, s def lt_(a, b, s=None): if s is None: assert a < b else: assert a < b, s def gte_(a, b, s=None): if s is None: assert a >= b else: assert a >= b, s def lte_(a, b, s=None): if s is None: assert a <= b else: assert a <= b, s def almost_eq_(a, b, tol=1e-6, s=None): if s is None: assert abs(a - b) < tol else: assert abs(a - b) < tol, sopenvax-sercol-55624b6/tests/test_collection.py000066400000000000000000000045131526552477100216650ustar00rootroot00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Test methods shared by both VariantCollection and EffectCollection """ from .common import eq_, neq_ from sercol import Collection def test_collection_len(): collection = Collection([1, 2, 3]) assert len(collection) == 3 collection = Collection([]) assert len(collection) == 0 def test_collection_eq(): elements = ["a", "b", "c"] collection = Collection(elements) eq_(collection, collection, "collection should equal itself") eq_(collection, Collection(elements)) def test_collection_neq(): elements = ["a", "b", "c"] c1 = Collection(elements) c2 = Collection(elements[:2]) neq_(c1, c2) def test_filter(): collection = Collection([1, 2, 3, 4]) filtered = collection.filter(lambda x: x < 3) expected = Collection([1, 2]) eq_(filtered, expected) def test_groupby(): collection = Collection(["alpha", "able", "beta", "backroom"]) groups = collection.groupby(lambda x: x[0]) eq_(len(groups), 2) eq_(set(groups.keys()), {"a", "b"}) def test_collection_dict_roundtrip(): collection = Collection(["a", "b"], sources={"example.vcf"}) state_dict = collection.to_dict() eq_(set(state_dict.keys()), {"elements", "distinct", "sort_key", "sources"}) restored = Collection.from_dict(state_dict) eq_(restored, collection) eq_(restored.sources, {"example.vcf"}) def test_collection_json_roundtrip(): collection = Collection(["a", "b"], sources={"example.vcf"}) restored = Collection.from_json(collection.to_json()) eq_(restored.__class__, Collection) eq_(restored, collection) eq_(restored.sources, {"example.vcf"}) def test_collection_to_dataframe(): collection = Collection([{"x": 1}, {"x": 2}]) df = collection.to_dataframe() eq_(list(df.columns), ["x"]) eq_(list(df["x"]), [1, 2])