diff --git a/.copier-answers.yml b/.copier-answers.yml new file mode 100644 index 00000000..5ea46327 --- /dev/null +++ b/.copier-answers.yml @@ -0,0 +1,12 @@ +# Changes here will be overwritten by Copier; NEVER EDIT MANUALLY +_commit: 06352e2 +_src_path: cookie +backend: setuptools +email: dssi@bnl.gov +full_name: NSLS2 +license: BSD +org: NSLS-II +project_name: nslsii +project_short_description: NSLS-II related devices +url: https://github.com/NSLS-II/nslsii +vcs: true diff --git a/.git_archival.txt b/.git_archival.txt new file mode 100644 index 00000000..7c510094 --- /dev/null +++ b/.git_archival.txt @@ -0,0 +1,3 @@ +node: $Format:%H$ +node-date: $Format:%cI$ +describe-name: $Format:%(describe:tags=true,match=*[0-9]*)$ diff --git a/.gitattributes b/.gitattributes index 011097e9..15ea70a6 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ nsls-ii-tools/_version.py export-subst +src/nslsii/_version.py export-subst diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 00000000..6acb6c70 --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,77 @@ +See the [Scientific Python Developer Guide][spc-dev-intro] for a detailed +description of best practices for developing scientific packages. + +[spc-dev-intro]: https://learn.scientific-python.org/development/ + +# Quick development + +The fastest way to start with development is to use nox. If you don't have nox, +you can use `uvx nox` to run it without installing, or `uv tool install nox`. If +you don't have uv, you can +[install it a variety of ways](https://docs.astral.sh/uv/getting-started/installation/), +including with pip, pipx, brew, and just downloading the binary (single file). + +To use, run `nox`. This will lint and test using every installed version of +Python on your system, skipping ones that are not installed. You can also run +specific jobs: + +```console +$ nox -s lint # Lint only +$ nox -s tests # Python tests +$ nox -s docs # Build and serve the docs +$ nox -s build # Make an SDist and wheel +``` + +Nox handles everything for you, including setting up an temporary virtual +environment for each run. + +# Setting up a development environment manually + +You can set up a development environment by running: + +```bash +uv sync +``` + +# Pre-commit + +You should prepare pre-commit, which will help you by checking that commits pass +required checks: + +```bash +uv tool install pre-commit # or brew install pre-commit on macOS +pre-commit install # Will install a pre-commit hook into the git repo +``` + +You can also/alternatively run `pre-commit run` (changes only) or +`pre-commit run --all-files` to check even without installing the hook. + +# Testing + +Use pytest to run the unit checks: + +```bash +uv run pytest +``` + +# Coverage + +Use pytest-cov to generate coverage reports: + +```bash +uv run pytest --cov=nslsii +``` + +# Building docs + +You can build and serve the docs using: + +```bash +nox -s docs +``` + +You can build the docs only with: + +```bash +nox -s docs --non-interactive +``` diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..6c4b3695 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +version: 2 +updates: + # Maintain dependencies for GitHub Actions + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + groups: + actions: + patterns: + - "*" diff --git a/.github/release.yml b/.github/release.yml new file mode 100644 index 00000000..9d1e0987 --- /dev/null +++ b/.github/release.yml @@ -0,0 +1,5 @@ +changelog: + exclude: + authors: + - dependabot + - pre-commit-ci diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml new file mode 100644 index 00000000..4030c724 --- /dev/null +++ b/.github/workflows/cd.yml @@ -0,0 +1,60 @@ +name: CD + +on: + workflow_dispatch: + pull_request: + push: + branches: + - main + release: + types: + - published + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + # Many color libraries just need this to be set to any value, but at least + # one distinguishes color depth, where "3" -> "256-bit color". + FORCE_COLOR: 3 + +jobs: + dist: + name: Distribution build + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: hynek/build-and-inspect-python-package@v2 + + publish: + needs: [dist] + name: Publish to PyPI + environment: pypi + permissions: + id-token: write + attestations: write + contents: read + runs-on: ubuntu-latest + if: github.event_name == 'release' && github.event.action == 'published' + + steps: + - uses: actions/download-artifact@v4 + with: + name: Packages + path: dist + + - name: Generate artifact attestation for sdist and wheel + uses: actions/attest-build-provenance@v2 + with: + subject-path: "dist/*" + + - uses: pypa/gh-action-pypi-publish@release/v1 + with: + # Remember to tell (test-)pypi about this repo before publishing + # Remove this line to publish to PyPI + repository-url: https://test.pypi.org/legacy/ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..4864c5ba --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,71 @@ +name: CI + +on: + workflow_dispatch: + pull_request: + push: + branches: + - main + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + # Many color libraries just need this variable to be set to any value. + # Set it to 3 to support 8-bit color graphics (256 colors per channel) + # for libraries that care about the value set. + FORCE_COLOR: 3 + +jobs: + pre-commit: + name: Format + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: actions/setup-python@v5 + with: + python-version: "3.x" + + - uses: astral-sh/setup-uv@v6 + + checks: + name: Check Python ${{ matrix.python-version }} on ${{ matrix.runs-on }} + runs-on: ${{ matrix.runs-on }} + needs: [pre-commit] + strategy: + fail-fast: false + matrix: + python-version: ["3.9", "3.13"] + runs-on: [ubuntu-latest, windows-latest, macos-14] + + include: + - python-version: "pypy-3.10" + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + allow-prereleases: true + + - uses: astral-sh/setup-uv@v6 + + - name: Install package + run: uv sync + + - name: Test package + run: >- + uv run pytest -ra --cov --cov-report=xml --cov-report=term + --durations=20 + + - name: Upload coverage report + uses: codecov/codecov-action@v5 + with: + token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index 0d434bd9..46778702 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -12,7 +12,6 @@ on: jobs: deploy: - runs-on: ubuntu-latest permissions: id-token: write @@ -23,7 +22,7 @@ jobs: - name: Set up Python uses: actions/setup-python@v4 with: - python-version: '3.x' + python-version: "3.x" - name: Build package run: | diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 07e1b099..e07f97b3 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -4,11 +4,10 @@ on: push: pull_request: schedule: - - cron: '00 4 * * *' # daily at 4AM + - cron: "00 4 * * *" # daily at 4AM jobs: build: - runs-on: ubuntu-latest strategy: @@ -17,35 +16,37 @@ jobs: fail-fast: false steps: - - - uses: actions/checkout@v2 - - - name: Start Redis - uses: supercharge/redis-github-action@1.4.0 - - - name: start Kafka and Zookeeper - run: docker compose -f scripts/bitnami-kafka-docker-compose.yml up -d - - - name: is Kafka running? - run: docker ps -a - - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v2 - with: - python-version: ${{ matrix.python-version }} - - - name: Install - shell: bash -l {0} - run: | - set -vxeuo pipefail - pip install --upgrade pip wheel - pip install . - pip install -r requirements-dev.txt - pip list - - - name: Test with pytest - shell: bash -l {0} - run: | - set -vxeuo pipefail - coverage run -m pytest -s -v - coverage report + - uses: actions/checkout@v2 + + - name: Start Redis + uses: supercharge/redis-github-action@1.4.0 + + - name: start Kafka and Zookeeper + run: docker compose -f scripts/bitnami-kafka-docker-compose.yml up -d + + - name: is Kafka running? + run: docker ps -a + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + + - name: Install + shell: bash -l {0} + run: | + set -vxeuo pipefail + pip install --upgrade pip wheel + pip install . + pip install -r requirements-dev.txt + pip list + + - name: Add src to PYTHONPATH + run: echo "PYTHONPATH=$PWD/src" >> $GITHUB_ENV + + - name: Test with pytest + shell: bash -l {0} + run: | + set -vxeuo pipefail + coverage run -m pytest -s -v + coverage report diff --git a/.gitignore b/.gitignore index fdef9704..974545eb 100644 --- a/.gitignore +++ b/.gitignore @@ -109,4 +109,4 @@ ENV/ .mypy_cache/ # -.DS_Store \ No newline at end of file +.DS_Store diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 51e5ee2c..89b3e001 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,24 +1,83 @@ +ci: + autoupdate_commit_msg: "chore: update pre-commit hooks" + autofix_commit_msg: "style: pre-commit fixes" + +exclude: ^.cruft.json|.copier-answers.yml$ + repos: + - repo: https://github.com/adamchainz/blacken-docs + rev: "1.19.1" + hooks: + - id: blacken-docs + additional_dependencies: [black==24.*] + - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v5.0.0 + rev: "v5.0.0" hooks: - id: check-added-large-files - - id: check-yaml + - id: check-case-conflict - id: check-merge-conflict + - id: check-symlinks + - id: check-yaml + - id: debug-statements - id: end-of-file-fixer + - id: mixed-line-ending + - id: name-tests-test + args: ["--pytest-test-first"] + - id: requirements-txt-fixer + - id: trailing-whitespace - - repo: local + - repo: https://github.com/pre-commit/pygrep-hooks + rev: "v1.10.0" + hooks: + - id: rst-backticks + - id: rst-directive-colons + - id: rst-inline-touching-normal + + - repo: https://github.com/rbubley/mirrors-prettier + rev: "v3.6.2" hooks: - - id: ruff - name: lint with ruff - language: system - entry: ruff check --force-exclude - types: [python] - require_serial: true + - id: prettier + types_or: [yaml, markdown, html, css, scss, javascript, json] + args: [--prose-wrap=always] + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: "v0.12.2" + hooks: + - id: ruff-check + args: ["--fix", "--show-fixes"] - id: ruff-format - name: format with ruff - language: system - entry: ruff format --force-exclude - types: [python] - require_serial: true + + - repo: https://github.com/codespell-project/codespell + rev: "v2.4.1" + hooks: + - id: codespell + args: [--ignore-words-list=inpt, INPU, NOE, NOO] + additional_dependencies: + - tomli; python_version<'3.11' + + - repo: https://github.com/shellcheck-py/shellcheck-py + rev: "v0.10.0.1" + hooks: + - id: shellcheck + + - repo: local + hooks: + - id: disallow-caps + name: Disallow improper capitalization + language: pygrep + entry: PyBind|Numpy|Cmake|CCache|Github|PyTest + exclude: .pre-commit-config.yaml + + - repo: https://github.com/abravalheri/validate-pyproject + rev: "v0.24.1" + hooks: + - id: validate-pyproject + additional_dependencies: ["validate-pyproject-schema-store[all]"] + + - repo: https://github.com/python-jsonschema/check-jsonschema + rev: "0.33.2" + hooks: + - id: check-dependabot + - id: check-github-workflows + - id: check-readthedocs diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 00000000..172d2d8b --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,16 @@ +# Read the Docs configuration file +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details + +version: 2 + +build: + os: ubuntu-24.04 + tools: + python: "3.13" + commands: + - asdf plugin add uv + - asdf install uv latest + - asdf global uv latest + - uv sync --group docs + - uv run python -m sphinx -T -b html -d docs/_build/doctrees -D language=en + docs $READTHEDOCS_OUTPUT/html diff --git a/.travis.yml b/.travis.yml index eff4d384..e8a0f337 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,14 +6,14 @@ services: - docker env: - global: + global: # Doctr deploy key for NSLS-II/nslsii - secure: "FhNkkbod0Wc/zUf9cTvwziAYHcjfte2POf+hoVSmC+v/RcYKCNCo+mGGMhF9F4KyC2nzvulfzow7YXoswZqav4+TEEu+mpuPaGlf9aqp8V61eij8MVTwonzQEYmHAy3KatwXxyvvhQpfj3gOuDVolfOg2MtNZi6QERES4E1sjOn714fx2HkVxqH2Y8/PF/FzzGeJaRlVaVci0EdIJ5Ss5c5SjO6JGgxj4hzhTPHjTaLjdLHlVhuB9Yatl80zbhGriljLcDQTHmoSODwBpAh5YLDUZq6B9vomaNB9Hb3e0D5gItjOdj53v6AsHU8LkncZMvsgJgh2sZZqMO6nkpHcYPwJgbPbKd3RtVlk6Kg/tvKQk0rMcxl5fFFeD2i9POnANg/xJsKN6yAEY3kaRwQtajQmlcicSa/wdwv9NhUTtBmA/mnyzxHbQXrB0bEc2P2QVu7U8en6dWaOAqc1VCMrWIhp2ADNWb7JZhYj70TgmExIU3UH8qlMb6dyx50SJUE9waJj3fiiZVkjh+E568ZRSMvL9n+bLlFt4uDT4AysSby6cj+zjfNViKFstTAqjyd5VJEvCoUu73vNzWEiWFtEvKKVL1P3pbLN/G3aSSJMa5fc1o+2lRUwdwNNOOdH6iKBDZGNpE8nGDlTP2b2dhFyEt8nICKJhbgU208jhyyH8Vk=" cache: directories: - $HOME/.cache/pip - - $HOME/.ccache # https://github.com/travis-ci/travis-ci/issues/5853 + - $HOME/.ccache # https://github.com/travis-ci/travis-ci/issues/5853 matrix: fast_finish: true @@ -46,11 +46,11 @@ before_script: sleep 20 script: - - coverage run -m pytest # Run the tests and check for test coverage. - - coverage report -m # Generate test coverage report. - - codecov # Upload the report to codecov. + - coverage run -m pytest # Run the tests and check for test coverage. + - coverage report -m # Generate test coverage report. + - codecov # Upload the report to codecov. - flake8 - - set -e # Stop here if anything fails above + - set -e # Stop here if anything fails above #commenting out the lines below until there are docs to build. # - make -C docs html # Build the documentation # - pip install doctr diff --git a/LICENSE b/LICENSE index a206536e..e2a872a6 100644 --- a/LICENSE +++ b/LICENSE @@ -6,16 +6,11 @@ All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. -3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. +3. Neither the name of the vector package developers nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE diff --git a/README.md b/README.md index c8630f2c..f504c985 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Repository of tools used for both data collection and analysis at NSLS-II. This is a home for facility-wide tools: code that is generalized for use at multiple beamlines but not necessarily generalized for use at multiple -facilties. +facilities. For an overview of the NSLS-II software see the [NSLS2 software overview](http://nsls-ii.github.io). diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 00000000..de111b4b --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +import importlib.metadata +from typing import Any + +project = "nslsii" +copyright = "2025, NSLS2" +author = "NSLS2" +version = release = importlib.metadata.version("nslsii") + +extensions = [ + "myst_parser", + "sphinx.ext.autodoc", + "sphinx.ext.intersphinx", + "sphinx.ext.mathjax", + "sphinx.ext.napoleon", + "sphinx_autodoc_typehints", + "sphinx_copybutton", +] + +source_suffix = [".rst", ".md"] +exclude_patterns = [ + "_build", + "**.ipynb_checkpoints", + "Thumbs.db", + ".DS_Store", + ".env", + ".venv", +] + +html_theme = "furo" + +html_theme_options: dict[str, Any] = { + "footer_icons": [ + { + "name": "GitHub", + "url": "https://github.com/NSLS-II/nslsii", + "html": """ + + + + """, + "class": "", + }, + ], + "source_repository": "https://github.com/NSLS-II/nslsii", + "source_branch": "main", + "source_directory": "docs/", +} + +myst_enable_extensions = [ + "colon_fence", +] + +intersphinx_mapping = { + "python": ("https://docs.python.org/3", None), +} + +nitpick_ignore = [ + ("py:class", "_io.StringIO"), + ("py:class", "_io.BytesIO"), +] + +always_document_param_types = True diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 00000000..ca54b2f2 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,17 @@ +# nslsii + +```{toctree} +:maxdepth: 2 +:hidden: + +``` + +```{include} ../README.md +:start-after: +``` + +## Indices and tables + +- {ref}`genindex` +- {ref}`modindex` +- {ref}`search` diff --git a/docs/source/release-history.rst b/docs/source/release-history.rst index 5a68d7e1..5f0a5522 100644 --- a/docs/source/release-history.rst +++ b/docs/source/release-history.rst @@ -32,9 +32,9 @@ v0.10.7 (2024-10-30) ==================== What's Changed .............. -* CI: only use the `published` event for PyPI releases by `@mrakitin `_ in https://github.com/NSLS-II/nslsii/pull/203 +* CI: only use the ``published`` event for PyPI releases by `@mrakitin `_ in https://github.com/NSLS-II/nslsii/pull/203 * Remove 'finally' that is eating exceptions by `@nmaytan `_ in https://github.com/NSLS-II/nslsii/pull/200 -* Use a configuration file from `n2sn_user_tools` for `sync-experiment` by `@mrakitin `_ in https://github.com/NSLS-II/nslsii/pull/202 +* Use a configuration file from ``n2sn_user_tools`` for ``sync-experiment`` by `@mrakitin `_ in https://github.com/NSLS-II/nslsii/pull/202 * Deprecate the webcam class by `@mrakitin `_ in https://github.com/NSLS-II/nslsii/pull/204 @@ -68,7 +68,7 @@ v0.10.4 (2024-09-18) ==================== * Add SRX MAIA code * Remove distutils -* Fix sync_experiment for SST +* Fix sync_experiment for SST * Fix docker compose usage v0.10.3 (2024-06-28) @@ -98,7 +98,7 @@ v0.9.1 (2023-06-08) v0.9.0 (2023-01-20) =================== -* fix incorrect usage of ``prefix=`` keyword argument in tests +* fix incorrect usage of ``prefix=`` keyword argument in tests * add ``nslsii.areadetector.xspress3.Xspress3ExternalFileReference.dtype_str`` v0.8.0 (2022-12-19) diff --git a/github_deploy_key_nsls_ii_nslsii.enc b/github_deploy_key_nsls_ii_nslsii.enc index 88f7ef24..c52e2bde 100644 --- a/github_deploy_key_nsls_ii_nslsii.enc +++ b/github_deploy_key_nsls_ii_nslsii.enc @@ -1 +1 @@ -gAAAAABbxz01GnyDC8lnHpPlT8i32N3mm2qpw6kSutu50zS_DzikWfBA2IdZtNwROhcddRSgExw8Mr0u254TMM_2jgN_c4GnMar40MjLD_sogS0ZF82vB0p_UTJqzAwimo1euMPalDqBvkoNasnRBz5mCIsrNsbE2QF3zuXqNM0EzTfgcie4f6xGo6C3PfNrxaZUqmlvt4GV5nle4wm7pD58BGiFwkXBqYB8uC6YC4NvkR-iR7jJonldxvcuspM6VZRlPAV7oIG2XTgouY0N3vIRaDpc595xqQwqooHGN9b-dWKWPU7q1dLbrz9SNuqJNtZaP0Q3md5eXdw_6rw9Lbq5GjEsSqhi1PRT8lQFByPNBnfZWGcNkMubjaMwq9psOQwl3dXdLHH-tGBnyB2DSRDdiyZ4nWgVt9SmHvnmvcapZUOjEStLjHkSjQBVb3lfIs7HamuU2TUMPJAUIRmvzKpmVX8m98A1seFlapJSU-6f23nJjAabHBnpJjSvw8ifuR2qWaNgBlVZrNs2neMpP7DgYdNAK-iE-inoDx3KsHb2ZidebxTLsS74ZifCWNA_Oz0QJLOuym2yYrKfdIde3VKnP20lHVYXyqcaBWcgOS70G33C-_vpm6fMnXx5uuRpnDi8bAoZI8IEd7Dq709VJ0YKVV32PYPfr6bjUdE64rdXn2Txl-7dtgV3OweivHqH63AoQ87-bl-uqFj81tVRmix-4WoHyEGMwhOW7ZkJcuDa0FwnS6Wg7NMBY2AbhcIDIq5p7wl-0oAtP9YCOG0gjPIn_L2SHWzFR_iNDbKvlHcucLjwczQOnWm9FSnldE0u3-tHJ8PSE9xhsuUGndT8bVTXE7q-GVmBFUsD9BxwfrOkeASmTd7TclxqSM-5OMRaAGF6_giqXLKrlREL-RihQRPreVpzEL9F25qczepGAjpA6GJ6j4WHDJR8UnXIZLoscieTuFzVrvbhcP0aMpSuNP6UaMrsiN1vNM72WDJuATkHiPyzwnWbUc-nIXUv5LO-ejTruO60YhmZRdRnvrstAFYHQyzJqkiEeeHSKVwIBOci2m60C0-5-5VvbkHXhAAtocqWeyS8xLVr2cSYuS3bZfHzK-GEizGsDFgVj4KIV4xxDeXEUxSdclQ933lw4kfr_IuvXIqgexhBvu9MLThLRAh0nDS_zFN4VyLXfGtg-0RuAtYbK7XQo-M9Dq4s3nDhHnDaPhN0KU617nDSJXIp-N0t4QR-W373QWo4EoVGSC0STD2leqB3atf8c1MNheix97ssqxfs9VX_1RJFtR4v8pXHyekGfqbmQllPBuTu8UH89Larjquo7ABUtGUriB2gm9ag8DjP5xf23hz-Ab9SJD0CBKMwb9H7U4K08pLv6JbcsGhbbqG6_erQYlNWYoI7kKgIT_5BmUFKaFt5mmC-a84XaegF2njZuls3k-z8Yp79yWQvEyPv9w0HJXurYeHzZL1NiF8Am-GKNpcSTa3U_sIG-VxjzBW-Q8pC1mRqTFkTXGTJ6rYSKXlN0VzWvn86ixILAbyF-tbvw9SOK8RdmNy4maqVubWXf_ojpKl7cq3TSAsK-TjntgFbCUz5XjsH57Aq4dzztBlIdXl7P_65ujlgqqq1nl7DvZX5Z50vPNFXukfgvixjH9qO-wiXE1Iy65IntINZb4CAbGwWWkftVbBaaooFW7O8ZJoQ66yM7psP0Ex-F2gDYWFX7QNRpPtTccoAoOfL23_PjVDMHp1kyRD3mha6yF4n4hBQ5JHtGg9nKQlZlED9zSL-Tf-dRJ_j1MGVdgrPJf09Uu7IMNE8-G_ULQz2cLuPrTHKdAFskeiJ6jeUfCtG-TorVetqwrjM2rfuTZHYnR1hBhn6sHk1PB0T-3N-XWwrKApdBFFiGYqN3ErT_7E5MS6QxyoX0Bonjm1vIUSVq0Jzdz3tBLOGecTkKGWi6jFC420Mw4M-SZtUFi3tQ8Hc2SNpmmHyq2GGqEQEklcXqoo69U_zzzQqyDLzOfCVDSoVBEzB6zR6CeWAhwICo0OVA2uLKWeKPp3_oe74TLzIgwVwbHJXGFPyI5MUFHAJL2Vjys-LB_kds4Ar5cOIoBbhfb2CoTn88M5nsu1LJbjjacBwmlCvcqyNhMngf6wxVr6PFDQsEmY1Fk_OS7cnAmdtM9OTkMhdV4o02v78VJD47tNT9J4BaGmwunxEygQHy5pnPqrfjnbdFXpV56Pa-yc_glwhd3NJsk5ZWAQVCZWQtuR6b-nLRO3r0fQo5ROpuTCidRhGgh7w7WTzcdDnPygdMBchaBzBj6TiWOKadJzhORKBKLiOdHlcircJeg1naraFkkp6hf0yaTZ-d3IMz69mS5BmLw4evkbHkG8h6w2dQFUMBRrc5a3A8Wp79IGxvoyOws7oTbad7ZwQn-dEWvILaNEBARK0hopOa8q2pOGLJcvkc_GtvE4ddWo_69q7-KhtN4gKfYLlWnOQryHouqVrt1FXge6qDRRalGMJADrFJdeHsCcbarV16K6tPzyXK87XyW1GoJC6fLToFXcU4G4RxB4QKyYbwWbYs4jc4VSD1lBuobDIYy0blFYoCay5OmPAAZGYbStB11C2s28cXCL_BouwsI2_V6HrDBtNy1xYV_IUIuUkNJtEMR3RVGpq_yPpaIENqDcUCFqXUE6h4HZ1dklFxSjBHLUX39tAAs7rE-CxTXcQkjFevXaSw2dLLMEFHk0OIdCUu10RmG2GPSatLzjsgjfcvSGvj1lt-Tu3SZxnZxGJitEKHCh923QHHfvLqRAEqybJV4pxnq2VsFtsfdtJPUH6zWAEnDjKI5bz9YyCDYQhI0AobvfMPDGz_t8VTREYMb1FXqYMZdGb3s_9o6skkz4McziyKhvq2_bWfmcwD5MN7TNUIX8ATHq7NWQUvQFDedbkE7ju5jDe3CvzLAbidpkfDDKhlAnLh46PN_wDk_xWnID46-aMiCNgYZOYUn59uiq6mgnnMYpPWAAbRpMsRlYWN-l3qXQB82RoiM_OhbOne7co39swWxnjWDRS9vahAcAVE_olQ-HGQRkRjH7kWI4uXjEejn6JT_s-3-MKB8GSkyNn0_RZAFlJiD042ZAd1zrwS-ZXGkDTwA48yNtbDkrfGcUhttM3ZKdV5SSQG19UnjxE6o8uHIPWPyvsW4TYjHJlTXc09jZA4ueUO71G2j9pVZIGU4nyDux2TXsgePQPNdL04zB4MUjEVX5mbfYWQceMassn_iTldJZrZtJEfEJvUl3mESlyA21ryy7TI2u8GKL8Mic4JkbEgBDTk0p4PohxIlyorEbO_7g7E4MUhqE9Qh1Sta-flBAD0iehcTJ8Yoekb2tDDpTRhTN-25m0zqR8mjTI4KvYsH4QJObfATsTGYyBHi7QJNmuNlw6601PoL8gf0RWMQGDjp5qjba-2y3l2fjBy1wAQj29ltY4rqpT5McUu1UDVOoR9hByvZH4vLA1eLdAPTqE_IaFXfGVqIHyovTPWfJUweWzqrj0g0gV1LQr-9UvofFWPX5ngGumzsXtLY-TQa9J7N9C-jkVRUIh9n0VHxm-w1INF0QVkqtBSgpE-BK6pU_-lhoMdyfMtVIRA_Z1ieikX2xtb2zNuUj0mqqumYjNSDoFfLEvzSX847lzVUNUqkyIBCi5R5g6Vu8kdIXsO6Wyb89QIuRWZu-mnLOtAi7ebnNurjpQXL9LQLmOkOmrNonKUH6e4IeJNscPl3dffnyjCZxYx3z4Xtjh4mLn6n50lnEBu2X28X_elyni3OgnnwOnmgGmKMKlCmVJ6_yciNx5SBxH3GScyminSSNoeLTmlHjjxeP2NZx8fYrwgf5j2gj8rYSkHYL2CiTtLN-mK-DbCkja8f7MivR-5onIwTtG6Jmh_H_80HCcGSOWHTEyfJD7DhhdKhJyMTq9xp-B6ZCS3bz7AhXEbvVtuMYBIPbxjdrhdv5uctQ3GYB72DJfKoaiCUnfvy_HRxayed1UswYDT6eA55BZHLC9gFAHMt1pmqV2bqxooDxfpTlPXBdfvHqphI3CVz4qIPK5chsdVC19aOh3pQrximlB_5qJAcNCZ3xtqyPO1Rf3sh53elsXW7gwhgzbPLe0opjexYDAC0OMiH_YJOZ4QVhu69SLc_jjfBH3D55qEg6r_AVETCCnNfF3iZwagkj75_aT24kr-W9vBVOctn3RngoKGsCYQvqZDTPSHjRpbsXe2pd7-a8tMRMXFaar7rBiXkeRjMkUxQuA5uxDKG1Fh-fpLmJU9haNmOL3xSysFu2Ep6eNbGYZ3djHKoHOL2kQYPEBIZ17R1tcO5DWgIxo0AQN4WOW5JkJh1s4CMtQAmDa7yRhDI49nQ8UByC1BIKgP1NJ99kD4wxS0IUHZ90zPcDq59UhtI1Xkr8J99Enp6u5Y1Qnhaf0l1WBo8O4qvHkRQl9oP8KfUz642S46w== \ No newline at end of file +gAAAAABbxz01GnyDC8lnHpPlT8i32N3mm2qpw6kSutu50zS_DzikWfBA2IdZtNwROhcddRSgExw8Mr0u254TMM_2jgN_c4GnMar40MjLD_sogS0ZF82vB0p_UTJqzAwimo1euMPalDqBvkoNasnRBz5mCIsrNsbE2QF3zuXqNM0EzTfgcie4f6xGo6C3PfNrxaZUqmlvt4GV5nle4wm7pD58BGiFwkXBqYB8uC6YC4NvkR-iR7jJonldxvcuspM6VZRlPAV7oIG2XTgouY0N3vIRaDpc595xqQwqooHGN9b-dWKWPU7q1dLbrz9SNuqJNtZaP0Q3md5eXdw_6rw9Lbq5GjEsSqhi1PRT8lQFByPNBnfZWGcNkMubjaMwq9psOQwl3dXdLHH-tGBnyB2DSRDdiyZ4nWgVt9SmHvnmvcapZUOjEStLjHkSjQBVb3lfIs7HamuU2TUMPJAUIRmvzKpmVX8m98A1seFlapJSU-6f23nJjAabHBnpJjSvw8ifuR2qWaNgBlVZrNs2neMpP7DgYdNAK-iE-inoDx3KsHb2ZidebxTLsS74ZifCWNA_Oz0QJLOuym2yYrKfdIde3VKnP20lHVYXyqcaBWcgOS70G33C-_vpm6fMnXx5uuRpnDi8bAoZI8IEd7Dq709VJ0YKVV32PYPfr6bjUdE64rdXn2Txl-7dtgV3OweivHqH63AoQ87-bl-uqFj81tVRmix-4WoHyEGMwhOW7ZkJcuDa0FwnS6Wg7NMBY2AbhcIDIq5p7wl-0oAtP9YCOG0gjPIn_L2SHWzFR_iNDbKvlHcucLjwczQOnWm9FSnldE0u3-tHJ8PSE9xhsuUGndT8bVTXE7q-GVmBFUsD9BxwfrOkeASmTd7TclxqSM-5OMRaAGF6_giqXLKrlREL-RihQRPreVpzEL9F25qczepGAjpA6GJ6j4WHDJR8UnXIZLoscieTuFzVrvbhcP0aMpSuNP6UaMrsiN1vNM72WDJuATkHiPyzwnWbUc-nIXUv5LO-ejTruO60YhmZRdRnvrstAFYHQyzJqkiEeeHSKVwIBOci2m60C0-5-5VvbkHXhAAtocqWeyS8xLVr2cSYuS3bZfHzK-GEizGsDFgVj4KIV4xxDeXEUxSdclQ933lw4kfr_IuvXIqgexhBvu9MLThLRAh0nDS_zFN4VyLXfGtg-0RuAtYbK7XQo-M9Dq4s3nDhHnDaPhN0KU617nDSJXIp-N0t4QR-W373QWo4EoVGSC0STD2leqB3atf8c1MNheix97ssqxfs9VX_1RJFtR4v8pXHyekGfqbmQllPBuTu8UH89Larjquo7ABUtGUriB2gm9ag8DjP5xf23hz-Ab9SJD0CBKMwb9H7U4K08pLv6JbcsGhbbqG6_erQYlNWYoI7kKgIT_5BmUFKaFt5mmC-a84XaegF2njZuls3k-z8Yp79yWQvEyPv9w0HJXurYeHzZL1NiF8Am-GKNpcSTa3U_sIG-VxjzBW-Q8pC1mRqTFkTXGTJ6rYSKXlN0VzWvn86ixILAbyF-tbvw9SOK8RdmNy4maqVubWXf_ojpKl7cq3TSAsK-TjntgFbCUz5XjsH57Aq4dzztBlIdXl7P_65ujlgqqq1nl7DvZX5Z50vPNFXukfgvixjH9qO-wiXE1Iy65IntINZb4CAbGwWWkftVbBaaooFW7O8ZJoQ66yM7psP0Ex-F2gDYWFX7QNRpPtTccoAoOfL23_PjVDMHp1kyRD3mha6yF4n4hBQ5JHtGg9nKQlZlED9zSL-Tf-dRJ_j1MGVdgrPJf09Uu7IMNE8-G_ULQz2cLuPrTHKdAFskeiJ6jeUfCtG-TorVetqwrjM2rfuTZHYnR1hBhn6sHk1PB0T-3N-XWwrKApdBFFiGYqN3ErT_7E5MS6QxyoX0Bonjm1vIUSVq0Jzdz3tBLOGecTkKGWi6jFC420Mw4M-SZtUFi3tQ8Hc2SNpmmHyq2GGqEQEklcXqoo69U_zzzQqyDLzOfCVDSoVBEzB6zR6CeWAhwICo0OVA2uLKWeKPp3_oe74TLzIgwVwbHJXGFPyI5MUFHAJL2Vjys-LB_kds4Ar5cOIoBbhfb2CoTn88M5nsu1LJbjjacBwmlCvcqyNhMngf6wxVr6PFDQsEmY1Fk_OS7cnAmdtM9OTkMhdV4o02v78VJD47tNT9J4BaGmwunxEygQHy5pnPqrfjnbdFXpV56Pa-yc_glwhd3NJsk5ZWAQVCZWQtuR6b-nLRO3r0fQo5ROpuTCidRhGgh7w7WTzcdDnPygdMBchaBzBj6TiWOKadJzhORKBKLiOdHlcircJeg1naraFkkp6hf0yaTZ-d3IMz69mS5BmLw4evkbHkG8h6w2dQFUMBRrc5a3A8Wp79IGxvoyOws7oTbad7ZwQn-dEWvILaNEBARK0hopOa8q2pOGLJcvkc_GtvE4ddWo_69q7-KhtN4gKfYLlWnOQryHouqVrt1FXge6qDRRalGMJADrFJdeHsCcbarV16K6tPzyXK87XyW1GoJC6fLToFXcU4G4RxB4QKyYbwWbYs4jc4VSD1lBuobDIYy0blFYoCay5OmPAAZGYbStB11C2s28cXCL_BouwsI2_V6HrDBtNy1xYV_IUIuUkNJtEMR3RVGpq_yPpaIENqDcUCFqXUE6h4HZ1dklFxSjBHLUX39tAAs7rE-CxTXcQkjFevXaSw2dLLMEFHk0OIdCUu10RmG2GPSatLzjsgjfcvSGvj1lt-Tu3SZxnZxGJitEKHCh923QHHfvLqRAEqybJV4pxnq2VsFtsfdtJPUH6zWAEnDjKI5bz9YyCDYQhI0AobvfMPDGz_t8VTREYMb1FXqYMZdGb3s_9o6skkz4McziyKhvq2_bWfmcwD5MN7TNUIX8ATHq7NWQUvQFDedbkE7ju5jDe3CvzLAbidpkfDDKhlAnLh46PN_wDk_xWnID46-aMiCNgYZOYUn59uiq6mgnnMYpPWAAbRpMsRlYWN-l3qXQB82RoiM_OhbOne7co39swWxnjWDRS9vahAcAVE_olQ-HGQRkRjH7kWI4uXjEejn6JT_s-3-MKB8GSkyNn0_RZAFlJiD042ZAd1zrwS-ZXGkDTwA48yNtbDkrfGcUhttM3ZKdV5SSQG19UnjxE6o8uHIPWPyvsW4TYjHJlTXc09jZA4ueUO71G2j9pVZIGU4nyDux2TXsgePQPNdL04zB4MUjEVX5mbfYWQceMassn_iTldJZrZtJEfEJvUl3mESlyA21ryy7TI2u8GKL8Mic4JkbEgBDTk0p4PohxIlyorEbO_7g7E4MUhqE9Qh1Sta-flBAD0iehcTJ8Yoekb2tDDpTRhTN-25m0zqR8mjTI4KvYsH4QJObfATsTGYyBHi7QJNmuNlw6601PoL8gf0RWMQGDjp5qjba-2y3l2fjBy1wAQj29ltY4rqpT5McUu1UDVOoR9hByvZH4vLA1eLdAPTqE_IaFXfGVqIHyovTPWfJUweWzqrj0g0gV1LQr-9UvofFWPX5ngGumzsXtLY-TQa9J7N9C-jkVRUIh9n0VHxm-w1INF0QVkqtBSgpE-BK6pU_-lhoMdyfMtVIRA_Z1ieikX2xtb2zNuUj0mqqumYjNSDoFfLEvzSX847lzVUNUqkyIBCi5R5g6Vu8kdIXsO6Wyb89QIuRWZu-mnLOtAi7ebnNurjpQXL9LQLmOkOmrNonKUH6e4IeJNscPl3dffnyjCZxYx3z4Xtjh4mLn6n50lnEBu2X28X_elyni3OgnnwOnmgGmKMKlCmVJ6_yciNx5SBxH3GScyminSSNoeLTmlHjjxeP2NZx8fYrwgf5j2gj8rYSkHYL2CiTtLN-mK-DbCkja8f7MivR-5onIwTtG6Jmh_H_80HCcGSOWHTEyfJD7DhhdKhJyMTq9xp-B6ZCS3bz7AhXEbvVtuMYBIPbxjdrhdv5uctQ3GYB72DJfKoaiCUnfvy_HRxayed1UswYDT6eA55BZHLC9gFAHMt1pmqV2bqxooDxfpTlPXBdfvHqphI3CVz4qIPK5chsdVC19aOh3pQrximlB_5qJAcNCZ3xtqyPO1Rf3sh53elsXW7gwhgzbPLe0opjexYDAC0OMiH_YJOZ4QVhu69SLc_jjfBH3D55qEg6r_AVETCCnNfF3iZwagkj75_aT24kr-W9vBVOctn3RngoKGsCYQvqZDTPSHjRpbsXe2pd7-a8tMRMXFaar7rBiXkeRjMkUxQuA5uxDKG1Fh-fpLmJU9haNmOL3xSysFu2Ep6eNbGYZ3djHKoHOL2kQYPEBIZ17R1tcO5DWgIxo0AQN4WOW5JkJh1s4CMtQAmDa7yRhDI49nQ8UByC1BIKgP1NJ99kD4wxS0IUHZ90zPcDq59UhtI1Xkr8J99Enp6u5Y1Qnhaf0l1WBo8O4qvHkRQl9oP8KfUz642S46w== diff --git a/noxfile.py b/noxfile.py new file mode 100644 index 00000000..62f165d6 --- /dev/null +++ b/noxfile.py @@ -0,0 +1,109 @@ +from __future__ import annotations + +import argparse +import shutil +from pathlib import Path + +import nox + +DIR = Path(__file__).parent.resolve() +PROJECT = nox.project.load_toml() + +nox.needs_version = ">=2025.2.9" +nox.options.default_venv_backend = "uv|virtualenv" + + +@nox.session +def lint(session: nox.Session) -> None: + """ + Run the linter. + """ + session.install("pre-commit") + session.run( + "pre-commit", "run", "--all-files", "--show-diff-on-failure", *session.posargs + ) + + +@nox.session +def pylint(session: nox.Session) -> None: + """ + Run Pylint. + """ + # This needs to be installed into the package environment, and is slower + # than a pre-commit check + session.install("-e.", "pylint>=3.2") + session.run("pylint", "nslsii", *session.posargs) + + +@nox.session +def tests(session: nox.Session) -> None: + """ + Run the unit and regular tests. + """ + test_deps = nox.project.dependency_groups(PROJECT, "test") + session.install("-e.", *test_deps) + session.run("pytest", *session.posargs) + + +@nox.session(reuse_venv=True, default=False) +def docs(session: nox.Session) -> None: + """ + Build the docs. Pass --non-interactive to avoid serving. First positional argument is the target directory. + """ + + doc_deps = nox.project.dependency_groups(PROJECT, "docs") + parser = argparse.ArgumentParser() + parser.add_argument( + "-b", dest="builder", default="html", help="Build target (default: html)" + ) + parser.add_argument("output", nargs="?", help="Output directory") + args, posargs = parser.parse_known_args(session.posargs) + serve = args.builder == "html" and session.interactive + + session.install("-e.", *doc_deps, "sphinx-autobuild") + + shared_args = ( + "-n", # nitpicky mode + "-T", # full tracebacks + f"-b={args.builder}", + "docs", + args.output or f"docs/_build/{args.builder}", + *posargs, + ) + + if serve: + session.run("sphinx-autobuild", "--open-browser", *shared_args) + else: + session.run("sphinx-build", "--keep-going", *shared_args) + + +@nox.session(default=False) +def build_api_docs(session: nox.Session) -> None: + """ + Build (regenerate) API docs. + """ + + session.install("sphinx") + session.run( + "sphinx-apidoc", + "-o", + "docs/api/", + "--module-first", + "--no-toc", + "--force", + "src/nslsii", + ) + + +@nox.session(default=False) +def build(session: nox.Session) -> None: + """ + Build an SDist and wheel. + """ + + build_path = DIR.joinpath("build") + if build_path.exists(): + shutil.rmtree(build_path) + + session.install("build") + session.run("python", "-m", "build") diff --git a/nslsii/ad33.py b/nslsii/ad33.py deleted file mode 100644 index e7ecb97b..00000000 --- a/nslsii/ad33.py +++ /dev/null @@ -1,242 +0,0 @@ -"""Classes to help with supporting AreaDetector 33 (and the -wait_for_plugins functionality) - - -This is actually adding a mix of functionality from AD 2-2 to 3-3 and -all of these names may change in the future. - -""" - -from ophyd import Device, Component as Cpt -from ophyd.areadetector.base import (ADBase, ADComponent as ADCpt, ad_group, - EpicsSignalWithRBV as SignalWithRBV) -from ophyd.areadetector.plugins import PluginBase -from ophyd.areadetector.trigger_mixins import TriggerBase, ADTriggerStatus -from ophyd.device import DynamicDeviceComponent as DDC, Staged -from ophyd.signal import (Signal, EpicsSignalRO, EpicsSignal) -from ophyd.quadem import QuadEM - -import time as ttime - - -class V22Mixin(Device): - ... - - -class V26Mixin(V22Mixin): - adcore_version = Cpt(EpicsSignalRO, 'ADCoreVersion_RBV', - string=True, kind='config') - driver_version = Cpt(EpicsSignalRO, 'DriverVersion_RBV', - string=True, kind='config') - - -class V33Mixin(V26Mixin): - ... - - -class CamV33Mixin(V33Mixin): - wait_for_plugins = Cpt(EpicsSignal, 'WaitForPlugins', - string=True, kind='config') - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.stage_sigs['wait_for_plugins'] = 'Yes' - - def ensure_nonblocking(self): - self.stage_sigs['wait_for_plugins'] = 'Yes' - for c in self.parent.component_names: - cpt = getattr(self.parent, c) - if cpt is self: - continue - if hasattr(cpt, 'ensure_nonblocking'): - cpt.ensure_nonblocking() - - -class FilePluginV22Mixin(V22Mixin): - create_directories = Cpt(EpicsSignal, - 'CreateDirectory', kind='config') - - -class SingleTriggerV33(TriggerBase): - _status_type = ADTriggerStatus - - def __init__(self, *args, image_name=None, **kwargs): - super().__init__(*args, **kwargs) - if image_name is None: - image_name = '_'.join([self.name, 'image']) - self._image_name = image_name - - def trigger(self): - "Trigger one acquisition." - if self._staged != Staged.yes: - raise RuntimeError("This detector is not ready to trigger." - "Call the stage() method before triggering.") - - self._status = self._status_type(self) - - def _acq_done(*args, **kwargs): - # TODO sort out if anything useful in here - self._status._finished() - - self._acquisition_signal.put(1, use_complete=True, callback=_acq_done) - self.generate_datum(self._image_name, ttime.time(), {}) - return self._status - - -class StatsPluginV33(PluginBase): - """This supports changes to time series PV names in AD 3-3 - - Due to https://github.com/areaDetector/ADCore/pull/333 - """ - _default_suffix = 'Stats1:' - _suffix_re = r'Stats\d:' - _html_docs = ['NDPluginStats.html'] - _plugin_type = 'NDPluginStats' - - _default_configuration_attrs = (PluginBase._default_configuration_attrs + ( - 'centroid_threshold', 'compute_centroid', 'compute_histogram', - 'compute_profiles', 'compute_statistics', 'bgd_width', - 'hist_size', 'hist_min', 'hist_max', 'ts_num_points', 'profile_size', - 'profile_cursor') - ) - - bgd_width = ADCpt(SignalWithRBV, 'BgdWidth') - centroid_threshold = ADCpt(SignalWithRBV, 'CentroidThreshold') - - centroid = DDC(ad_group(EpicsSignalRO, - (('x', 'CentroidX_RBV'), - ('y', 'CentroidY_RBV'))), - doc='The centroid XY', - default_read_attrs=('x', 'y')) - - compute_centroid = ADCpt(SignalWithRBV, 'ComputeCentroid', string=True) - compute_histogram = ADCpt(SignalWithRBV, 'ComputeHistogram', string=True) - compute_profiles = ADCpt(SignalWithRBV, 'ComputeProfiles', string=True) - compute_statistics = ADCpt(SignalWithRBV, 'ComputeStatistics', string=True) - - cursor = DDC(ad_group(SignalWithRBV, - (('x', 'CursorX'), - ('y', 'CursorY'))), - doc='The cursor XY', - default_read_attrs=('x', 'y')) - - hist_entropy = ADCpt(EpicsSignalRO, 'HistEntropy_RBV') - hist_max = ADCpt(SignalWithRBV, 'HistMax') - hist_min = ADCpt(SignalWithRBV, 'HistMin') - hist_size = ADCpt(SignalWithRBV, 'HistSize') - histogram = ADCpt(EpicsSignalRO, 'Histogram_RBV') - - max_size = DDC(ad_group(EpicsSignal, - (('x', 'MaxSizeX'), - ('y', 'MaxSizeY'))), - doc='The maximum size in XY', - default_read_attrs=('x', 'y')) - - max_value = ADCpt(EpicsSignalRO, 'MaxValue_RBV') - max_xy = DDC(ad_group(EpicsSignalRO, - (('x', 'MaxX_RBV'), - ('y', 'MaxY_RBV'))), - doc='Maximum in XY', - default_read_attrs=('x', 'y')) - - mean_value = ADCpt(EpicsSignalRO, 'MeanValue_RBV') - min_value = ADCpt(EpicsSignalRO, 'MinValue_RBV') - - min_xy = DDC(ad_group(EpicsSignalRO, - (('x', 'MinX_RBV'), - ('y', 'MinY_RBV'))), - doc='Minimum in XY', - default_read_attrs=('x', 'y')) - - net = ADCpt(EpicsSignalRO, 'Net_RBV') - profile_average = DDC(ad_group(EpicsSignalRO, - (('x', 'ProfileAverageX_RBV'), - ('y', 'ProfileAverageY_RBV'))), - doc='Profile average in XY', - default_read_attrs=('x', 'y')) - - profile_centroid = DDC(ad_group(EpicsSignalRO, - (('x', 'ProfileCentroidX_RBV'), - ('y', 'ProfileCentroidY_RBV'))), - doc='Profile centroid in XY', - default_read_attrs=('x', 'y')) - - profile_cursor = DDC(ad_group(EpicsSignalRO, - (('x', 'ProfileCursorX_RBV'), - ('y', 'ProfileCursorY_RBV'))), - doc='Profile cursor in XY', - default_read_attrs=('x', 'y')) - - profile_size = DDC(ad_group(EpicsSignalRO, - (('x', 'ProfileSizeX_RBV'), - ('y', 'ProfileSizeY_RBV'))), - doc='Profile size in XY', - default_read_attrs=('x', 'y')) - - profile_threshold = DDC(ad_group(EpicsSignalRO, - (('x', 'ProfileThresholdX_RBV'), - ('y', 'ProfileThresholdY_RBV'))), - doc='Profile threshold in XY', - default_read_attrs=('x', 'y')) - - set_xhopr = ADCpt(EpicsSignal, 'SetXHOPR') - set_yhopr = ADCpt(EpicsSignal, 'SetYHOPR') - sigma_xy = ADCpt(EpicsSignalRO, 'SigmaXY_RBV') - sigma_x = ADCpt(EpicsSignalRO, 'SigmaX_RBV') - sigma_y = ADCpt(EpicsSignalRO, 'SigmaY_RBV') - sigma = ADCpt(EpicsSignalRO, 'Sigma_RBV') - ts_acquiring = ADCpt(EpicsSignal, 'TS:TSAcquiring') - - ts_centroid = DDC(ad_group(EpicsSignal, - (('x', 'TS:TSCentroidX'), - ('y', 'TS:TSCentroidY'))), - doc='Time series centroid in XY', - default_read_attrs=('x', 'y')) - - # ts_control = ADCpt(EpicsSignal, 'TS:TSControl', string=True) - ts_current_point = ADCpt(EpicsSignal, 'TS:TSCurrentPoint') - ts_max_value = ADCpt(EpicsSignal, 'TS:TSMaxValue') - - ts_max = DDC(ad_group(EpicsSignal, - (('x', 'TS:TSMaxX'), - ('y', 'TS:TSMaxY'))), - doc='Time series maximum in XY', - default_read_attrs=('x', 'y')) - - ts_mean_value = ADCpt(EpicsSignal, 'TS:TSMeanValue') - ts_min_value = ADCpt(EpicsSignal, 'TS:TSMinValue') - - ts_min = DDC(ad_group(EpicsSignal, - (('x', 'TS:TSMinX'), - ('y', 'TS:TSMinY'))), - doc='Time series minimum in XY', - default_read_attrs=('x', 'y')) - - ts_net = ADCpt(EpicsSignal, 'TS:TSNet') - ts_num_points = ADCpt(EpicsSignal, 'TS:TSNumPoints') - ts_read = ADCpt(EpicsSignal, 'TS:TSRead') - ts_sigma = ADCpt(EpicsSignal, 'TS:TSSigma') - ts_sigma_x = ADCpt(EpicsSignal, 'TS:TSSigmaX') - ts_sigma_xy = ADCpt(EpicsSignal, 'TS:TSSigmaXY') - ts_sigma_y = ADCpt(EpicsSignal, 'TS:TSSigmaY') - ts_total = ADCpt(EpicsSignal, 'TS:TSTotal') - total = ADCpt(EpicsSignalRO, 'Total_RBV') - - -class QuadEMPort(ADBase): - port_name = Cpt(Signal, value="") - - def __init__(self, port_name, *args, **kwargs): - super().__init__(*args, **kwargs) - self.port_name.put(port_name) - - -class QuadEMV33(QuadEM): - conf = Cpt(QuadEMPort, port_name="EM180") - em_range = Cpt(SignalWithRBV, "Range", string=True) - - current1 = ADCpt(StatsPluginV33, 'Current1:') - current2 = ADCpt(StatsPluginV33, 'Current2:') - current3 = ADCpt(StatsPluginV33, 'Current3:') - current4 = ADCpt(StatsPluginV33, 'Current4:') - sum_all = ADCpt(StatsPluginV33, 'SumAll:') diff --git a/nslsii/common/__init__.py b/nslsii/common/__init__.py deleted file mode 100644 index 665813fd..00000000 --- a/nslsii/common/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .touchbl import if_touch_beamline - -__all__ = ["if_touch_beamline"] \ No newline at end of file diff --git a/nslsii/common/ipynb/__init__.py b/nslsii/common/ipynb/__init__.py deleted file mode 100644 index 4dfcb9f9..00000000 --- a/nslsii/common/ipynb/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -__all__ = ['image_stack_to_movie', 'show_image_stack', - 'notebook_to_nbviewer', 'get_sys_info', - 'show_kernels'] - -from .animation import image_stack_to_movie, show_image_stack -from .nbviewer import notebook_to_nbviewer -from .info import get_sys_info, show_kernels diff --git a/nslsii/common/ipynb/info.py b/nslsii/common/ipynb/info.py deleted file mode 100644 index 1af3af0b..00000000 --- a/nslsii/common/ipynb/info.py +++ /dev/null @@ -1,67 +0,0 @@ -import sys -import psutil -import platform -from IPython.display import HTML - - -def get_sys_info(): - """Display info on system and output as nice HTML""" - html = '

System Information for {}

'.format(platform.node()) - html += '' - - html += '' - html += ''.format(sys.executable) - html += ''.format( - psutil.Process().pid) - - mem = psutil.virtual_memory() - html += '' - html += ''.format(mem.total/1024**3) - html += '' - html += ''.format(mem.used/1024**3) - html += '' - html += ''.format(mem.free/1024**3) - - html += ''.format( - psutil.cpu_count()) - html += ''.format( - psutil.cpu_percent(1, False)) - - html += '
Python Executable{}
Kernel PID{}
Total System Memory{:.4} Mb
Total Memory Used{:.4} Mb
Total Memory Free{:.4} Mb
Number of CPU Cores{}
Current CPU Load{} %
' - return HTML(html) - - -def show_kernels(): - """Show all IPython Kernels on System""" - - total_mem = psutil.virtual_memory().total - - html = ('

IPython Notebook Processes on {}

' - '' - '' - '' - '').format(platform.node()) - - for proc in psutil.process_iter(): - try: - pinfo = proc.as_dict(attrs=['pid', 'username', 'cmdline', - 'memory_info', 'status']) - except psutil.NoSuchProcess: - pass - else: - if any(x in pinfo['cmdline'] for x in ['IPython.kernel', - 'ipykernel_launcher']): - html += '' - html += ''.format(**pinfo) - p = psutil.Process(pinfo['pid']).cpu_percent(0.1) - html += ''.format(p) - html += ''.format(pinfo['memory_info'].vms / - 1024**3) - html += ''.format(100 * - pinfo['memory_info'].vms / - total_mem) - html += ''.format(pinfo['status']) - html += '' - - html += '
UsernamePIDCPU UsageProcess MemorySystem Memory UsedStatus
{username}{pid}{}%{:.4} Mb{:.3}%{}
' - return HTML(html) diff --git a/nslsii/detectors/QEPro.py b/nslsii/detectors/QEPro.py deleted file mode 100644 index 488ea08b..00000000 --- a/nslsii/detectors/QEPro.py +++ /dev/null @@ -1,166 +0,0 @@ -from gc import collect -import logging - -from ophyd import (Device, Component as Cpt, FormattedComponent as FC, - Signal) -from ophyd import (EpicsSignal, EpicsSignalRO, DeviceStatus, DerivedSignal) -from ophyd.areadetector import EpicsSignalWithRBV as SignalWithRBV -from ophyd.status import SubscriptionStatus - -class QEProTEC(Device): - - # Thermal electric cooler settings - tec = Cpt(SignalWithRBV, 'TEC') - tec_temp = Cpt(SignalWithRBV, 'TEC_TEMP') - curr_tec_temp = Cpt(EpicsSignalRO, 'CURR_TEC_TEMP_RBV') - - def __init__(self, *args, tolerance=1, **kwargs): - self.tolerance = tolerance - super().__init__(*args, **kwargs) - - def set(self, value): - - def check_setpoint(value, old_value, **kwargs): - if abs(value - self.tec_temp.get()) < self.tolerance: - print(f'Reached setpoint {self.tec_temp.get()}.') - return True - return False - - status = SubscriptionStatus(self.curr_tec_temp, run=False, callback=check_setpoint) - self.tec_temp.put(value) - self.tec.put(1) - - return status - - -class QEPro(Device): - - # Device information - serial = Cpt(EpicsSignal, 'SERIAL') - model = Cpt(EpicsSignal, 'MODEL') - - # Device Status - status = Cpt(EpicsSignal, 'STATUS') - status_msg = Cpt(EpicsSignal, 'STATUS_MSG') - device_connected = Cpt(EpicsSignalRO, 'CONNECTED_RBV') - - # Utility signal that periodically checks device temps. - __check_status = Cpt(EpicsSignal, 'CHECK_STATUS') - - # Bit array outlining which features are supported by the device - features = Cpt(EpicsSignalRO, 'FEATURES_RBV') - - # Togglable features (if supported) - strobe = Cpt(SignalWithRBV, 'STROBE') - electric_dark_correction = Cpt(SignalWithRBV, 'EDC') - non_linearity_correction = Cpt(SignalWithRBV, 'NLC') - shutter = Cpt(SignalWithRBV, 'SHUTTER') - - # Thermal electric cooler - tec_device = Cpt(QEProTEC, '') - - # Light source feature signals - light_source = Cpt(SignalWithRBV, 'LIGHT_SOURCE') - light_source_intensity = Cpt(SignalWithRBV, 'LIGHT_SOURCE_INTENSITY') - light_source_count = Cpt(EpicsSignalRO, 'LIGHT_SOURCE_COUNT_RBV') - - # Signals for specifying the number of spectra to average and counter for spectra - # collected in current scan - num_spectra = Cpt(SignalWithRBV, 'NUM_SPECTRA') - spectra_collected = Cpt(EpicsSignalRO, 'SPECTRA_COLLECTED_RBV') - - # Integration time settings (in ms) - int_min_time = Cpt(EpicsSignalRO, 'INT_MIN_TIME_RBV') - int_max_time = Cpt(EpicsSignalRO, 'INT_MAX_TIME_RBV') - integration_time = Cpt(SignalWithRBV, 'INTEGRATION_TIME', kind='normal') - - # Internal buffer feature settings - buff_min_capacity = Cpt(EpicsSignalRO, 'BUFF_MIN_CAPACITY_RBV') - buff_max_capacity = Cpt(EpicsSignalRO, 'BUFF_MAX_CAPACITY_RBV') - buff_capacity = Cpt(SignalWithRBV, 'BUFF_CAPACITY') - buff_element_count = Cpt(EpicsSignalRO, 'BUFF_ELEMENT_COUNT_RBV') - - # Formatted Spectra - spectrum = Cpt(EpicsSignal, 'SPECTRUM', kind='normal') - dark = Cpt(EpicsSignal, 'DARK', kind='normal') - reference = Cpt(EpicsSignal, 'REFERENCE', kind='normal') - - # Length of spectrum (in pixels) - formatted_spectrum_len = Cpt(EpicsSignalRO, 'FORMATTED_SPECTRUM_LEN_RBV') - - # X-axis format and array - x_axis = Cpt(EpicsSignal, 'X_AXIS') - x_axis_format = Cpt(SignalWithRBV, 'X_AXIS_FORMAT') - - # Dark/Ref available signals - dark_available = Cpt(EpicsSignalRO, 'DARK_AVAILABLE_RBV') - ref_available = Cpt(EpicsSignalRO, 'REF_AVAILABLE_RBV') - - # Collection settings and start signals. - acquire = Cpt(SignalWithRBV, 'COLLECT', put_complete=True) - collect_mode = Cpt(SignalWithRBV, 'COLLECT_MODE') - spectrum_type = Cpt(SignalWithRBV, 'SPECTRUM_TYPE') - correction = Cpt(SignalWithRBV, 'CORRECTION') - trigger_mode = Cpt(SignalWithRBV, 'TRIGGER_MODE') - - - @property - def has_nlc_feature(self): - return self.features.get() & 32 - - @property - def has_lightsource_feature(self): - return self.features.get() & 16 - - @property - def has_edc_feature(self): - return self.features.get() & 8 - - @property - def has_buffer_feature(self): - return self.features.get() & 4 - - @property - def has_tec_feature(self): - return self.features.get() & 2 - - @property - def has_irrad_feature(self): - return self.features.get() & 1 - - - def set_temp(self, temperature): - self.tec_device.set(temperature).wait() - - - def get_dark_frame(self): - - self.spectrum_type.put(1) - self.acquire.put(1, wait=True) - - def get_reference_frame(self): - - if self.dark_available.get() == 0: - return - self.spectrum_type.put(2) - self.acquire.put(1, wait=True) - - - def setup_collection(self, integration_time, num_spectra_to_average, correction_type='reference', electric_dark_correction=True): - self.integration_time.put(integration_time) - self.num_spectra = num_spectra_to_average - if electric_dark_correction: - self.electric_dark_correction = True - - - self.get_dark_frame() - self.get_reference_frame() - - - def trigger(self): - - self.acquire.put(1, wait=True) - - - - diff --git a/nslsii/detectors/zebra.py b/nslsii/detectors/zebra.py deleted file mode 100644 index 9f97860b..00000000 --- a/nslsii/detectors/zebra.py +++ /dev/null @@ -1,325 +0,0 @@ -from enum import IntEnum -import logging - -from ophyd import (Device, Component as Cpt, FormattedComponent as FC, - Signal) -from ophyd import (EpicsSignal, EpicsSignalRO, DeviceStatus) -from ophyd.utils import set_and_wait - -from .trigger_mixins import ModalBase - -logger = logging.getLogger(__name__) - - -def _get_configuration_attrs(inst, *, signal_class=Signal): - cls = inst.__class__ - return [sig_name for sig_name in cls.component_names - if issubclass(getattr(cls, sig_name).cls, signal_class)] - - -class ZebraInputEdge(IntEnum): - FALLING = 1 - RISING = 0 - - -class ZebraAddresses(IntEnum): - DISCONNECT = 0 - IN1_TTL = 1 - IN1_NIM = 2 - IN1_LVDS = 3 - IN2_TTL = 4 - IN2_NIM = 5 - IN2_LVDS = 6 - IN3_TTL = 7 - IN3_OC = 8 - IN3_LVDS = 9 - IN4_TTL = 10 - IN4_CMP = 11 - IN4_PECL = 12 - IN5_ENCA = 13 - IN5_ENCB = 14 - IN5_ENCZ = 15 - IN5_CONN = 16 - IN6_ENCA = 17 - IN6_ENCB = 18 - IN6_ENCZ = 19 - IN6_CONN = 20 - IN7_ENCA = 21 - IN7_ENCB = 22 - IN7_ENCZ = 23 - IN7_CONN = 24 - IN8_ENCA = 25 - IN8_ENCB = 26 - IN8_ENCZ = 27 - IN8_CONN = 28 - PC_ARM = 29 - PC_GATE = 30 - PC_PULSE = 31 - AND1 = 32 - AND2 = 33 - AND3 = 34 - AND4 = 35 - OR1 = 36 - OR2 = 37 - OR3 = 38 - OR4 = 39 - GATE1 = 40 - GATE2 = 41 - GATE3 = 42 - GATE4 = 43 - DIV1_OUTD = 44 - DIV2_OUTD = 45 - DIV3_OUTD = 46 - DIV4_OUTD = 47 - DIV1_OUTN = 48 - DIV2_OUTN = 49 - DIV3_OUTN = 50 - DIV4_OUTN = 51 - PULSE1 = 52 - PULSE2 = 53 - PULSE3 = 54 - PULSE4 = 55 - QUAD_OUTA = 56 - QUAD_OUTB = 57 - CLOCK_1KHZ = 58 - CLOCK_1MHZ = 59 - SOFT_IN1 = 60 - SOFT_IN2 = 61 - SOFT_IN3 = 62 - SOFT_IN4 = 63 - - -class EpicsSignalWithRBV(EpicsSignal): - # An EPICS signal that uses the Zebra convention of 'pvname' being the - # setpoint and 'pvname:RBV' being the read-back - - def __init__(self, prefix, **kwargs): - super().__init__(prefix + ':RBV', write_pv=prefix, **kwargs) - - -class ZebraPulse(Device): - width = Cpt(EpicsSignalWithRBV, 'WID') - input_addr = Cpt(EpicsSignalWithRBV, 'INP') - input_str = Cpt(EpicsSignalRO, 'INP:STR', string=True) - input_status = Cpt(EpicsSignalRO, 'INP:STA') - delay = Cpt(EpicsSignalWithRBV, 'DLY') - delay_sync = Cpt(EpicsSignal, 'DLY:SYNC') - time_units = Cpt(EpicsSignalWithRBV, 'PRE', string=True) - output = Cpt(EpicsSignal, 'OUT') - - input_edge = FC(EpicsSignal, - '{self._zebra_prefix}POLARITY:{self._edge_addr}') - - _edge_addrs = {1: 'BC', - 2: 'BD', - 3: 'BE', - 4: 'BF', - } - - def __init__(self, prefix, *, index=None, parent=None, - configuration_attrs=None, read_attrs=None, **kwargs): - if read_attrs is None: - read_attrs = [] - if configuration_attrs is None: - configuration_attrs = _get_configuration_attrs(self) - - zebra = parent - self.index = index - self._zebra_prefix = zebra.prefix - self._edge_addr = self._edge_addrs[index] - - super().__init__(prefix, configuration_attrs=configuration_attrs, - read_attrs=read_attrs, parent=parent, **kwargs) - - -class ZebraOutputBase(Device): - '''The base of all zebra outputs (1~8) - - Front outputs - # TTL LVDS NIM PECL OC ENC - 1 o o o - 2 o o o - 3 o o o - 4 o o o - - Rear outputs - # TTL LVDS NIM PECL OC ENC - 5 o - 6 o - 7 o - 8 o - - ''' - def __init__(self, prefix, *, index=None, read_attrs=None, - configuration_attrs=None, **kwargs): - self.index = index - - if read_attrs is None: - read_attrs = [] - if configuration_attrs is None: - configuration_attrs = _get_configuration_attrs(self) - - super().__init__(prefix, read_attrs=read_attrs, - configuration_attrs=configuration_attrs, **kwargs) - - -class ZebraOutputType(Device): - '''Shared by all output types (ttl, lvds, nim, pecl, out)''' - addr = Cpt(EpicsSignalWithRBV, '') - status = Cpt(EpicsSignalRO, ':STA') - string = Cpt(EpicsSignalRO, ':STR', string=True) - sync = Cpt(EpicsSignal, ':SYNC') - write_output = Cpt(EpicsSignal, ':SET') - - def __init__(self, prefix, *, read_attrs=None, configuration_attrs=None, - **kwargs): - if read_attrs is None: - read_attrs = [] - if configuration_attrs is None: - configuration_attrs = _get_configuration_attrs(self) - - super().__init__(prefix, read_attrs=read_attrs, - configuration_attrs=configuration_attrs, **kwargs) - - -class ZebraFrontOutput12(ZebraOutputBase): - ttl = Cpt(ZebraOutputType, 'TTL') - lvds = Cpt(ZebraOutputType, 'LVDS') - nim = Cpt(ZebraOutputType, 'NIM') - - -class ZebraFrontOutput3(ZebraOutputBase): - ttl = Cpt(ZebraOutputType, 'TTL') - lvds = Cpt(ZebraOutputType, 'LVDS') - open_collector = Cpt(ZebraOutputType, 'OC') - - -class ZebraFrontOutput4(ZebraOutputBase): - ttl = Cpt(ZebraOutputType, 'TTL') - nim = Cpt(ZebraOutputType, 'NIM') - pecl = Cpt(ZebraOutputType, 'PECL') - - -class ZebraRearOutput(ZebraOutputBase): - enca = Cpt(ZebraOutputType, 'ENCA') - encb = Cpt(ZebraOutputType, 'ENCB') - encz = Cpt(ZebraOutputType, 'ENCZ') - conn = Cpt(ZebraOutputType, 'CONN') - - -class ZebraGateInput(Device): - addr = Cpt(EpicsSignalWithRBV, '') - string = Cpt(EpicsSignalRO, ':STR', string=True) - status = Cpt(EpicsSignalRO, ':STA') - sync = Cpt(EpicsSignal, ':SYNC') - write_input = Cpt(EpicsSignal, ':SET') - - # Input edge index depends on the gate number (these are set in __init__) - edge = FC(EpicsSignal, - '{self._zebra_prefix}POLARITY:B{self._input_edge_idx}') - - def __init__(self, prefix, *, index=None, parent=None, - configuration_attrs=None, read_attrs=None, **kwargs): - if read_attrs is None: - read_attrs = [] - if configuration_attrs is None: - configuration_attrs = _get_configuration_attrs(self) - - gate = parent - zebra = gate.parent - - self.index = index - self._zebra_prefix = zebra.prefix - self._input_edge_idx = gate._input_edge_idx[self.index] - - super().__init__(prefix, read_attrs=read_attrs, - configuration_attrs=configuration_attrs, - parent=parent, **kwargs) - - -class ZebraGate(Device): - input1 = Cpt(ZebraGateInput, 'INP1', index=1) - input2 = Cpt(ZebraGateInput, 'INP2', index=2) - output = Cpt(EpicsSignal, 'OUT') - - def __init__(self, prefix, *, index=None, read_attrs=None, - configuration_attrs=None, **kwargs): - self.index = index - self._input_edge_idx = {1: index - 1, - 2: 4 + index - 1 - } - - if read_attrs is None: - read_attrs = [] - if configuration_attrs is None: - configuration_attrs = ['output'] - - super().__init__(prefix, configuration_attrs=configuration_attrs, - read_attrs=read_attrs, **kwargs) - - def set_input_edges(self, edge1, edge2): - set_and_wait(self.input1.edge, int(edge1)) - set_and_wait(self.input2.edge, int(edge2)) - - -class Zebra(ModalBase, Device): - soft_input1 = Cpt(EpicsSignal, 'SOFT_IN:B0') - soft_input2 = Cpt(EpicsSignal, 'SOFT_IN:B1') - soft_input3 = Cpt(EpicsSignal, 'SOFT_IN:B2') - soft_input4 = Cpt(EpicsSignal, 'SOFT_IN:B3') - - pulse1 = Cpt(ZebraPulse, 'PULSE1_', index=1) - pulse2 = Cpt(ZebraPulse, 'PULSE2_', index=2) - pulse3 = Cpt(ZebraPulse, 'PULSE3_', index=3) - pulse4 = Cpt(ZebraPulse, 'PULSE4_', index=4) - - output1 = Cpt(ZebraFrontOutput12, 'OUT1_', index=1) - output2 = Cpt(ZebraFrontOutput12, 'OUT2_', index=2) - output3 = Cpt(ZebraFrontOutput3, 'OUT3_', index=3) - output4 = Cpt(ZebraFrontOutput4, 'OUT4_', index=4) - - output5 = Cpt(ZebraRearOutput, 'OUT5_', index=5) - output6 = Cpt(ZebraRearOutput, 'OUT6_', index=6) - output7 = Cpt(ZebraRearOutput, 'OUT7_', index=7) - output8 = Cpt(ZebraRearOutput, 'OUT8_', index=8) - - gate1 = Cpt(ZebraGate, 'GATE1_', index=1) - gate2 = Cpt(ZebraGate, 'GATE2_', index=2) - gate3 = Cpt(ZebraGate, 'GATE3_', index=3) - gate4 = Cpt(ZebraGate, 'GATE4_', index=4) - - addresses = ZebraAddresses - - def __init__(self, prefix, *, configuration_attrs=None, read_attrs=None, - **kwargs): - if read_attrs is None: - read_attrs = [] - if configuration_attrs is None: - configuration_attrs = _get_configuration_attrs(self) - - super().__init__(prefix, configuration_attrs=configuration_attrs, - read_attrs=read_attrs, **kwargs) - - self.pulse = dict(self._get_indexed_devices(ZebraPulse)) - self.output = dict(self._get_indexed_devices(ZebraOutputBase)) - self.gate = dict(self._get_indexed_devices(ZebraGate)) - - def _get_indexed_devices(self, cls): - for attr in self._sub_devices: - dev = getattr(self, attr) - if isinstance(dev, cls): - yield dev.index, dev - - def mode_internal(self): - super().mode_internal() - # handle the scan type here - - def mode_external(self): - super().mode_external() - # handle the scan type here - - def trigger(self): - # Re-implement this to trigger as desired in bluesky - status = DeviceStatus(self) - status._finished() - return status diff --git a/nslsii/iocs/eps_two_state_ioc_sim.py b/nslsii/iocs/eps_two_state_ioc_sim.py deleted file mode 100644 index 17cc3e76..00000000 --- a/nslsii/iocs/eps_two_state_ioc_sim.py +++ /dev/null @@ -1,247 +0,0 @@ -#!/usr/bin/env python3 -from caproto.server import pvproperty, PVGroup -from caproto.server import template_arg_parser, run -from caproto import ChannelType -import contextvars -import functools - -internal_process = contextvars.ContextVar('internal_process', - default=False) - - -def no_reentry(func): - @functools.wraps(func) - async def inner(*args, **kwargs): - if internal_process.get(): - return - try: - internal_process.set(True) - return (await func(*args, **kwargs)) - finally: - internal_process.set(False) - - return inner - - -class EPSTwoStateIOC(PVGroup): - """ - Simulates an EPS Two State device including multiple-attempt issue - for two-state device. - - This IOC is used to simulate an EPS Two State Device, for testing - or development purposes. Known EPS two state devices include Photon - shutters, gate valves and Pneumatic actuators at NSLS-II. It simulates - known issues with some of these including: A hardware error (when some - attempts at sending the command fail and we need to 'kick' the device - a few times to get it to actuate), A position status error (it sometimes - does not reach the final state but remains 'between states') and - an enable state change error (there is an 'enable' PV controlled by - the control room that determines if the device can be operated or not). - A parameter (described below) allows each of these error paths to be - tested against. - - Parameters - ---------- - retries : int, optional - Number of attempts required for changing state, - default is 2 - enbl_sts_val: str, optional - Enumerated string that enables the state change, - default is True - hw_error_val: str, optional - Enumerated string that activates the hardware error, - default is False - sts_error_val: str, optional - Enumerated string that activates the Pos-Sts error, - default is False - """ - - def __init__(self, retries=2, enbl_sts_val='True', - hw_error_val='False', sts_error_val='False', - **kwargs): - - super().__init__(**kwargs) - - self._max_retries = retries - self._num_retries = 0 - - self._enbl_sts_val = enbl_sts_val - - self._hw_error_val = hw_error_val - self._sts_error_val = sts_error_val - - # Pos-Sts two-state PV - - _pos_states = ['Open', 'Not Open'] # two position states - - pos_sts = pvproperty(value="Open", - enum_strings=_pos_states, - dtype=ChannelType.ENUM, - read_only=True, - name='Pos-Sts') - - # Opn-Cmd and Cls-Cmd PVs used by client for changing state - - _cmd_states = ['None', 'Done'] # two command states - - state1_cmd = pvproperty(value=_cmd_states[0], - enum_strings=['None', 'Open'], - dtype=ChannelType.ENUM, - name='Cmd:Opn-Cmd') - state2_cmd = pvproperty(value=_cmd_states[0], - enum_strings=['None', 'Close'], - dtype=ChannelType.ENUM, - name='Cmd:Cls-Cmd') - - _fail_states = ['False', 'True'] - - fail_to_state1 = pvproperty(value=_fail_states[0], - enum_strings=_fail_states, - dtype=ChannelType.ENUM, - read_only=True, - name='Sts:FailOpn-Sts') - fail_to_state2 = pvproperty(value=_fail_states[0], - enum_strings=_fail_states, - dtype=ChannelType.ENUM, - read_only=True, - name='Sts:FailCls-Sts') - - # Enbl-Sts PV that enables/disables the state change - - _enbl_states = ['False', 'True'] - - enbl_sts = pvproperty(value='', - enum_strings=_enbl_states, - dtype=ChannelType.ENUM, - name='Enbl-Sts') - - # Hardware error status - - _hw_error_states = ['False', 'True'] - - hw_error_sts = pvproperty(value='', - enum_strings=_hw_error_states, - dtype=ChannelType.ENUM, - name='HwError-Sts') - - # Pos-Sts error status - - _sts_error_states = ['False', 'True'] - - sts_error_sts = pvproperty(value='', - enum_strings=_sts_error_states, - dtype=ChannelType.ENUM, - name='StsError-Sts') - - # PV Startup/Putter Methods - - @enbl_sts.startup - async def enbl_sts(self, instance, async_lib): - await instance.write(value=self._enbl_sts_val) - - @hw_error_sts.startup - async def hw_error_sts(self, instance, async_lib): - await instance.write(value=self._hw_error_val) - - @sts_error_sts.startup - async def sts_error_sts(self, instance, async_lib): - await instance.write(value=self._sts_error_val) - - @state1_cmd.startup - async def state1_cmd(self, instance, async_lib): - instance.async_lib = async_lib - - @state1_cmd.putter - @no_reentry - async def state1_cmd(self, instance, value): - if value == 'Open': - await self.state1_cmd.write(value) - await instance.async_lib.library.sleep(1) - await self.pos_sts.write('Open') - return 'None' - - @state2_cmd.startup - async def state2_cmd(self, instance, async_lib): - instance.async_lib = async_lib - - @state2_cmd.putter - @no_reentry - async def state2_cmd(self, instance, value): - if value == 'Close': - await self.state2_cmd.write(value) - await instance.async_lib.library.sleep(1) - await self.pos_sts.write('Not Open') - return 'None' - - @enbl_sts.putter - async def enbl_sts(self, instance, value): - self._enbl_sts_val = value - return value - - @hw_error_sts.putter - async def hw_error_sts(self, instance, value): - self._hw_error_val = value - return value - - @sts_error_sts.putter - async def sts_error_sts(self, instance, value): - self._sts_error_val = value - return value - - # Internal Methods - - async def _state_cmd_put(self, instance, value, state_val, fail_to_state): - if(value == self._cmd_states[0]): # if None -> do nothing - return self._cmd_states[0] - if(self._pos_sts_val == state_val): # if in state -> do nothing - return self._cmd_states[0] - if(self._enbl_sts_val == 'False'): # if changes not enabled -> fail - await fail_to_state.write(value='True') - return self._cmd_states[0] - self._num_retries += 1 - if(self._num_retries < self._max_retries): - return self._cmd_states[0] - else: - self._num_retries = 0 - if(self._hw_error_val == 'True'): # if hw error -> fail - await fail_to_state.write(value='True') - return self._cmd_states[1] - else: - await fail_to_state.write(value='False') - if(self._sts_error_val == 'True'): # if sts error -> don't change sts - return self._cmd_states[1] - await self.pos_sts.write(value=state_val) - self._pos_sts_val = state_val - return self._cmd_states[0] - - -if __name__ == '__main__': - - parser, split_args = template_arg_parser( - default_prefix='eps2state:', - desc='EPS Two State IOC.') - - retries_help = 'Number of attempts required for changing state' - enable_help = 'State change is enabled' - hwerror_help = 'HW error is activated' - stserror_help = 'Pos-Sts error is activated' - - parser.add_argument('--retries', help=retries_help, - required=False, default=2, type=int) - parser.add_argument('--enable', help=enable_help, - required=False, default='True', type=str) - parser.add_argument('--hwerror', help=hwerror_help, - required=False, default='False', type=str) - parser.add_argument('--stserror', help=stserror_help, - required=False, default='False', type=str) - - args = parser.parse_args() - ioc_options, run_options = split_args(args) - - ioc = EPSTwoStateIOC(retries=args.retries, - enbl_sts_val=args.enable, - hw_error_val=args.hwerror, - sts_error_val=args.stserror, - **ioc_options) - - run(ioc.pvdb, **run_options) diff --git a/nslsii/sync_experiment/__init__.py b/nslsii/sync_experiment/__init__.py deleted file mode 100644 index 5528c0fa..00000000 --- a/nslsii/sync_experiment/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .sync_experiment import main, sync_experiment, validate_proposal, switch_redis_proposal diff --git a/nslsii/tests/test_ipynb.py b/nslsii/tests/test_ipynb.py deleted file mode 100644 index cb78cc46..00000000 --- a/nslsii/tests/test_ipynb.py +++ /dev/null @@ -1,22 +0,0 @@ -import os - -def test_ipynb(): - from nslsii.common import ipynb - obj = ipynb.get_sys_info() - obj.data - obj.filename - obj.metadata - obj.url - obj.reload() - -def test_touchbl(): - from nslsii.common import if_touch_beamline - - if "TOUCHBEAMLINE" in os.environ: - del os.environ["TOUCHBEAMLINE"] - - assert not if_touch_beamline() - - os.environ["TOUCHBEAMLINE"] = "1" - - assert if_touch_beamline() \ No newline at end of file diff --git a/nslsii/tests/test_kafka_conditional_import.py b/nslsii/tests/test_kafka_conditional_import.py deleted file mode 100644 index ea6d3038..00000000 --- a/nslsii/tests/test_kafka_conditional_import.py +++ /dev/null @@ -1,133 +0,0 @@ -import os -import subprocess -import sys - -import pytest - - -def test_conditional_import_negative_case(): - """ - Test that bluesky_kafka is not imported when publish_documents_with_kafka=False. - - This is a "subprocess test" meaning the entire test function executes in a - separate python interpreter and the pass/fail result is returned by sys.exit(). - This is necessary to guarantee bluesky_kakfa has not been imported as a result - of other tests. - """ - the_test = """ -import sys -from unittest.mock import Mock - -import IPython.core.interactiveshell - -import nslsii - - -ip = IPython.core.interactiveshell.InteractiveShell() -nslsii.configure_base( - user_ns=ip.user_ns, - redis_url = "localhost", - redis_prefix = "", - # a mock databroker will be enough for this test - broker_name=Mock(), - bec=False, - epics_context=False, - magics=False, - mpl=False, - configure_logging=False, - pbar=False, - ipython_logging=False, - # this is the important condition for the test - publish_documents_with_kafka=False, -) - -if "bluesky_kafka" in sys.modules: - sys.exit(1) -else: - sys.exit(0) -""" - proc = subprocess.run( - [sys.executable, "-c", the_test], - ) - - if proc.returncode: - pytest.fail( - "The subprocess returned with non-zero exit status " f"{proc.returncode}." - ) - - -test_bluesky_kafka_config = """\ ---- - abort_run_on_kafka_exception: true - bootstrap_servers: - - kafka1:9092 - - kafka2:9092 - - kafka3:9092 - runengine_producer_config: - acks: 0 - message.timeout.ms: 3000 - compression.codec: snappy -""" - - -def test_conditional_import_positive_case(tmp_path): - """ - Test that bluesky_kafka is imported when publish_documents_with_kafka=True. - - The connection to a Kafka broker will fail but that does not affect the test result. - - This is a "subprocess test" meaning the entire test function executes in a - separate python interpreter and the pass/fail result is returned by sys.exit(). - This is necessary to guarantee bluesky_kakfa has not been imported as a result - of other tests. - """ - - # write a temporary file for this test - test_config_file_path = tmp_path / "bluesky_kafka_config_content.yml" - with open(test_config_file_path, "wt") as f: - f.write(test_bluesky_kafka_config) - - the_test = f""" -import sys -from unittest.mock import Mock - -import IPython.core.interactiveshell - -import nslsii - - -ip = IPython.core.interactiveshell.InteractiveShell() -nslsii.configure_base( - user_ns=ip.user_ns, - redis_url = "localhost", - redis_prefix = "", - # a mock databroker will be enough for this test - broker_name=Mock(), - bec=False, - epics_context=False, - magics=False, - mpl=False, - configure_logging=False, - pbar=False, - ipython_logging=False, - # this is the important condition for the test - publish_documents_with_kafka=True, -) - -if "bluesky_kafka" in sys.modules: - sys.exit(0) -else: - sys.exit(1) -""" - proc = subprocess.run( - [sys.executable, "-c", the_test], - env={ - **os.environ, - "BLUESKY_KAFKA_CONFIG_PATH": str(test_config_file_path), - }, - ) - - if proc.returncode: - pytest.fail( - "The subprocess returned with non-zero exit status " f"{proc.returncode}." - ) diff --git a/nslsii/tests/test_kafka_configuration.py b/nslsii/tests/test_kafka_configuration.py deleted file mode 100644 index 20f04d8c..00000000 --- a/nslsii/tests/test_kafka_configuration.py +++ /dev/null @@ -1,255 +0,0 @@ -import os - -import pytest - -from nslsii import configure_kafka_publisher - -from nslsii.kafka_utils import ( - _read_bluesky_kafka_config_file, -) - -# these test configurations include localhost:9092 -# because configure_kafka_publisher verifies that -# a connection can be made to a broker - -test_bluesky_kafka_config_true = """\ ---- - abort_run_on_kafka_exception: true - bootstrap_servers: - - localhost:9092 - - kafka1:9092 - - kafka2:9092 - runengine_producer_config: - acks: 0 - message.timeout.ms: 3000 - compression.codec: snappy -""" - -test_bluesky_kafka_config_false = """\ ---- - abort_run_on_kafka_exception: false - bootstrap_servers: - - localhost:9092 - - kafka1:9092 - - kafka2:9092 - runengine_producer_config: - acks: 0 - message.timeout.ms: 3000 - compression.codec: snappy -""" - -test_bluesky_kafka_config_security_section = """\ ---- - abort_run_on_kafka_exception: false - bootstrap_servers: - - localhost:9092 - - kafka2:9092 - - kafka3:9092 - producer_consumer_security_config: - security.protocol: SASL_SSL - sasl.mechanisms: PLAIN - ssl.ca.location: /etc/ssl/certs/ca-bundle.crt - consumer_config: - auto.offset.reset: latest - runengine_producer_config: - compression.codec: snappy - security.protocol: SASL_SSL - sasl.mechanisms: PLAIN - ssl.ca.location: /etc/ssl/certs/ca-bundle.crt - runengine_topics: - - "{endstation}.bluesky.runengine.documents" - - "{endstation}.bluesky.runengine.{document_name}.documents" -""" - - -def test_bluesky_kafka_config_path_env_var(tmp_path, RE, temporary_topics): - """Test specifying a configuration file path by environment variable.""" - with temporary_topics(topics=["abc.bluesky.runengine.documents"]) as ( - beamline_topic, - ): - # write a temporary file for this test - test_config_file_path = tmp_path / "bluesky_kafka_config_content.yml" - with open(test_config_file_path, "wt") as f: - f.write(test_bluesky_kafka_config_false) - # add an extra item to test for later - f.write(f" config_file_path: {test_config_file_path}") - - os.environ["BLUESKY_KAFKA_CONFIG_PATH"] = str(test_config_file_path) - bluesky_kafka_configuration, publisher_details = configure_kafka_publisher( - RE, "abc" - ) - - assert bluesky_kafka_configuration["config_file_path"] == str( - test_config_file_path - ) - - -def test_bluesky_kafka_config_path_env_var_negative(tmp_path, RE): - """Test specifying a configuration file path that does not exist by environment variable.""" - # write a temporary file for this test - test_config_file_path = tmp_path / "bluesky_kafka_config_content.yml" - os.environ["BLUESKY_KAFKA_CONFIG_PATH"] = str(test_config_file_path) - with pytest.raises(FileNotFoundError, match=str(test_config_file_path)): - bluesky_kafka_configuration = configure_kafka_publisher(RE, "abc") - - -def test_bluesky_kafka_config_path_default_negative(tmp_path, RE): - """Test the default configuration file path. - - It is not possible to install a test file to the default location. - This test checks for FileNotFoundError with the expected default file path. - - """ - # a previous test may have left this - if "BLUESKY_KAFKA_CONFIG_PATH" in os.environ: - del os.environ["BLUESKY_KAFKA_CONFIG_PATH"] - with pytest.raises(FileNotFoundError, match="/etc/bluesky/kafka.yml"): - bluesky_kafka_configuration = configure_kafka_publisher(RE, "abc") - - -def test__read_bluesky_kafka_config_file(tmp_path): - # write a temporary file for this test - test_config_file_path = tmp_path / "bluesky_kafka_config_content.yml" - with open(test_config_file_path, "wt") as f: - f.write(test_bluesky_kafka_config_false) - - bluesky_kafka_config = _read_bluesky_kafka_config_file(str(test_config_file_path)) - - assert bluesky_kafka_config["bootstrap_servers"] == [ - "localhost:9092", - "kafka1:9092", - "kafka2:9092", - ] - - runengine_producer_config = bluesky_kafka_config["runengine_producer_config"] - assert len(runengine_producer_config) == 3 - assert runengine_producer_config["acks"] == 0 - assert runengine_producer_config["message.timeout.ms"] == 3000 - assert runengine_producer_config["compression.codec"] == "snappy" - - -def test__read_bluesky_kafka_config_file_producer_consumer_security(tmp_path): - # write a temporary file for this test - test_config_file_path = tmp_path / "bluesky_kafka_config_content.yml" - with open(test_config_file_path, "wt") as f: - f.write(test_bluesky_kafka_config_security_section) - - bluesky_kafka_config = _read_bluesky_kafka_config_file(str(test_config_file_path)) - - assert bluesky_kafka_config["bootstrap_servers"] == [ - "localhost:9092", - "kafka2:9092", - "kafka3:9092", - ] - - producer_consumer_security_config = bluesky_kafka_config[ - "producer_consumer_security_config" - ] - assert len(producer_consumer_security_config) == 3 - assert producer_consumer_security_config["security.protocol"] == "SASL_SSL" - assert producer_consumer_security_config["sasl.mechanisms"] == "PLAIN" - assert ( - producer_consumer_security_config["ssl.ca.location"] - == "/etc/ssl/certs/ca-bundle.crt" - ) - - runengine_producer_config = bluesky_kafka_config["runengine_producer_config"] - assert len(runengine_producer_config) == 4 - assert runengine_producer_config["compression.codec"] == "snappy" - assert producer_consumer_security_config["security.protocol"] == "SASL_SSL" - assert producer_consumer_security_config["sasl.mechanisms"] == "PLAIN" - assert ( - producer_consumer_security_config["ssl.ca.location"] - == "/etc/ssl/certs/ca-bundle.crt" - ) - - -def test__read_bluesky_kafka_config_file_runengine_topics(tmp_path): - # write a temporary file for this test - test_config_file_path = tmp_path / "bluesky_kafka_config_content.yml" - with open(test_config_file_path, "wt") as f: - f.write(test_bluesky_kafka_config_security_section) - - bluesky_kafka_config = _read_bluesky_kafka_config_file(str(test_config_file_path)) - - runengine_topics = bluesky_kafka_config["runengine_topics"] - assert len(runengine_topics) == 2 - assert runengine_topics[0] == "{endstation}.bluesky.runengine.documents" - assert ( - runengine_topics[1] - == "{endstation}.bluesky.runengine.{document_name}.documents" - ) - - -def test__read_bluesky_kafka_config_file_failure(tmp_path): - """Raise FileNotFoundError if the configuration file does not exist. - - The configuration file path should be reported in the error. - """ - test_config_file_path = tmp_path / "bluesky_kafka_config_content.yml" - - with pytest.raises(FileNotFoundError, match=str(test_config_file_path)): - _read_bluesky_kafka_config_file(str(test_config_file_path)) - - -def test__read_bluesky_kafka_config_file_missing_sections(tmp_path): - """Raise Exception if the configuration file is missing one or more required sections. - - The configuration file path and all missing required sections should be reported in the Exception. - """ - # write a temporary file for this test - test_config_file_path = tmp_path / "bluesky_kafka_config_content.yml" - with open(test_config_file_path, "wt") as f: - # write a configuration file with none of the required sections - f.write("---\n a\n b\n") - - with pytest.raises( - Exception, - match=f".*{str(test_config_file_path)}.*\\['abort_run_on_kafka_exception', 'bootstrap_servers', 'runengine_producer_config'\\]", - ): - _read_bluesky_kafka_config_file(str(test_config_file_path)) - - -def test_configure_kafka_publisher_abort_run_true(tmp_path, RE): - """Test Kafka publisher is configured correctly in the case - abort_run_on_kafka_exception: true - """ - # write a temporary file for this test - test_config_file_path = tmp_path / "bluesky_kafka_config.yml" - with open(test_config_file_path, "wt") as f: - f.write(test_bluesky_kafka_config_true) - - bluesky_kafka_configuration, publisher_details = configure_kafka_publisher( - RE, "abc", override_config_path=test_config_file_path - ) - - assert publisher_details.__class__.__name__ == "SubscribeKafkaPublisherDetails" - assert publisher_details.beamline_topic == "abc.bluesky.runengine.documents" - assert ( - publisher_details.bootstrap_servers == "localhost:9092,kafka1:9092,kafka2:9092" - ) - assert publisher_details.re_subscribe_token == 0 - - -def test_configure_kafka_publisher_abort_run_false(tmp_path, RE): - """Test Kafka publisher is configured correctly in the case - abort_run_on_kafka_exception: false - """ - # write a temporary file for this test - test_config_file_path = tmp_path / "bluesky_kafka_config.yml" - with open(test_config_file_path, "wt") as f: - f.write(test_bluesky_kafka_config_false) - - bluesky_kafka_configuration, publisher_details = configure_kafka_publisher( - RE, "abc", override_config_path=test_config_file_path - ) - - assert ( - publisher_details.__class__.__name__ - == "SubscribeKafkaQueueThreadPublisherDetails" - ) - assert publisher_details.beamline_topic == "abc.bluesky.runengine.documents" - assert ( - publisher_details.bootstrap_servers == "localhost:9092,kafka1:9092,kafka2:9092" - ) - assert publisher_details.re_subscribe_token is None diff --git a/nslsii/tests/test_kafka_publisher.py b/nslsii/tests/test_kafka_publisher.py deleted file mode 100644 index 7659696b..00000000 --- a/nslsii/tests/test_kafka_publisher.py +++ /dev/null @@ -1,251 +0,0 @@ -import uuid - -from unittest.mock import Mock - -import pytest - -import nslsii -import nslsii.kafka_utils - -from bluesky.plans import count -from bluesky_kafka import BlueskyKafkaException -from event_model import sanitize_doc - - -def test__subscribe_kafka_publisher( - kafka_bootstrap_servers, - temporary_topics, - consume_documents_from_kafka_until_first_stop_document, - RE, - hw, -): - """Test abort run on Kafka exception. - - This test follows the pattern in bluesky_kafka/tests/test_in_single_process.py, - which is to publish Kafka messages _before_ subscribing a Kafka consumer to - those messages. After the messages have been published a consumer is subscribed - to the topic and should receive all messages since they will have been cached by - the Kafka broker(s). This keeps the test code relatively simple. - - Start Kafka and Zookeeper like this: - $ sudo docker-compose -f scripts/bitnami-kafka-docker-compose.yml up - - Remove Kafka and Zookeeper containers like this: - $ sudo docker ps -a -q - 78485383ca6f - 8a80fb4a385f - $ sudo docker stop 78485383ca6f 8a80fb4a385f - 78485383ca6f - 8a80fb4a385f - $ sudo docker rm 78485383ca6f 8a80fb4a385f - 78485383ca6f - 8a80fb4a385f - - Or remove ALL containers like this: - $ sudo docker stop $(sudo docker ps -a -q) - $ sudo docker rm $(sudo docker ps -a -q) - Use this in difficult cases to remove *all traces* of docker containers: - $ sudo docker system prune -a - - Parameters - ---------- - kafka_bootstrap_servers: str (pytest fixture) - comma-delimited string of Kafka broker host:port, for example "kafka1:9092,kafka2:9092" - temporary_topics: context manager (pytest fixture) - creates and cleans up temporary Kafka topics for testing - RE: pytest fixture - bluesky RunEngine - hw: pytest fixture - ophyd simulated hardware objects - """ - - # use a random string as the beamline name so topics will not be duplicated across tests - beamline_name = str(uuid.uuid4())[:8] - with temporary_topics(topics=[f"{beamline_name}.bluesky.runengine.documents"]) as ( - beamline_topic, - ): - - subscribe_kafka_publisher_details = ( - nslsii.kafka_utils._subscribe_kafka_publisher( - RE=RE, - beamline_name=beamline_name, - bootstrap_servers=kafka_bootstrap_servers, - producer_config={ - "acks": "all", - "enable.idempotence": False, - "request.timeout.ms": 1000, - }, - ) - ) - - assert subscribe_kafka_publisher_details.beamline_topic == beamline_topic - assert isinstance(subscribe_kafka_publisher_details.re_subscribe_token, int) - - published_bluesky_documents = [] - - # this function will store all documents - # published by the RunEngine in a list - def store_published_document(name, document): - published_bluesky_documents.append((name, document)) - - RE.subscribe(store_published_document) - - RE(count([hw.det])) - - # it is known that RE(count()) will produce four - # documents: start, descriptor, event, stop - assert len(published_bluesky_documents) == 4 - - consumed_bluesky_documents = ( - consume_documents_from_kafka_until_first_stop_document( - kafka_topic=subscribe_kafka_publisher_details.beamline_topic - ) - ) - - assert len(published_bluesky_documents) == len(consumed_bluesky_documents) - - # sanitize_doc normalizes some document data, such as numpy arrays, that are - # problematic for direct comparison of documents by 'assert' - sanitized_published_bluesky_documents = [ - sanitize_doc(doc) for doc in published_bluesky_documents - ] - sanitized_consumed_bluesky_documents = [ - sanitize_doc(doc) for doc in consumed_bluesky_documents - ] - - assert len(sanitized_consumed_bluesky_documents) == len( - sanitized_published_bluesky_documents - ) - - # the Kafka publisher will publish event_page rather than event - # so check start, descriptor, and stop documents only - for i in (0, 1, 3): - assert ( - sanitized_consumed_bluesky_documents[i] - == sanitized_published_bluesky_documents[i] - ) - - -def test_no_broker( - temporary_topics, - RE, - hw, -): - """Test the case of no Kafka broker. - - An exception should interrupt the RunEngine. - - Parameters - ---------- - temporary_topics: context manager (pytest fixture) - creates and cleans up temporary Kafka topics for testing - RE: pytest fixture - bluesky RunEngine - hw: pytest fixture - ophyd simulated hardware objects - """ - - # use a random string as the beamline name so topics will not be duplicated across tests - beamline_name = str(uuid.uuid4())[:8] - with temporary_topics(topics=[f"{beamline_name}.bluesky.runengine.documents"]) as ( - beamline_topic, - ): - - subscribe_kafka_publisher_details = ( - nslsii.kafka_utils._subscribe_kafka_publisher( - RE=RE, - beamline_name=beamline_name, - bootstrap_servers="100.100.100.100:9092", - producer_config={ - "acks": "all", - "enable.idempotence": False, - "request.timeout.ms": 1000, - }, - ) - ) - - assert subscribe_kafka_publisher_details.beamline_topic == beamline_topic - assert isinstance(subscribe_kafka_publisher_details.re_subscribe_token, int) - - published_bluesky_documents = [] - - # this function will store all documents - # published by the RunEngine in a list - def store_published_document(name, document): - published_bluesky_documents.append((name, document)) - - RE.subscribe(store_published_document) - - with pytest.raises(Exception): - RE(count([hw.det])) - - # only a stop document is expected ??? - assert len(published_bluesky_documents) == 1 - assert published_bluesky_documents[0][0] == "stop" - - -def test_exception_on_publisher_call( - kafka_bootstrap_servers, - temporary_topics, - RE, - hw, -): - """Test the case of an exception raised by Publisher.__call__. - - The exception should interrupt the RunEngine. This test simulates a failure - to publish a bluesky document as a Kafka message. - - Parameters - ---------- - kafka_bootstrap_servers: str (pytest fixture) - comma-delimited string of Kafka broker host:port, for example "kafka1:9092,kafka2:9092" - temporary_topics: context manager (pytest fixture) - creates and cleans up temporary Kafka topics for testing - RE: pytest fixture - bluesky RunEngine - hw: pytest fixture - ophyd simulated hardware objects - """ - - # use a random string as the beamline name so topics will not be duplicated across tests - beamline_name = str(uuid.uuid4())[:8] - with temporary_topics(topics=[f"{beamline_name}.bluesky.runengine.documents"]) as ( - beamline_topic, - ): - - def mock_publisher_factory(*args, **kwargs): - # the mock publisher will raise BlueskyKafkaException on every method call - # but only __call__ will be invoked - return Mock(side_effect=BlueskyKafkaException) - - subscribe_kafka_publisher_details = nslsii.kafka_utils._subscribe_kafka_publisher( - RE=RE, - beamline_name=beamline_name, - bootstrap_servers=kafka_bootstrap_servers, - producer_config={ - "acks": "all", - "enable.idempotence": False, - "request.timeout.ms": 1000, - }, - # use a mock-ed publisher - _publisher_factory=mock_publisher_factory, - ) - - assert subscribe_kafka_publisher_details.beamline_topic == beamline_topic - assert isinstance(subscribe_kafka_publisher_details.re_subscribe_token, int) - - published_bluesky_documents = [] - - # this function will store all documents - # published by the RunEngine in a list - def store_published_document(name, document): - published_bluesky_documents.append((name, document)) - - RE.subscribe(store_published_document) - - with pytest.raises(BlueskyKafkaException): - RE(count([hw.det])) - - # the RE will publish a stop document - assert len(published_bluesky_documents) == 1 - assert published_bluesky_documents[0][0] == "stop" diff --git a/nslsii/tests/test_kafka_queue_thread_publisher.py b/nslsii/tests/test_kafka_queue_thread_publisher.py deleted file mode 100644 index e40bccbb..00000000 --- a/nslsii/tests/test_kafka_queue_thread_publisher.py +++ /dev/null @@ -1,208 +0,0 @@ -import io -import logging -import uuid - -from bluesky.plans import count -from event_model import sanitize_doc - -import nslsii -import nslsii.kafka_utils - - -def test_build_and_subscribe_kafka_queue_thread_publisher( - kafka_bootstrap_servers, - temporary_topics, - consume_documents_from_kafka_until_first_stop_document, - RE, - hw, -): - """Test threaded publishing of Kafka messages. - - This test follows the pattern in bluesky_kafka/tests/test_in_single_process.py, - which is to publish Kafka messages _before_ subscribing a Kafka consumer to - those messages. After the messages have been published a consumer is subscribed - to the topic and should receive all messages since they will have been cached by - the Kafka broker(s). This keeps the test code relatively simple. - - Start Kafka and Zookeeper like this: - $ sudo docker-compose -f scripts/bitnami-kafka-docker-compose.yml up - - Remove Kafka and Zookeeper containers like this: - $ sudo docker ps -a -q - 78485383ca6f - 8a80fb4a385f - $ sudo docker stop 78485383ca6f 8a80fb4a385f - 78485383ca6f - 8a80fb4a385f - $ sudo docker rm 78485383ca6f 8a80fb4a385f - 78485383ca6f - 8a80fb4a385f - - Or remove ALL containers like this: - $ sudo docker stop $(sudo docker ps -a -q) - $ sudo docker rm $(sudo docker ps -a -q) - Use this in difficult cases to remove *all traces* of docker containers: - $ sudo docker system prune -a - - Parameters - ---------- - kafka_bootstrap_servers: str (pytest fixture) - comma-delimited string of Kafka broker host:port, for example "kafka1:9092,kafka2:9092" - temporary_topics: context manager (pytest fixture) - creates and cleans up temporary Kafka topics for testing - RE: pytest fixture - bluesky RunEngine - hw: pytest fixture - ophyd simulated hardware objects - """ - - # use a random string as the beamline name so topics will not be duplicated across tests - beamline_name = str(uuid.uuid4())[:8] - with temporary_topics(topics=[f"{beamline_name}.bluesky.runengine.documents"]) as ( - beamline_topic, - ): - - subscribe_kafka_queue_thread_publisher_details = ( - nslsii.kafka_utils._subscribe_kafka_queue_thread_publisher( - RE=RE, - beamline_name=beamline_name, - bootstrap_servers=kafka_bootstrap_servers, - producer_config={ - "acks": "all", - "enable.idempotence": False, - "request.timeout.ms": 1000, - }, - ) - ) - - assert ( - subscribe_kafka_queue_thread_publisher_details.beamline_topic - == beamline_topic - ) - assert isinstance( - subscribe_kafka_queue_thread_publisher_details.re_subscribe_token, int - ) - - published_bluesky_documents = [] - - # this function will store all documents - # published by the RunEngine in a list - def store_published_document(name, document): - published_bluesky_documents.append((name, document)) - - RE.subscribe(store_published_document) - - RE(count([hw.det])) - - # it is known that RE(count()) will produce four - # documents: start, descriptor, event, stop - assert len(published_bluesky_documents) == 4 - - consumed_bluesky_documents = consume_documents_from_kafka_until_first_stop_document( - kafka_topic=subscribe_kafka_queue_thread_publisher_details.beamline_topic - ) - - assert len(published_bluesky_documents) == len(consumed_bluesky_documents) - - # sanitize_doc normalizes some document data, such as numpy arrays, that are - # problematic for direct comparison of documents by 'assert' - sanitized_published_bluesky_documents = [ - sanitize_doc(doc) for doc in published_bluesky_documents - ] - sanitized_consumed_bluesky_documents = [ - sanitize_doc(doc) for doc in consumed_bluesky_documents - ] - - assert len(sanitized_consumed_bluesky_documents) == len( - sanitized_published_bluesky_documents - ) - assert ( - sanitized_consumed_bluesky_documents - == sanitized_published_bluesky_documents - ) - - -def test_no_beamline_topic(kafka_bootstrap_servers, RE): - """ - If the beamline Kafka topic does not exist then an exception - should be raised and handled by writing an exception message - to the nslsii logger. - - Parameters - ---------- - kafka_bootstrap_servers: str (pytest fixture) - comma-delimited string of Kafka broker host:port, for example "kafka1:9092,kafka2:9092" - RE: RunEngine (pytest fixture) - bluesky RunEngine - """ - try: - logging_test_output = io.StringIO() - nslsii_logger = logging.getLogger("nslsii") - logging_test_handler = logging.StreamHandler(stream=logging_test_output) - logging_test_handler.setFormatter(logging.Formatter("%(message)s")) - nslsii_logger.addHandler(logging_test_handler) - - # use a random string as the beamline name so topics will not be duplicated across tests - beamline_name = str(uuid.uuid4())[:8] - nslsii.kafka_utils._subscribe_kafka_queue_thread_publisher( - RE=RE, - beamline_name=beamline_name, - bootstrap_servers=kafka_bootstrap_servers, - producer_config={ - "acks": "all", - "enable.idempotence": False, - "request.timeout.ms": 1000, - }, - ) - - assert ( - f"topic `{beamline_name}.bluesky.runengine.documents` does not exist on Kafka broker(s)" - in logging_test_output.getvalue() - ) - - finally: - nslsii_logger.removeHandler(hdlr=logging_test_handler) - - -def test_publisher_with_no_broker(RE, hw): - """ - Test the case of no Kafka broker. - """ - beamline_name = str(uuid.uuid4())[:8] - subscribe_kafka_queue_thread_publisher_details = nslsii.kafka_utils._subscribe_kafka_queue_thread_publisher( - RE=RE, - beamline_name=beamline_name, - # specify a bootstrap server that does not exist - bootstrap_servers="100.100.100.100:9092", - producer_config={ - "acks": "all", - "enable.idempotence": False, - "request.timeout.ms": 1000, - }, - publisher_queue_timeout=1, - ) - - assert subscribe_kafka_queue_thread_publisher_details.re_subscribe_token is None - - published_bluesky_documents = [] - - # this function will store all documents - # published by the RunEngine in a list - def store_published_document(name, document): - published_bluesky_documents.append((name, document)) - - RE.subscribe(store_published_document) - - import time - - t0 = time.time() - RE(count([hw.det1])) - t1 = time.time() - - # timeout is set at 1s but it takes longer than 5s to run count - # so running count should take less than 10s - print(f"time for count: {t1-t0:.3f}") - assert (t1 - t0) < 10.0 - - # the RunEngine should have published 4 documents - assert len(published_bluesky_documents) == 4 diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..740d4775 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,203 @@ +[build-system] +requires = ["setuptools>=77", "setuptools_scm[toml]>=7", "versioneer[toml]"] +build-backend = "setuptools.build_meta" + +[project] +name = "nslsii" +authors = [ + { name = "NSLS2", email = "dssi@bnl.gov" }, +] +description = "A great package." +readme = "README.md" +license = "BSD-3-Clause" +requires-python = ">=3.9" +classifiers = [ + "Development Status :: 1 - Planning", + "Intended Audience :: Science/Research", + "Intended Audience :: Developers", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Topic :: Scientific/Engineering", + "Typing :: Typed", +] +dynamic = ["version"] +dependencies = [ + "appdirs", + "bluesky-kafka>=0.8.0", + "bluesky>=1.8.1", + "caproto", + "databroker", + "h5py", + "httpx", + "ipython", + "ipywidgets", + "ldap3", + "matplotlib", + "msgpack >= 1.0.0", + "msgpack-numpy", + "numpy", + "opencv-python", + "ophyd", + "ophyd-async <=0.12.3", + "packaging", + "pillow", + "psutil", + "pycryptodome", + "pyolog", + "redis", + "redis-json-dict", + "requests", + "setuptools", + "shortuuid", +] + +[project.urls] +Homepage = "https://github.com/NSLS-II/nslsii" +"Bug Tracker" = "https://github.com/NSLS-II/nslsii/issues" +Discussions = "https://github.com/NSLS-II/nslsii/discussions" +Changelog = "https://github.com/NSLS-II/nslsii/releases" + +[tool.setuptools.packages.find] +where = ["src"] + +[dependency-groups] +test = [ + "pytest >=6", + "pytest-cov >=3", +] +dev = [ + { include-group = "test" }, + "attrs>=17.40", + "codecov", + "coverage", + "flake8", + "ipython", + "matplotlib", + "numpydoc", + "pytest", + "sphinx", + "sphinx_rtd_theme", + "area_detector_handlers", + "pre-commit", + "ruff", +] +docs = [ + "sphinx>=7.0", + "myst_parser>=0.13", + "sphinx_copybutton", + "sphinx_autodoc_typehints", + "furo>=2023.08.17", +] + + +[tool.setuptools_scm] +write_to = "src/nslsii/_version.py" + + +[tool.pytest.ini_options] +minversion = "6.0" +addopts = ["-ra", "--showlocals", "--strict-markers", "--strict-config"] +xfail_strict = true +filterwarnings = [ + "error", +] +log_cli_level = "INFO" +testpaths = [ + "tests", +] +pythonpath = [ + "src", +] + + +[tool.coverage] +run.source = ["nslsii"] +report.exclude_also = [ + '\.\.\.', + 'if typing.TYPE_CHECKING:', +] + +[tool.mypy] +files = ["src", "tests"] +python_version = "3.9" +warn_unused_configs = true +strict = true +enable_error_code = ["redundant-expr", "truthy-bool"] +warn_unreachable = true +disallow_untyped_defs = false +disallow_incomplete_defs = false + +[[tool.mypy.overrides]] +module = "nslsii.*" +disallow_untyped_defs = true +disallow_incomplete_defs = true + + +[tool.ruff] + +[tool.ruff.lint] +extend-select = [ + "ARG", # flake8-unused-arguments + "B", # flake8-bugbear + "C4", # flake8-comprehensions + "EM", # flake8-errmsg + "EXE", # flake8-executable + "G", # flake8-logging-format + "I", # isort + "ICN", # flake8-import-conventions + "NPY", # NumPy specific rules + "PD", # pandas-vet + "PGH", # pygrep-hooks + "PIE", # flake8-pie + "PL", # pylint + "PT", # flake8-pytest-style + "PTH", # flake8-use-pathlib + "RET", # flake8-return + "RUF", # Ruff-specific + "SIM", # flake8-simplify + "T20", # flake8-print + "UP", # pyupgrade + "YTT", # flake8-2020 +] +ignore = [ + "PLR09", # Too many <...> + "PLR2004", # Magic value used in comparison +] +isort.required-imports = ["from __future__ import annotations"] +# Uncomment if using a _compat.typing backport +# typing-modules = ["nslsii._compat.typing"] + +[tool.ruff.lint.per-file-ignores] +"tests/**" = ["T20"] +"noxfile.py" = ["T20"] + +[tool.uv.extra-build-dependencies] +nslsii = ["versioneer"] + +[tool.versioneer] +VCS = "git" +style = "pep440" +versionfile_source = "src/nslsii/_version.py" +tag_prefix = "" +parentdir_prefix = "" + +[tool.pylint] +py-version = "3.9" +ignore-paths = [".*/_version.py"] +reports.output-format = "colorized" +similarities.ignore-imports = "yes" +messages_control.disable = [ + "design", + "fixme", + "line-too-long", + "missing-module-docstring", + "missing-function-docstring", + "wrong-import-position", +] diff --git a/pytest.ini b/pytest.ini index 122fee2b..00a574cb 100644 --- a/pytest.ini +++ b/pytest.ini @@ -3,4 +3,4 @@ log_cli = True log_cli_format = %(asctime)s - %(threadName)s - %(name)s - [%(filename)s #%(lineno)s] - %(levelname)s - %(message)s log_cli_level = WARNING -testpaths = nslsii/tests \ No newline at end of file +testpaths = nslsii/tests diff --git a/requirements-dev.txt b/requirements-dev.txt index de53051c..effc3707 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,3 +1,4 @@ +area_detector_handlers # These are required for developing the package (running the tests, building # the documentation) but not necessarily required for _using_ it. attrs>=17.4.0 @@ -7,9 +8,8 @@ flake8 ipython matplotlib numpydoc +pre-commit pytest +ruff sphinx sphinx_rtd_theme -area_detector_handlers -pre-commit -ruff diff --git a/requirements.txt b/requirements.txt index 9146b53f..625b4b0a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,6 @@ appdirs -bluesky-kafka>=0.8.0 bluesky>=1.8.1 +bluesky-kafka>=0.8.0 caproto databroker h5py diff --git a/scripts/bitnami-kafka-docker-compose.yml b/scripts/bitnami-kafka-docker-compose.yml index 03334810..16d13954 100644 --- a/scripts/bitnami-kafka-docker-compose.yml +++ b/scripts/bitnami-kafka-docker-compose.yml @@ -1,18 +1,18 @@ -version: '3' +version: "3" services: zookeeper: - image: 'docker.io/bitnami/zookeeper:latest' + image: "docker.io/bitnami/zookeeper:latest" ports: - - '2181:2181' + - "2181:2181" #volumes: # - 'zookeeper_data:/bitnami' environment: - ALLOW_ANONYMOUS_LOGIN=yes kafka: - image: 'docker.io/bitnami/kafka:latest' + image: "docker.io/bitnami/kafka:latest" ports: - - '9092:9092' + - "9092:9092" #- '29092:29092' #volumes: # - 'kafka_data:/bitnami' @@ -30,7 +30,6 @@ services: #- KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092 depends_on: - zookeeper - #volumes: # zookeeper_data: # driver: local diff --git a/setup.py b/setup.py index d43826cb..2911eb2f 100644 --- a/setup.py +++ b/setup.py @@ -1,37 +1,38 @@ -from __future__ import (absolute_import, division, print_function) - -import versioneer -import setuptools +from __future__ import annotations # To use a consistent encoding from codecs import open -from os import path +from pathlib import Path + +import setuptools + +import versioneer -here = path.abspath(path.dirname(__file__)) +here = Path(__file__).resolve().parent # Get the long description from the README file -with open(path.join(here, 'README.md'), encoding='utf-8') as f: +with open(here.joinpath("README.md"), encoding="utf-8") as f: long_description = f.read() -with open(path.join(here, 'requirements.txt')) as f: +with open(here.joinpath("requirements.txt"), encoding="utf-8") as f: requirements = f.read().splitlines() setuptools.setup( - name='nslsii', + name="nslsii", version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), license="BSD (3-clause)", packages=setuptools.find_packages(), long_description=long_description, - long_description_content_type='text/markdown', - description='Tools for data collection and analysis at NSLS-II', - author='Brookhaven National Laboratory', + long_description_content_type="text/markdown", + description="Tools for data collection and analysis at NSLS-II", + author="Brookhaven National Laboratory", install_requires=requirements, entry_points={ "console_scripts": [ "sync-experiment = nslsii.sync_experiment:main", "what-is-ioc = nslsii.epics_utils:main", - "axis-saver-ioc = nslsii.iocs.caproto_saver:start_axis_ioc" + "axis-saver-ioc = nslsii.iocs.caproto_saver:start_axis_ioc", ], }, ) diff --git a/nslsii/__init__.py b/src/nslsii/__init__.py similarity index 89% rename from nslsii/__init__.py rename to src/nslsii/__init__.py index f171de11..dbc9c3bc 100644 --- a/nslsii/__init__.py +++ b/src/nslsii/__init__.py @@ -1,3 +1,11 @@ +""" +Copyright (c) 2025. All rights reserved. + +nslsii: NSLS-II related devices +""" + +from __future__ import annotations + import logging import os import sys @@ -8,12 +16,17 @@ import appdirs from IPython import get_ipython +# from ._version import version as __version__ + +# __version__ = _version.get_versions()['version'] +# __all__ = ["__version__"] +# del get_versions + from ._version import get_versions __version__ = get_versions()["version"] del get_versions - bluesky_log_file_path = None @@ -115,7 +128,7 @@ def configure_base( >>>> configure_base(get_ipython().user_ns, 'chx'); """ - from packaging.version import parse + from packaging.version import parse # noqa : PLC0415 ipython = get_ipython() @@ -123,17 +136,18 @@ def configure_base( # Protect against double-subscription. SENTINEL = "__nslsii_configure_base_has_been_run" if user_ns.get(SENTINEL): - raise RuntimeError("configure_base should only be called once per process.") + msg = "configure_base should only be called once per process." + raise RuntimeError(msg) ns[SENTINEL] = True # Set up a RunEngine and use metadata backed by files on disk. - from bluesky import RunEngine - from bluesky import __version__ as bluesky_version + from bluesky import RunEngine # noqa : PLC0415 + from bluesky import __version__ as bluesky_version # noqa : PLC0415 if redis_url is None: md = {} else: - from redis import Redis - from redis_json_dict import RedisJSONDict + from redis import Redis # noqa : PLC0415 + from redis_json_dict import RedisJSONDict # noqa : PLC0415 md = RedisJSONDict(Redis(redis_url), prefix=redis_prefix) @@ -148,7 +162,7 @@ def configure_base( # Set up SupplementalData. # (This is a no-op until devices are added to it, # so there is no need to provide a 'skip_sd' switch.) - from bluesky import SupplementalData + from bluesky import SupplementalData # noqa : PLC0415 sd = SupplementalData() RE.preprocessors.append(sd) @@ -156,23 +170,18 @@ def configure_base( if isinstance(broker_name, str): # Set up a Broker. - from databroker import Broker + from databroker import Broker # noqa : PLC0415 db = Broker.named(broker_name) ns["db"] = db else: db = broker_name - if db is not None: - if hasattr(db, "insert"): - # subscribe using insert if it exists - RE.subscribe(db.insert) - else: - RE.subscribe(db) + RE.subscribe(db.insert) if pbar: # Add a progress bar. - from bluesky.utils import ProgressBarManager + from bluesky.utils import ProgressBarManager # noqa : PLC0415 pbar_manager = ProgressBarManager() RE.waiting_hook = pbar_manager @@ -180,14 +189,14 @@ def configure_base( if magics: # Register bluesky IPython magics. - from bluesky.magics import BlueskyMagics + from bluesky.magics import BlueskyMagics # noqa : PLC0415 if ipython: ipython.register_magics(BlueskyMagics) if bec: # Set up the BestEffortCallback. - from bluesky.callbacks.best_effort import BestEffortCallback + from bluesky.callbacks.best_effort import BestEffortCallback # noqa : PLC0415 _bec_kwargs = {} if bec_derivative: @@ -200,20 +209,20 @@ def configure_base( if mpl: # Import matplotlib and put it in interactive mode. - import matplotlib.pyplot as plt + import matplotlib.pyplot as plt # noqa : PLC0415 ns["plt"] = plt plt.ion() # Make plots update live while scans run. if parse(bluesky_version) < parse("1.6.0"): - from bluesky.utils import install_kicker + from bluesky.utils import install_kicker # noqa : PLC0415 install_kicker() if epics_context: # Create a context in the underlying EPICS client. - from ophyd import setup_ophyd + from ophyd import setup_ophyd # noqa : PLC0415 setup_ophyd() @@ -221,7 +230,7 @@ def configure_base( configure_bluesky_logging(ipython=ipython) if ipython_logging and ipython: - from nslsii.common.ipynb.logutils import log_exception + from nslsii.common.ipynb.logutils import log_exception # noqa : PLC0415 # IPython logging will be enabled with logstart(...) configure_ipython_logging(exception_logger=log_exception, ipython=ipython) @@ -234,10 +243,11 @@ def configure_base( elif isinstance(broker_name, str): configure_kafka_publisher(RE, beamline_name=broker_name) else: - raise ValueError( + msg = ( "If broker_name is not a string and lacks a name attribute, " "publish_documents_with_kafka must be a string" ) + raise ValueError(msg) if tb_minimize and ipython: # configure %xmode minimal @@ -248,21 +258,21 @@ def configure_base( # some of the * imports are for 'back-compatibility' of a sort -- we have # taught BL staff to expect LiveTable and LivePlot etc. to be in their # namespace - import numpy as np + import numpy as np # noqa : PLC0415 ns["np"] = np - import bluesky.callbacks + import bluesky.callbacks # noqa : PLC0415 ns["bc"] = bluesky.callbacks import_star(bluesky.callbacks, ns) - import bluesky.plans + import bluesky.plans # noqa : PLC0415 ns["bp"] = bluesky.plans import_star(bluesky.plans, ns) - import bluesky.plan_stubs + import bluesky.plan_stubs # noqa : PLC0415 ns["bps"] = bluesky.plan_stubs import_star(bluesky.plan_stubs, ns) @@ -272,15 +282,15 @@ def configure_base( ns["mov"] = bluesky.plan_stubs.mov ns["movr"] = bluesky.plan_stubs.movr - import bluesky.preprocessors + import bluesky.preprocessors # noqa : PLC0415 ns["bpp"] = bluesky.preprocessors - import bluesky.callbacks.broker + import bluesky.callbacks.broker # noqa : PLC0415 import_star(bluesky.callbacks.broker, ns) - import bluesky.simulators + import bluesky.simulators # noqa : PLC0415 import_star(bluesky.simulators, ns) @@ -326,11 +336,11 @@ def configure_bluesky_logging( log file path """ - global bluesky_log_file_path + global bluesky_log_file_path # noqa : PLW0603 if "BLUESKY_LOG_FILE" in os.environ: bluesky_log_file_path = Path(os.environ["BLUESKY_LOG_FILE"]) - print( + print( # noqa : T201 f"bluesky log file path configured from environment variable" f" BLUESKY_LOG_FILE: '{bluesky_log_file_path}'", file=sys.stderr, @@ -340,7 +350,7 @@ def configure_bluesky_logging( if not bluesky_log_dir.exists(): bluesky_log_dir.mkdir(parents=True, exist_ok=True) bluesky_log_file_path = bluesky_log_dir / Path("bluesky.log") - print( + print( # noqa : T201 f"environment variable BLUESKY_LOG_FILE is not set," f" using default log file path '{bluesky_log_file_path}'", file=sys.stderr, @@ -432,7 +442,7 @@ def configure_ipython_logging( if "BLUESKY_IPYTHON_LOG_FILE" in os.environ: bluesky_ipython_log_file_path = Path(os.environ["BLUESKY_IPYTHON_LOG_FILE"]) - print( + print( # noqa : T201 "bluesky ipython log file configured from environment" f" variable BLUESKY_IPYTHON_LOG_FILE: '{bluesky_ipython_log_file_path}'", file=sys.stderr, @@ -444,7 +454,7 @@ def configure_ipython_logging( bluesky_ipython_log_file_path = bluesky_ipython_log_dir / Path( "bluesky_ipython.log" ) - print( + print( # noqa : T201 "environment variable BLUESKY_IPYTHON_LOG_FILE is not set," f" using default file path '{bluesky_ipython_log_file_path}'", file=sys.stderr, @@ -454,7 +464,7 @@ def configure_ipython_logging( # if a previous copy exists just overwrite it if ( bluesky_ipython_log_file_path.exists() - and os.path.getsize(bluesky_ipython_log_file_path) >= rotate_file_size + and bluesky_ipython_log_file_path.stat().st_size >= rotate_file_size ): bluesky_ipython_log_file_path.rename( str(bluesky_ipython_log_file_path) + ".old" @@ -483,7 +493,7 @@ def configure_kafka_publisher(RE, beamline_name, override_config_path=None): See `tests/test_kafka_configuration.py` for an example configuration file. """ - from nslsii.kafka_utils import ( + from nslsii.kafka_utils import ( # noqa : PLC0415 _read_bluesky_kafka_config_file, _subscribe_kafka_publisher, _subscribe_kafka_queue_thread_publisher, @@ -578,13 +588,13 @@ def configure_olog(user_ns, *, callback=None, subscribe=True): ns = {} # We will update user_ns with this at the end. - import queue - import threading - from functools import partial - from warnings import warn + import queue # noqa : PLC0415 + import threading # noqa : PLC0415 + from functools import partial # noqa : PLC0415 + from warnings import warn # noqa : PLC0415 - from bluesky.callbacks.olog import logbook_cb_factory - from pyOlog import SimpleOlogClient + from bluesky.callbacks.olog import logbook_cb_factory # noqa : PLC0415 + from pyOlog import SimpleOlogClient # noqa : PLC0415 # This is for pyOlog.ophyd_tools.get_logbook, which simply looks for # a variable called 'logbook' in the global IPython namespace. @@ -610,7 +620,8 @@ def submit_to_olog(queue, cb): except Exception as exc: warn( "This olog is giving errors. This will not be logged." - "Error:" + str(exc) + "Error:" + str(exc), + stacklevel=2, ) olog_queue = queue.Queue(maxsize=100) @@ -624,14 +635,17 @@ def send_to_olog_queue(name, doc): try: olog_queue.put((name, doc), block=False) except queue.Full: - warn("The olog queue is full. This will not be logged.") + warn("The olog queue is full. This will not be logged.", stacklevel=2) RE = user_ns["RE"] RE.subscribe(send_to_olog_queue, "start") - import pyOlog.ophyd_tools + import pyOlog.ophyd_tools # noqa : PLC0415 import_star(pyOlog.ophyd_tools, ns) user_ns.update(ns) return list(ns) + +from . import _version +__version__ = _version.get_versions()['version'] diff --git a/nslsii/_version.py b/src/nslsii/_version.py similarity index 99% rename from nslsii/_version.py rename to src/nslsii/_version.py index 07508f5d..9a9325e5 100644 --- a/nslsii/_version.py +++ b/src/nslsii/_version.py @@ -517,4 +517,4 @@ def get_versions(): return {"version": "0+unknown", "full-revisionid": None, "dirty": None, - "error": "unable to compute version", "date": None} + "error": "unable to compute version", "date": None} \ No newline at end of file diff --git a/src/nslsii/ad33.py b/src/nslsii/ad33.py new file mode 100644 index 00000000..71aa5ece --- /dev/null +++ b/src/nslsii/ad33.py @@ -0,0 +1,266 @@ +"""Classes to help with supporting AreaDetector 33 (and the +wait_for_plugins functionality) + + +This is actually adding a mix of functionality from AD 2-2 to 3-3 and +all of these names may change in the future. + +""" + +from __future__ import annotations + +import time as ttime + +from ophyd import Component as Cpt +from ophyd import Device +from ophyd.areadetector.base import ADBase, ad_group +from ophyd.areadetector.base import ADComponent as ADCpt +from ophyd.areadetector.base import EpicsSignalWithRBV as SignalWithRBV +from ophyd.areadetector.plugins import PluginBase +from ophyd.areadetector.trigger_mixins import ADTriggerStatus, TriggerBase +from ophyd.device import DynamicDeviceComponent as DDC +from ophyd.device import Staged +from ophyd.quadem import QuadEM +from ophyd.signal import EpicsSignal, EpicsSignalRO, Signal + + +class V22Mixin(Device): ... + + +class V26Mixin(V22Mixin): + adcore_version = Cpt(EpicsSignalRO, "ADCoreVersion_RBV", string=True, kind="config") + driver_version = Cpt(EpicsSignalRO, "DriverVersion_RBV", string=True, kind="config") + + +class V33Mixin(V26Mixin): ... + + +class CamV33Mixin(V33Mixin): + wait_for_plugins = Cpt(EpicsSignal, "WaitForPlugins", string=True, kind="config") + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.stage_sigs["wait_for_plugins"] = "Yes" + + def ensure_nonblocking(self): + self.stage_sigs["wait_for_plugins"] = "Yes" + for c in self.parent.component_names: + cpt = getattr(self.parent, c) + if cpt is self: + continue + if hasattr(cpt, "ensure_nonblocking"): + cpt.ensure_nonblocking() + + +class FilePluginV22Mixin(V22Mixin): + create_directories = Cpt(EpicsSignal, "CreateDirectory", kind="config") + + +class SingleTriggerV33(TriggerBase): + _status_type = ADTriggerStatus + + def __init__(self, *args, image_name=None, **kwargs): + super().__init__(*args, **kwargs) + if image_name is None: + image_name = "_".join([self.name, "image"]) + self._image_name = image_name + + def trigger(self): + "Trigger one acquisition." + if self._staged != Staged.yes: + msg = ( + "This detector is not ready to trigger." + "Call the stage() method before triggering." + ) + raise RuntimeError(msg) + + self._status = self._status_type(self) + + def _acq_done(*args, **kwargs): # noqa : ARG001 + # TODO sort out if anything useful in here + self._status._finished() + + self._acquisition_signal.put(1, use_complete=True, callback=_acq_done) + self.generate_datum(self._image_name, ttime.time(), {}) + return self._status + + +class StatsPluginV33(PluginBase): + """This supports changes to time series PV names in AD 3-3 + + Due to https://github.com/areaDetector/ADCore/pull/333 + """ + + _default_suffix = "Stats1:" + _suffix_re = r"Stats\d:" + from typing import ClassVar # noqa : PLC0415 + + _html_docs: ClassVar[list[str]] = ["NDPluginStats.html"] + _plugin_type = "NDPluginStats" + + _default_configuration_attrs = ( + *PluginBase._default_configuration_attrs, + "centroid_threshold", + "compute_centroid", + "compute_histogram", + "compute_profiles", + "compute_statistics", + "bgd_width", + "hist_size", + "hist_min", + "hist_max", + "ts_num_points", + "profile_size", + "profile_cursor", + ) + + bgd_width = ADCpt(SignalWithRBV, "BgdWidth") + centroid_threshold = ADCpt(SignalWithRBV, "CentroidThreshold") + + centroid = DDC( + ad_group(EpicsSignalRO, (("x", "CentroidX_RBV"), ("y", "CentroidY_RBV"))), + doc="The centroid XY", + default_read_attrs=("x", "y"), + ) + + compute_centroid = ADCpt(SignalWithRBV, "ComputeCentroid", string=True) + compute_histogram = ADCpt(SignalWithRBV, "ComputeHistogram", string=True) + compute_profiles = ADCpt(SignalWithRBV, "ComputeProfiles", string=True) + compute_statistics = ADCpt(SignalWithRBV, "ComputeStatistics", string=True) + + cursor = DDC( + ad_group(SignalWithRBV, (("x", "CursorX"), ("y", "CursorY"))), + doc="The cursor XY", + default_read_attrs=("x", "y"), + ) + + hist_entropy = ADCpt(EpicsSignalRO, "HistEntropy_RBV") + hist_max = ADCpt(SignalWithRBV, "HistMax") + hist_min = ADCpt(SignalWithRBV, "HistMin") + hist_size = ADCpt(SignalWithRBV, "HistSize") + histogram = ADCpt(EpicsSignalRO, "Histogram_RBV") + + max_size = DDC( + ad_group(EpicsSignal, (("x", "MaxSizeX"), ("y", "MaxSizeY"))), + doc="The maximum size in XY", + default_read_attrs=("x", "y"), + ) + + max_value = ADCpt(EpicsSignalRO, "MaxValue_RBV") + max_xy = DDC( + ad_group(EpicsSignalRO, (("x", "MaxX_RBV"), ("y", "MaxY_RBV"))), + doc="Maximum in XY", + default_read_attrs=("x", "y"), + ) + + mean_value = ADCpt(EpicsSignalRO, "MeanValue_RBV") + min_value = ADCpt(EpicsSignalRO, "MinValue_RBV") + + min_xy = DDC( + ad_group(EpicsSignalRO, (("x", "MinX_RBV"), ("y", "MinY_RBV"))), + doc="Minimum in XY", + default_read_attrs=("x", "y"), + ) + + net = ADCpt(EpicsSignalRO, "Net_RBV") + profile_average = DDC( + ad_group( + EpicsSignalRO, (("x", "ProfileAverageX_RBV"), ("y", "ProfileAverageY_RBV")) + ), + doc="Profile average in XY", + default_read_attrs=("x", "y"), + ) + + profile_centroid = DDC( + ad_group( + EpicsSignalRO, + (("x", "ProfileCentroidX_RBV"), ("y", "ProfileCentroidY_RBV")), + ), + doc="Profile centroid in XY", + default_read_attrs=("x", "y"), + ) + + profile_cursor = DDC( + ad_group( + EpicsSignalRO, (("x", "ProfileCursorX_RBV"), ("y", "ProfileCursorY_RBV")) + ), + doc="Profile cursor in XY", + default_read_attrs=("x", "y"), + ) + + profile_size = DDC( + ad_group(EpicsSignalRO, (("x", "ProfileSizeX_RBV"), ("y", "ProfileSizeY_RBV"))), + doc="Profile size in XY", + default_read_attrs=("x", "y"), + ) + + profile_threshold = DDC( + ad_group( + EpicsSignalRO, + (("x", "ProfileThresholdX_RBV"), ("y", "ProfileThresholdY_RBV")), + ), + doc="Profile threshold in XY", + default_read_attrs=("x", "y"), + ) + + set_xhopr = ADCpt(EpicsSignal, "SetXHOPR") + set_yhopr = ADCpt(EpicsSignal, "SetYHOPR") + sigma_xy = ADCpt(EpicsSignalRO, "SigmaXY_RBV") + sigma_x = ADCpt(EpicsSignalRO, "SigmaX_RBV") + sigma_y = ADCpt(EpicsSignalRO, "SigmaY_RBV") + sigma = ADCpt(EpicsSignalRO, "Sigma_RBV") + ts_acquiring = ADCpt(EpicsSignal, "TS:TSAcquiring") + + ts_centroid = DDC( + ad_group(EpicsSignal, (("x", "TS:TSCentroidX"), ("y", "TS:TSCentroidY"))), + doc="Time series centroid in XY", + default_read_attrs=("x", "y"), + ) + + # ts_control = ADCpt(EpicsSignal, 'TS:TSControl', string=True) + ts_current_point = ADCpt(EpicsSignal, "TS:TSCurrentPoint") + ts_max_value = ADCpt(EpicsSignal, "TS:TSMaxValue") + + ts_max = DDC( + ad_group(EpicsSignal, (("x", "TS:TSMaxX"), ("y", "TS:TSMaxY"))), + doc="Time series maximum in XY", + default_read_attrs=("x", "y"), + ) + + ts_mean_value = ADCpt(EpicsSignal, "TS:TSMeanValue") + ts_min_value = ADCpt(EpicsSignal, "TS:TSMinValue") + + ts_min = DDC( + ad_group(EpicsSignal, (("x", "TS:TSMinX"), ("y", "TS:TSMinY"))), + doc="Time series minimum in XY", + default_read_attrs=("x", "y"), + ) + + ts_net = ADCpt(EpicsSignal, "TS:TSNet") + ts_num_points = ADCpt(EpicsSignal, "TS:TSNumPoints") + ts_read = ADCpt(EpicsSignal, "TS:TSRead") + ts_sigma = ADCpt(EpicsSignal, "TS:TSSigma") + ts_sigma_x = ADCpt(EpicsSignal, "TS:TSSigmaX") + ts_sigma_xy = ADCpt(EpicsSignal, "TS:TSSigmaXY") + ts_sigma_y = ADCpt(EpicsSignal, "TS:TSSigmaY") + ts_total = ADCpt(EpicsSignal, "TS:TSTotal") + total = ADCpt(EpicsSignalRO, "Total_RBV") + + +class QuadEMPort(ADBase): + port_name = Cpt(Signal, value="") + + def __init__(self, port_name, *args, **kwargs): + super().__init__(*args, **kwargs) + self.port_name.put(port_name) + + +class QuadEMV33(QuadEM): + conf = Cpt(QuadEMPort, port_name="EM180") + em_range = Cpt(SignalWithRBV, "Range", string=True) + + current1 = ADCpt(StatsPluginV33, "Current1:") + current2 = ADCpt(StatsPluginV33, "Current2:") + current3 = ADCpt(StatsPluginV33, "Current3:") + current4 = ADCpt(StatsPluginV33, "Current4:") + sum_all = ADCpt(StatsPluginV33, "SumAll:") diff --git a/nslsii/areadetector/xspress3.py b/src/nslsii/areadetector/xspress3.py similarity index 90% rename from nslsii/areadetector/xspress3.py rename to src/nslsii/areadetector/xspress3.py index e097ac02..d4c3490d 100644 --- a/nslsii/areadetector/xspress3.py +++ b/src/nslsii/areadetector/xspress3.py @@ -1,21 +1,19 @@ +from __future__ import annotations + import datetime import logging import re import time as ttime - from collections import deque from pathlib import Path from uuid import uuid4 from databroker.assets.handlers import Xspress3HDF5Handler - from event_model import compose_resource - -from ophyd import Component as Cpt, Device, Kind -from ophyd import EpicsSignal, EpicsSignalRO, Signal -from ophyd.areadetector import ADBase +from ophyd import Component as Cpt +from ophyd import Device, EpicsSignal, EpicsSignalRO, Kind, Signal +from ophyd.areadetector import ADBase, Xspress3Detector from ophyd.areadetector import EpicsSignalWithRBV as SignalWithRBV -from ophyd.areadetector import Xspress3Detector from ophyd.areadetector.filestore_mixins import FileStorePluginBase from ophyd.areadetector.plugins import HDF5Plugin_V34 as HDF5Plugin from ophyd.device import Staged @@ -23,7 +21,6 @@ from ..detectors.utils import makedirs - logger = logging.getLogger(__name__) @@ -53,7 +50,7 @@ def unstage(self): self._acquire_status = None return super_unstage_result - def _acquire_changed(self, value=None, old_value=None, **kwargs): + def _acquire_changed(self, value=None, old_value=None, **kwargs): # noqa : ARG002 """Respond to changes in the Xspress3Detector.cam.acquire PV. The important behavior of this method is to mark self._acquire_status @@ -102,9 +99,8 @@ def new_acquire_status(self): def trigger(self): logger.debug("trigger") if self._staged != Staged.yes: - raise RuntimeError( - "tried to trigger Xspress3 with prefix {self.prefix} but it is not staged" - ) + msg = f"tried to trigger Xspress3 with prefix {self.prefix} but it is not staged" + raise RuntimeError(msg) self._acquire_status = self.new_acquire_status() self.cam.acquire.put(1, wait=False) @@ -122,7 +118,7 @@ def trigger(self): class Xspress3ExternalFileReference(Signal): - """ A special Signal for datum document information. + """A special Signal for datum document information. Parameters ---------- @@ -136,7 +132,9 @@ class Xspress3ExternalFileReference(Signal): """ - def __init__(self, *args, dtype_str="uint32", bin_count=4096, dim_name="bin_count", **kwargs): + def __init__( + self, *args, dtype_str="uint32", bin_count=4096, dim_name="bin_count", **kwargs + ): super().__init__(*args, **kwargs) self.dtype_str = dtype_str self.shape = (bin_count,) @@ -145,13 +143,13 @@ def __init__(self, *args, dtype_str="uint32", bin_count=4096, dim_name="bin_coun def describe(self): res = super().describe() res[self.name].update( - dict( - external="FILESTORE:", - dtype="array", - dtype_str=self.dtype_str, - shape=self.shape, - dims=self.dims, - ) + { + "external": "FILESTORE:", + "dtype": "array", + "dtype_str": self.dtype_str, + "shape": self.shape, + "dims": self.dims, + } ) return res @@ -267,7 +265,7 @@ def stage(self): the_full_data_dir_path = self._build_data_dir_path( the_datetime=datetime.datetime.now(), root_path=self.root_path.get(), - path_template=self.path_template.get() + path_template=self.path_template.get(), ) self.file_path.set(the_full_data_dir_path).wait() # 3. set file_name to a uuid @@ -329,20 +327,21 @@ def stage(self): return staged_devices def unstage(self): - self.capture.set(0).wait() return super().unstage() - def generate_datum(self, key, timestamp, datum_kwargs): + def generate_datum(self, key, timestamp, datum_kwargs): # noqa : ARG002 if key is not None: - raise ValueError(f"'key' must be None but key='{key}'") + msg = f"'key' must be None but key='{key}'" + raise ValueError(msg) # generate datum document for "bulk" image data (the whole array) - if self.parent.get_external_file_ref() and self.parent.get_external_file_ref().kind & Kind.normal: - bulk_data_datum = self._bulk_data_datum_factory( - datum_kwargs={} - ) + if ( + self.parent.get_external_file_ref() + and self.parent.get_external_file_ref().kind & Kind.normal + ): + bulk_data_datum = self._bulk_data_datum_factory(datum_kwargs={}) self._asset_docs_cache.append(("datum", bulk_data_datum)) self.parent.get_external_file_ref().put(bulk_data_datum["datum_id"]) @@ -361,7 +360,7 @@ def generate_datum(self, key, timestamp, datum_kwargs): def collect_asset_docs(self): items = list(self._asset_docs_cache) self._asset_docs_cache.clear() - for item in items: + for item in items: # noqa : UP028 yield item @@ -402,9 +401,8 @@ def __init__( super().__init__(basename, parent=parent, **kwargs) if not isinstance(parent, Xspress3Detector): - raise TypeError( - "parent must be an instance of ophyd.areadetector.Xspress3Detector" - ) + msg = "parent must be an instance of ophyd.areadetector.Xspress3Detector" + raise TypeError(msg) # establish PV values to be set when this detector is staged # the original values will be replaced when it is unstaged @@ -450,7 +448,8 @@ def stage(self): total_points_reading = self.parent.total_points.get() if total_points_reading < 1: - raise RuntimeError(f"total_points '{self.parent.total_points}' must be set") + msg = f"total_points '{self.parent.total_points}' must be set" + raise RuntimeError(msg) spectra_per_point_reading = self.parent.spectra_per_point.get() total_capture = total_points_reading * spectra_per_point_reading @@ -512,7 +511,8 @@ def stage(self): ) if not self.file_path_exists.get(): - raise IOError(f"path '{self.file_path.get()}' does not exist on the IOC") + msg = f"path '{self.file_path.get()}' does not exist on the IOC" + raise OSError(msg) logger.debug("inserting the filestore resource: '%s'", self._fn) # JL: calling generate_resource() in stage is usual @@ -564,8 +564,8 @@ def unstage(self): logger.warning("Still capturing data .... giving up.") logger.warning( "Check that the xspress3 is configured to take the right " - "number of frames " - f"(it is trying to take {self.parent.cam.num_images.get()})" + "number of frames (it is trying to take %s)", + self.parent.cam.num_images.get(), ) self.capture.put(0) break @@ -609,15 +609,14 @@ def generate_datum(self, key, timestamp, datum_kwargs): ) # we are done return - else: - pass # we have a problem # the `key` parameter did not match any of our channels - raise ValueError( + msg = ( f"failed to find channel with name '{key}' " f"on Xspress3 detector with PV prefix '{self.parent.prefix}'" ) + raise ValueError(msg) # JL: is there any reason to keep this? def configure(self, total_points=0, master=None, external_trig=False, **kwargs): @@ -696,9 +695,8 @@ def __init__(self, prefix, *args, **kwargs): # and we want the 1 at the end mcaroi_prefix_match = self.mcaroi_prefix_re.search(prefix) if mcaroi_prefix_match is None: - raise ValueError( - f"mcaroi prefix '{prefix}' does not match the expected pattern `{self.mcaroi_prefix_re.pattern}`" - ) + msg = f"mcaroi prefix '{prefix}' does not match the expected pattern `{self.mcaroi_prefix_re.pattern}`" + raise ValueError(msg) self.mcaroi_number = int(mcaroi_prefix_match.group("mcaroi_number")) def configure_mcaroi(self, *, min_x, size_x, roi_name=None, use=True): @@ -814,14 +812,12 @@ def _validate_mcaroi_number(mcaroi_number): """ if not isinstance(mcaroi_number, int): - raise ValueError(f"MCAROI number '{mcaroi_number}' is not an integer") - elif not 1 <= mcaroi_number <= 48: - raise ValueError( - f"MCAROI number '{mcaroi_number}' is outside the allowed interval [1,48]" - ) - else: - # everything is awesome - pass + msg = f"MCAROI number '{mcaroi_number}' is not an integer" + raise ValueError(msg) + if not 1 <= mcaroi_number <= 48: + msg = f"MCAROI number '{mcaroi_number}' is outside the allowed interval [1,48]" + raise ValueError(msg) + # everything is awesome def build_channel_class( @@ -868,12 +864,12 @@ def clear_all_rois(self): """ if channel_parent_classes is None: - channel_parent_classes = tuple([ADBase]) + channel_parent_classes = (ADBase,) _validate_channel_number(channel_number=channel_number) # create a tuple in case the mcaroi_numbers parameter can be iterated only once - mcaroi_numbers = tuple([mcaroi_number for mcaroi_number in mcaroi_numbers]) + mcaroi_numbers = tuple(mcaroi_numbers) for mcaroi_number in mcaroi_numbers: _validate_mcaroi_number(mcaroi_number=mcaroi_number) @@ -886,7 +882,7 @@ def __init__(self, *args, **kwargs): def __repr__(self): return f"{self.__class__.__name__}(channel_number={self.channel_number}, mcaroi_numbers={self.mcaroi_numbers})" - def get_mcaroi_count(self): + def get_mcaroi_count(self): # noqa : ARG001 return len(mcaroi_numbers) def get_mcaroi(self, *, mcaroi_number): @@ -894,10 +890,11 @@ def get_mcaroi(self, *, mcaroi_number): try: return getattr(self, f"mcaroi{mcaroi_number:02d}") except AttributeError as ae: - raise ValueError( + msg = ( f"no MCAROI on channel {self.channel_number} " f"with prefix '{self.prefix}' has number {mcaroi_number}" - ) from ae + ) + raise ValueError(msg) from ae def iterate_mcaroi_attr_names(self): for attr_name in self.__dir__(): @@ -923,14 +920,13 @@ def clear_all_rois(self): def get_external_file_ref(self): """Return the Xspress3ExternalFileReference. - - image_data_key is an optional attribute - if it is not present return None + + image_data_key is an optional attribute + if it is not present return None """ if image_data_key: return getattr(self, image_data_key) - else: - return None + return None channel_fields_and_methods = { "__init__": __init__, @@ -988,14 +984,14 @@ def _validate_channel_number(channel_number): """ if not isinstance(channel_number, int): - raise ValueError(f"channel number '{channel_number}' is not an integer") - elif not 1 <= channel_number <= 16: - raise ValueError( + msg = f"channel number '{channel_number}' is not an integer" + raise ValueError(msg) + if not 1 <= channel_number <= 16: + msg = ( f"channel number '{channel_number}' is outside the allowed interval [1,16]" ) - else: - # everything is great - pass + raise ValueError(msg) + # everything is great def build_detector_class( @@ -1004,9 +1000,8 @@ def build_detector_class( detector_parent_classes=None, extra_class_members=None, ): - raise NotImplementedError( - "build_detector_class() has been removed, use build_xspress3_class()" - ) + msg = "build_detector_class() has been removed, use build_xspress3_class()" + raise NotImplementedError(msg) def build_xspress3_class( @@ -1070,16 +1065,16 @@ def iterate_channels(self): ... """ if xspress3_parent_classes is None: - xspress3_parent_classes = tuple([Xspress3Detector]) + xspress3_parent_classes = (Xspress3Detector,) if extra_class_members is None: - extra_class_members = dict() + extra_class_members = {} # in case channel_numbers can be iterated only once, create a tuple - channel_numbers = tuple([channel_number for channel_number in channel_numbers]) + channel_numbers = tuple([channel_number for channel_number in channel_numbers]) # noqa : C416 # in case mcaroi_numbers can be iterated only once, create a tuple - mcaroi_numbers = tuple([mcaroi_number for mcaroi_number in mcaroi_numbers]) + mcaroi_numbers = tuple([mcaroi_number for mcaroi_number in mcaroi_numbers]) # noqa : C416 channel_attr_name_re = re.compile(r"channel\d{2}") @@ -1093,7 +1088,7 @@ def __repr__(self): """ return f"{self.__class__.__name__}(channels=({','.join([str(channel) for channel in self.iterate_channels()])}))" - def get_channel_count(self): + def get_channel_count(self): # noqa : ARG001 """Return the number of channels on this xspress3 class. Returns @@ -1123,10 +1118,11 @@ def get_channel(self, *, channel_number): try: return getattr(self, f"channel{channel_number:02d}") except AttributeError as ae: - raise ValueError( + msg = ( f"no channel on detector with prefix '{self.prefix}' " f"has number {channel_number}" - ) from ae + ) + raise ValueError(msg) from ae def iterate_channels(self): """Yield the channel objects of this xspress3 class in the order they were specified. @@ -1142,41 +1138,36 @@ def iterate_channels(self): def get_external_file_ref(self): """Return the Xspress3ExternalFileReference. - - image_data_key is an optional attribute - if it is not present return None + + image_data_key is an optional attribute + if it is not present return None """ if image_data_key: return getattr(self, image_data_key) - else: - return None + return None xspress3_fields_and_methods = dict( - **{ - "channel_numbers": tuple(sorted(channel_numbers)), - "external_trig": Cpt(Signal, value=False, doc="Use external triggering"), - "total_points": Cpt( - Signal, - value=-1, - doc="The total number of points to acquire overall", - ), - "spectra_per_point": Cpt( - Signal, value=1, doc="Number of spectra per point" - ), - "make_directories": Cpt( - Signal, value=False, doc="Make directories on the Xspress3 side" - ), - "rewindable": Cpt( - Signal, - value=False, - doc="Xspress3 cannot safely be rewound in bluesky", - ), - "__repr__": __repr__, - "get_channel_count": get_channel_count, - "get_channel": get_channel, - "iterate_channels": iterate_channels, - "get_external_file_ref": get_external_file_ref, - }, + channel_numbers=tuple(sorted(channel_numbers)), + external_trig=Cpt(Signal, value=False, doc="Use external triggering"), + total_points=Cpt( + Signal, + value=-1, + doc="The total number of points to acquire overall", + ), + spectra_per_point=Cpt(Signal, value=1, doc="Number of spectra per point"), + make_directories=Cpt( + Signal, value=False, doc="Make directories on the Xspress3 side" + ), + rewindable=Cpt( + Signal, + value=False, + doc="Xspress3 cannot safely be rewound in bluesky", + ), + __repr__=__repr__, + get_channel_count=get_channel_count, + get_channel=get_channel, + iterate_channels=iterate_channels, + get_external_file_ref=get_external_file_ref, **extra_class_members, ) diff --git a/src/nslsii/common/__init__.py b/src/nslsii/common/__init__.py new file mode 100644 index 00000000..cd7c525c --- /dev/null +++ b/src/nslsii/common/__init__.py @@ -0,0 +1,5 @@ +from __future__ import annotations + +from .touchbl import if_touch_beamline + +__all__ = ["if_touch_beamline"] diff --git a/src/nslsii/common/ipynb/__init__.py b/src/nslsii/common/ipynb/__init__.py new file mode 100644 index 00000000..107269ed --- /dev/null +++ b/src/nslsii/common/ipynb/__init__.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +__all__ = [ + "get_sys_info", + "image_stack_to_movie", + "notebook_to_nbviewer", + "show_image_stack", + "show_kernels", +] + +from .animation import image_stack_to_movie, show_image_stack +from .info import get_sys_info, show_kernels +from .nbviewer import notebook_to_nbviewer diff --git a/nslsii/common/ipynb/animation.py b/src/nslsii/common/ipynb/animation.py similarity index 58% rename from nslsii/common/ipynb/animation.py rename to src/nslsii/common/ipynb/animation.py index fc34ceb6..ccc45393 100644 --- a/nslsii/common/ipynb/animation.py +++ b/src/nslsii/common/ipynb/animation.py @@ -1,13 +1,23 @@ -from matplotlib import animation -from matplotlib import pyplot as plt +from __future__ import annotations + +import base64 +from pathlib import Path +from tempfile import NamedTemporaryFile + from IPython.display import HTML from ipywidgets import interact -from tempfile import NamedTemporaryFile -import base64 +from matplotlib import animation +from matplotlib import pyplot as plt -def show_image_stack(images, minmax, fontsize=18, cmap='CMRmap', - zlabel=r'Intensty [ADU]', figsize=(12, 10)): +def show_image_stack( + images, + minmax, + fontsize=18, + cmap="CMRmap", + zlabel=r"Intensty [ADU]", + figsize=(12, 10), +): """Show an Interactive Image Stack in an IPython Notebook Parameters @@ -35,28 +45,33 @@ def view_frame(i, vmin, vmax): fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111) - im = ax.imshow(images[i], cmap=cmap, interpolation='none', - vmin=vmin, vmax=vmax) + im = ax.imshow(images[i], cmap=cmap, interpolation="none", vmin=vmin, vmax=vmax) cbar = fig.colorbar(im) cbar.ax.tick_params(labelsize=fontsize) - cbar.set_label(zlabel, size=fontsize, weight='bold') - - ax.set_title('Frame {} Min = {} Max = {}'.format(i, vmin, vmax), - fontsize=fontsize, fontweight='bold') - - for item in ([ax.xaxis.label, ax.yaxis.label] + - ax.get_xticklabels() + ax.get_yticklabels()): + cbar.set_label(zlabel, size=fontsize, weight="bold") + + ax.set_title( + f"Frame {i} Min = {vmin} Max = {vmax}", fontsize=fontsize, fontweight="bold" + ) + + for item in [ + ax.xaxis.label, + ax.yaxis.label, + *ax.get_xticklabels(), + *ax.get_yticklabels(), + ]: item.set_fontsize(fontsize) - item.set_fontweight('bold') + item.set_fontweight("bold") plt.show() - interact(view_frame, i=(0, n-1), vmin=minmax, vmax=minmax) + interact(view_frame, i=(0, n - 1), vmin=minmax, vmax=minmax) -def image_stack_to_movie(images, frames=None, vmin=None, vmax=None, - figsize=(6, 5), cmap='CMRmap', fps=10): +def image_stack_to_movie( + images, frames=None, vmin=None, vmax=None, figsize=(6, 5), cmap="CMRmap", fps=10 +): """Convert image stack to movie and show in notebook. Parameters @@ -82,23 +97,28 @@ def image_stack_to_movie(images, frames=None, vmin=None, vmax=None, fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111) - im = plt.imshow(images[1], vmin=vmin, vmax=vmax, cmap=cmap, - interpolation='none') + im = plt.imshow(images[1], vmin=vmin, vmax=vmax, cmap=cmap, interpolation="none") cbar = fig.colorbar(im) cbar.ax.tick_params(labelsize=14) - cbar.set_label(r"Intensity [ADU]", size=14,) - for item in ([ax.xaxis.label, ax.yaxis.label] + - ax.get_xticklabels() + ax.get_yticklabels()): + cbar.set_label( + r"Intensity [ADU]", + size=14, + ) + for item in [ + ax.xaxis.label, + ax.yaxis.label, + *ax.get_xticklabels(), + *ax.get_yticklabels(), + ]: item.set_fontsize(14) - item.set_fontweight('bold') + item.set_fontweight("bold") def animate(i): im.set_array(images[i]) - ax.set_title('Frame {}'.format(i), fontsize=16, fontweight='bold') - return im, + ax.set_title(f"Frame {i}", fontsize=16, fontweight="bold") + return (im,) - anim = animation.FuncAnimation(fig, animate, frames=frames, - interval=1, blit=True) + anim = animation.FuncAnimation(fig, animate, frames=frames, interval=1, blit=True) plt.close(anim._fig) # return anim.to_html5_video() return HTML(_anim_to_html(anim, fps)) @@ -110,11 +130,13 @@ def _anim_to_html(anim, fps): Your browser does not support the video tag. """ - if not hasattr(anim, '_encoded_video'): - with NamedTemporaryFile(suffix='.mp4') as f: - anim.save(f.name, fps=fps, - extra_args=['-vcodec', 'libx264', - '-pix_fmt', 'yuv420p']) - video = open(f.name, "rb").read() + if not hasattr(anim, "_encoded_video"): + with NamedTemporaryFile(suffix=".mp4") as f: + anim.save( + f.name, + fps=fps, + extra_args=["-vcodec", "libx264", "-pix_fmt", "yuv420p"], + ) + video = Path.open(f.name, "rb").read() anim._encoded_video = base64.b64encode(video) return VIDEO_TAG.format(anim._encoded_video.decode("utf-8")) diff --git a/src/nslsii/common/ipynb/info.py b/src/nslsii/common/ipynb/info.py new file mode 100644 index 00000000..4047faff --- /dev/null +++ b/src/nslsii/common/ipynb/info.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +import platform +import sys + +import psutil +from IPython.display import HTML + + +def get_sys_info(): + """Display info on system and output as nice HTML""" + html = f"

System Information for {platform.node()}

" + html += "" + + html += '' + html += f"" + html += f"" + + mem = psutil.virtual_memory() + html += "" + html += f"" + html += "" + html += f"" + html += "" + html += f"" + + html += f"" + html += ( + f"" + ) + + html += "
Python Executable{sys.executable}
Kernel PID{psutil.Process().pid}
Total System Memory{mem.total / 1024**3:.4} Mb
Total Memory Used{mem.used / 1024**3:.4} Mb
Total Memory Free{mem.free / 1024**3:.4} Mb
Number of CPU Cores{psutil.cpu_count()}
Current CPU Load{psutil.cpu_percent(1, False)} %
" + return HTML(html) + + +def show_kernels(): + """Show all IPython Kernels on System""" + + total_mem = psutil.virtual_memory().total + + html = ( + f"

IPython Notebook Processes on {platform.node()}

" + "" + "" + "" + "" + ) + + for proc in psutil.process_iter(): + try: + pinfo = proc.as_dict( + attrs=["pid", "username", "cmdline", "memory_info", "status"] + ) + except psutil.NoSuchProcess: + pass + else: + if any( + x in pinfo["cmdline"] for x in ["IPython.kernel", "ipykernel_launcher"] + ): + html += "" + html += "".format(**pinfo) + p = psutil.Process(pinfo["pid"]).cpu_percent(0.1) + html += f"" + html += "".format(pinfo["memory_info"].vms / 1024**3) + html += "".format( + 100 * pinfo["memory_info"].vms / total_mem + ) + html += "".format(pinfo["status"]) + html += "" + + html += "
UsernamePIDCPU UsageProcess MemorySystem Memory UsedStatus
{username}{pid}{p}%{:.4} Mb{:.3}%{}
" + return HTML(html) diff --git a/nslsii/common/ipynb/logutils.py b/src/nslsii/common/ipynb/logutils.py similarity index 85% rename from nslsii/common/ipynb/logutils.py rename to src/nslsii/common/ipynb/logutils.py index cf15facd..1c438eea 100644 --- a/nslsii/common/ipynb/logutils.py +++ b/src/nslsii/common/ipynb/logutils.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import logging import sys import traceback @@ -45,18 +47,14 @@ def log_exception(ipyshell, etype, evalue, tb, tb_offset=None): # display the exception in the console if ipyshell.InteractiveTB.mode == "Minimal": - print( - "An exception has occurred, use '%tb verbose'" - " to see the full traceback.", + print( # noqa : T201 + "An exception has occurred, use '%tb verbose' to see the full traceback.", file=sys.stderr, ) ipyshell.showtraceback((etype, evalue, tb), tb_offset=tb_offset) # send the traceback to the nslsii.ipython logger logging.getLogger("nslsii.ipython").exception(evalue) - print( - f"See {bluesky_log_file_path} for the full traceback.", - file=sys.stderr - ) + print(f"See {bluesky_log_file_path} for the full traceback.", file=sys.stderr) # noqa : T201 return tb_lines diff --git a/nslsii/common/ipynb/nbviewer.py b/src/nslsii/common/ipynb/nbviewer.py similarity index 83% rename from nslsii/common/ipynb/nbviewer.py rename to src/nslsii/common/ipynb/nbviewer.py index 0bfc33dd..6a9633f6 100644 --- a/nslsii/common/ipynb/nbviewer.py +++ b/src/nslsii/common/ipynb/nbviewer.py @@ -1,4 +1,6 @@ -from IPython.display import display, HTML +from __future__ import annotations + +from IPython.display import HTML, display _js_callback_open = """ function callback(out){ @@ -32,6 +34,6 @@ def notebook_to_nbviewer(): js = _js_callback_open + _js html = '' - html += 'nbviewer will open in a new tab in 20 seconds .....' + html += "" + html += "nbviewer will open in a new tab in 20 seconds ....." return display(HTML(html)) diff --git a/nslsii/common/touchbl.py b/src/nslsii/common/touchbl.py similarity index 50% rename from nslsii/common/touchbl.py rename to src/nslsii/common/touchbl.py index eccf6472..e79f233d 100644 --- a/nslsii/common/touchbl.py +++ b/src/nslsii/common/touchbl.py @@ -1,12 +1,14 @@ +from __future__ import annotations + import os -# you can make it a unique envvar or just a test thing + +# you can make it a unique envvar or just a test thing def if_touch_beamline(envvar="TOUCHBEAMLINE"): value = os.environ.get(envvar, "false").lower() if value in ("", "n", "no", "f", "false", "off", "0"): return False - elif value in ("y", "yes", "t", "true", "on", "1"): + if value in ("y", "yes", "t", "true", "on", "1"): return True - else: - raise ValueError(f"Unknown value: {value}") - \ No newline at end of file + msg = f"Unknown value: {value}" + raise ValueError(msg) diff --git a/src/nslsii/detectors/QEPro.py b/src/nslsii/detectors/QEPro.py new file mode 100644 index 00000000..0cf22ef6 --- /dev/null +++ b/src/nslsii/detectors/QEPro.py @@ -0,0 +1,157 @@ +from __future__ import annotations + +from ophyd import Component as Cpt +from ophyd import Device, EpicsSignal, EpicsSignalRO +from ophyd.areadetector import EpicsSignalWithRBV as SignalWithRBV +from ophyd.status import SubscriptionStatus + + +class QEProTEC(Device): + # Thermal electric cooler settings + tec = Cpt(SignalWithRBV, "TEC") + tec_temp = Cpt(SignalWithRBV, "TEC_TEMP") + curr_tec_temp = Cpt(EpicsSignalRO, "CURR_TEC_TEMP_RBV") + + def __init__(self, *args, tolerance=1, **kwargs): + self.tolerance = tolerance + super().__init__(*args, **kwargs) + + def set(self, value): + def check_setpoint(value, old_value, **kwargs): # noqa : ARG001 + if abs(value - self.tec_temp.get()) < self.tolerance: + print(f"Reached setpoint {self.tec_temp.get()}.") # noqa : T201 + return True + return False + + status = SubscriptionStatus( + self.curr_tec_temp, run=False, callback=check_setpoint + ) + self.tec_temp.put(value) + self.tec.put(1) + + return status + + +class QEPro(Device): + # Device information + serial = Cpt(EpicsSignal, "SERIAL") + model = Cpt(EpicsSignal, "MODEL") + + # Device Status + status = Cpt(EpicsSignal, "STATUS") + status_msg = Cpt(EpicsSignal, "STATUS_MSG") + device_connected = Cpt(EpicsSignalRO, "CONNECTED_RBV") + + # Utility signal that periodically checks device temps. + __check_status = Cpt(EpicsSignal, "CHECK_STATUS") + + # Bit array outlining which features are supported by the device + features = Cpt(EpicsSignalRO, "FEATURES_RBV") + + # Togglable features (if supported) + strobe = Cpt(SignalWithRBV, "STROBE") + electric_dark_correction = Cpt(SignalWithRBV, "EDC") + non_linearity_correction = Cpt(SignalWithRBV, "NLC") + shutter = Cpt(SignalWithRBV, "SHUTTER") + + # Thermal electric cooler + tec_device = Cpt(QEProTEC, "") + + # Light source feature signals + light_source = Cpt(SignalWithRBV, "LIGHT_SOURCE") + light_source_intensity = Cpt(SignalWithRBV, "LIGHT_SOURCE_INTENSITY") + light_source_count = Cpt(EpicsSignalRO, "LIGHT_SOURCE_COUNT_RBV") + + # Signals for specifying the number of spectra to average and counter for spectra + # collected in current scan + num_spectra = Cpt(SignalWithRBV, "NUM_SPECTRA") + spectra_collected = Cpt(EpicsSignalRO, "SPECTRA_COLLECTED_RBV") + + # Integration time settings (in ms) + int_min_time = Cpt(EpicsSignalRO, "INT_MIN_TIME_RBV") + int_max_time = Cpt(EpicsSignalRO, "INT_MAX_TIME_RBV") + integration_time = Cpt(SignalWithRBV, "INTEGRATION_TIME", kind="normal") + + # Internal buffer feature settings + buff_min_capacity = Cpt(EpicsSignalRO, "BUFF_MIN_CAPACITY_RBV") + buff_max_capacity = Cpt(EpicsSignalRO, "BUFF_MAX_CAPACITY_RBV") + buff_capacity = Cpt(SignalWithRBV, "BUFF_CAPACITY") + buff_element_count = Cpt(EpicsSignalRO, "BUFF_ELEMENT_COUNT_RBV") + + # Formatted Spectra + spectrum = Cpt(EpicsSignal, "SPECTRUM", kind="normal") + dark = Cpt(EpicsSignal, "DARK", kind="normal") + reference = Cpt(EpicsSignal, "REFERENCE", kind="normal") + + # Length of spectrum (in pixels) + formatted_spectrum_len = Cpt(EpicsSignalRO, "FORMATTED_SPECTRUM_LEN_RBV") + + # X-axis format and array + x_axis = Cpt(EpicsSignal, "X_AXIS") + x_axis_format = Cpt(SignalWithRBV, "X_AXIS_FORMAT") + + # Dark/Ref available signals + dark_available = Cpt(EpicsSignalRO, "DARK_AVAILABLE_RBV") + ref_available = Cpt(EpicsSignalRO, "REF_AVAILABLE_RBV") + + # Collection settings and start signals. + acquire = Cpt(SignalWithRBV, "COLLECT", put_complete=True) + collect_mode = Cpt(SignalWithRBV, "COLLECT_MODE") + spectrum_type = Cpt(SignalWithRBV, "SPECTRUM_TYPE") + correction = Cpt(SignalWithRBV, "CORRECTION") + trigger_mode = Cpt(SignalWithRBV, "TRIGGER_MODE") + + @property + def has_nlc_feature(self): + return self.features.get() & 32 + + @property + def has_lightsource_feature(self): + return self.features.get() & 16 + + @property + def has_edc_feature(self): + return self.features.get() & 8 + + @property + def has_buffer_feature(self): + return self.features.get() & 4 + + @property + def has_tec_feature(self): + return self.features.get() & 2 + + @property + def has_irrad_feature(self): + return self.features.get() & 1 + + def set_temp(self, temperature): + self.tec_device.set(temperature).wait() + + def get_dark_frame(self): + self.spectrum_type.put(1) + self.acquire.put(1, wait=True) + + def get_reference_frame(self): + if self.dark_available.get() == 0: + return + self.spectrum_type.put(2) + self.acquire.put(1, wait=True) + + def setup_collection( + self, + integration_time, + num_spectra_to_average, + correction_type="reference", # noqa : ARG002 + electric_dark_correction=True, + ): + self.integration_time.put(integration_time) + self.num_spectra = num_spectra_to_average + if electric_dark_correction: + self.electric_dark_correction = True + + self.get_dark_frame() + self.get_reference_frame() + + def trigger(self): + self.acquire.put(1, wait=True) diff --git a/nslsii/areadetector/__init__.py b/src/nslsii/detectors/__init__.py similarity index 100% rename from nslsii/areadetector/__init__.py rename to src/nslsii/detectors/__init__.py diff --git a/nslsii/detectors/maia.py b/src/nslsii/detectors/maia.py similarity index 98% rename from nslsii/detectors/maia.py rename to src/nslsii/detectors/maia.py index 3467fc20..c2b2fa4e 100644 --- a/nslsii/detectors/maia.py +++ b/src/nslsii/detectors/maia.py @@ -1,14 +1,15 @@ -from collections import OrderedDict -import time as ttime +from __future__ import annotations -import numpy as np +import time as ttime +from collections import OrderedDict +from typing import ClassVar -from ophyd import Device, Component as Cpt, EpicsSignal, EpicsSignalRO -from ophyd.status import DeviceStatus +from ophyd import Component as Cpt +from ophyd import Device, EpicsSignal, EpicsSignalRO from ophyd.signal import Signal - - -from recordwhat import RecordBase, _register_record_type, FieldComponent as FldCpt +from ophyd.status import DeviceStatus +from recordwhat import FieldComponent as FldCpt +from recordwhat import RecordBase, _register_record_type from recordwhat.records import ( AiRecord, AoRecord, @@ -27,6 +28,7 @@ @_register_record_type("vsin") class VsinRecord(RecordBase): "Autogenerated class" + previous_value = FldCpt(EpicsSignalRO, ".OVAL$", string=True) quoted_value = FldCpt(EpicsSignalRO, ".QVAL$", string=True) simulation_mode = FldCpt(EpicsSignal, ".SIMM") @@ -47,6 +49,7 @@ class VsinRecord(RecordBase): @_register_record_type("vsout") class VsoutRecord(RecordBase): "Autogenerated class" + previous_value = FldCpt(EpicsSignalRO, ".OVAL$", string=True) quoted_value = FldCpt(EpicsSignalRO, ".QVAL$", string=True) simulation_mode = FldCpt(EpicsSignal, ".SIMM") @@ -72,6 +75,7 @@ class VsoutRecord(RecordBase): @_register_record_type("blog") class BlogRecord(RecordBase): "Autogenerated class" + blog_record_length = FldCpt(EpicsSignal, ".RECLEN") blogd_data_path = FldCpt(EpicsSignal, ".DTPATH$", string=True) blogd_subversion_revision = FldCpt(EpicsSignal, ".SVNREV$", string=True) @@ -137,6 +141,7 @@ class BlogRecord(RecordBase): @_register_record_type("strnout") class StrnoutRecord(RecordBase): "Autogenerated class" + num_bytes_in_val_incl_null = FldCpt(EpicsSignal, ".NBYTES") previous_value = FldCpt(EpicsSignalRO, ".OVAL$", string=True) simulation_mode = FldCpt(EpicsSignal, ".SIMM") @@ -162,6 +167,7 @@ class StrnoutRecord(RecordBase): @_register_record_type("genSub") class GensubRecord(RecordBase): "Autogenerated class" + old_subr_address = FldCpt(EpicsSignalRO, ".OSAD") old_return_value = FldCpt(EpicsSignalRO, ".OVAL") subr_return_value = FldCpt(EpicsSignal, ".VAL") @@ -192,7 +198,7 @@ class GensubRecord(RecordBase): input_link_r = FldCpt(EpicsSignalRO, ".INPR$", string=True) input_link_s = FldCpt(EpicsSignalRO, ".INPS$", string=True) input_link_t = FldCpt(EpicsSignalRO, ".INPT$", string=True) - input_link_u = FldCpt(EpicsSignalRO, ".INPU$", string=True) + input_link_u = FldCpt(EpicsSignalRO, ".INPU$", string=True) # codespell:ignore subroutine_input_link = FldCpt(EpicsSignalRO, ".SUBL$", string=True) # - output @@ -273,7 +279,7 @@ class GensubRecord(RecordBase): no_in_b = FldCpt(EpicsSignalRO, ".NOB") no_in_c = FldCpt(EpicsSignalRO, ".NOC") no_in_d = FldCpt(EpicsSignalRO, ".NOD") - no_in_e = FldCpt(EpicsSignalRO, ".NOE") + no_in_e = FldCpt(EpicsSignalRO, ".NOE") # codespell:ignore no_in_f = FldCpt(EpicsSignalRO, ".NOF") no_in_g = FldCpt(EpicsSignalRO, ".NOG") no_in_h = FldCpt(EpicsSignalRO, ".NOH") @@ -283,7 +289,7 @@ class GensubRecord(RecordBase): no_in_l = FldCpt(EpicsSignalRO, ".NOL") no_in_m = FldCpt(EpicsSignalRO, ".NOM") no_in_n = FldCpt(EpicsSignalRO, ".NON") - no_in_o = FldCpt(EpicsSignalRO, ".NOO") + no_in_o = FldCpt(EpicsSignalRO, ".NOO") # codespell:ignore no_in_p = FldCpt(EpicsSignalRO, ".NOP") no_in_q = FldCpt(EpicsSignalRO, ".NOQ") no_in_r = FldCpt(EpicsSignalRO, ".NOR") @@ -377,17 +383,14 @@ class GensubRecord(RecordBase): class Usercalcn_nodisable(Device): - ... usercalc = Cpt(SwaitRecord, "userCalc") class Scalcout(Device): - ... scalcout = Cpt(ScalcoutRecord, ":scalcout") class Blogioc(Device): - ... info = Cpt(BlogRecord, ":info") id_2 = Cpt(BiRecord, ":id_2") newrun = Cpt(StrnoutRecord, ":newrun") @@ -529,8 +532,6 @@ class KandMeta(Device): class Kandinskivars(Device): - ... - bias_volt_max = Cpt(AiRecord, ":BIAS_VOLT_MAX") blog = Cpt(Blogioc, "") @@ -802,7 +803,6 @@ class Kandinskivars(Device): class Scanparms2pos(Device): - ... scanparms = Cpt(ScanparmRecord, ":scanParms") scanparms_p2 = Cpt(ScanparmRecord, ":scanParms_p2") @@ -817,7 +817,7 @@ class Encoder(Device): class MAIA(Kandinskivars): - fly_keys = [ + fly_keys: ClassVar[list[str]] = [ "blog.info.blogd_data_path", "blog.info.blogd_working_directory", "blog.info.run_number", @@ -827,14 +827,14 @@ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def kickoff(self): - # paranoia enableing + # paranoia enabling self.pixel_enable_cmd.value.put(1) self.pixel_event_enable_cmd.value.put(1) self.photon_enable_sp.value.put(1) st = DeviceStatus(self) - def _cb_discard(value, **kwargs): + def _cb_discard(value, **kwargs): # noqa : ARG001 if value == 0: st._finished() self.blog_discard_mon.value.clear_sub(_cb_discard) @@ -846,7 +846,7 @@ def _cb_discard(value, **kwargs): def complete(self): st = DeviceStatus(self) - def _cb_discard(value, **kwargs): + def _cb_discard(value, **kwargs): # noqa : ARG001 if value == 1: st._finished() self.blog_discard_mon.value.clear_sub(_cb_discard) diff --git a/nslsii/detectors/trigger_mixins.py b/src/nslsii/detectors/trigger_mixins.py similarity index 63% rename from nslsii/detectors/trigger_mixins.py rename to src/nslsii/detectors/trigger_mixins.py index f84bee8b..661ba238 100644 --- a/nslsii/detectors/trigger_mixins.py +++ b/src/nslsii/detectors/trigger_mixins.py @@ -1,12 +1,15 @@ -import time as ttime +from __future__ import annotations + import itertools import logging +import time as ttime -from ophyd.device import (DeviceStatus, BlueskyInterface, Staged, - Component as Cpt, Device) -from ophyd import (Signal, ) +from ophyd import ( + Signal, +) from ophyd.areadetector.filestore_mixins import FileStoreIterativeWrite - +from ophyd.device import BlueskyInterface, Device, DeviceStatus, Staged +from ophyd.device import Component as Cpt from .utils import ordered_dict_move_to_beginning @@ -19,49 +22,45 @@ def __init__(self, *args, **kwargs): # If acquiring, stop. self.stage_sigs[self.cam.acquire] = 0 - self.stage_sigs[self.cam.image_mode] = 'Multiple' + self.stage_sigs[self.cam.image_mode] = "Multiple" self._acquisition_signal = self.cam.acquire self._status = None class ModalSettings(Device): - mode = Cpt(Signal, value='internal', - doc='Triggering mode (internal/external)') - scan_type = Cpt(Signal, value='step', - doc='Scan type (step/fly)') - make_directories = Cpt(Signal, value=True, - doc='Make directories on the DAQ side') - total_points = Cpt(Signal, value=2, - doc='The total number of points to acquire overall') - triggers = Cpt(Signal, value=None, - doc='Detector instances which this one triggers') + mode = Cpt(Signal, value="internal", doc="Triggering mode (internal/external)") + scan_type = Cpt(Signal, value="step", doc="Scan type (step/fly)") + make_directories = Cpt(Signal, value=True, doc="Make directories on the DAQ side") + total_points = Cpt( + Signal, value=2, doc="The total number of points to acquire overall" + ) + triggers = Cpt(Signal, value=None, doc="Detector instances which this one triggers") class ModalBase(Device): - mode_settings = Cpt(ModalSettings, '') - count_time = Cpt(Signal, value=1.0, - doc='Exposure/count time, as specified by bluesky') + mode_settings = Cpt(ModalSettings, "") + count_time = Cpt( + Signal, value=1.0, doc="Exposure/count time, as specified by bluesky" + ) def mode_setup(self, mode): devices = [self] + [getattr(self, attr) for attr in self._sub_devices] - attr = 'mode_{}'.format(mode) + attr = f"mode_{mode}" for dev in devices: if hasattr(dev, attr): mode_setup_method = getattr(dev, attr) mode_setup_method() def mode_internal(self): - logger.debug('%s internal triggering %s', self.name, - self.mode_settings.get()) + logger.debug("%s internal triggering %s", self.name, self.mode_settings.get()) def mode_external(self): - logger.debug('%s external triggering %s', self.name, - self.mode_settings.get()) + logger.debug("%s external triggering %s", self.name, self.mode_settings.get()) @property def mode(self): - '''Trigger mode (external/internal)''' + """Trigger mode (external/internal)""" return self.mode_settings.mode.get() def stage(self): @@ -71,9 +70,10 @@ def stage(self): return super().stage() def unstage(self): - if self.mode == 'external': - logger.debug('[Unstage] Stopping externally-triggered detector %s', - self.name) + if self.mode == "external": + logger.debug( + "[Unstage] Stopping externally-triggered detector %s", self.name + ) self.stop(success=True) super().unstage() @@ -83,7 +83,7 @@ class ModalTrigger(ModalBase, TriggerBase): def __init__(self, *args, image_name=None, **kwargs): super().__init__(*args, **kwargs) if image_name is None: - image_name = '_'.join([self.name, 'image']) + image_name = "_".join([self.name, "image"]) self._image_name = image_name self._external_acquire_at_stage = True @@ -100,8 +100,8 @@ def mode_internal(self): ordered_dict_move_to_beginning(cam.stage_sigs, cam.acquire) cam.stage_sigs[cam.num_images] = 1 - cam.stage_sigs[cam.image_mode] = 'Single' - cam.stage_sigs[cam.trigger_mode] = 'Internal' + cam.stage_sigs[cam.image_mode] = "Single" + cam.stage_sigs[cam.trigger_mode] = "Internal" def mode_external(self): super().mode_external() @@ -109,8 +109,8 @@ def mode_external(self): cam = self.cam cam.stage_sigs[cam.num_images] = total_points - cam.stage_sigs[cam.image_mode] = 'Multiple' - cam.stage_sigs[cam.trigger_mode] = 'External' + cam.stage_sigs[cam.image_mode] = "Multiple" + cam.stage_sigs[cam.trigger_mode] = "External" def stage(self): self._acquisition_signal.subscribe(self._acquire_changed) @@ -118,7 +118,7 @@ def stage(self): # In external triggering mode, the devices is only triggered once at # stage - if self.mode == 'external' and self._external_acquire_at_stage: + if self.mode == "external" and self._external_acquire_at_stage: self._acquisition_signal.put(1, wait=False) return staged @@ -130,8 +130,11 @@ def unstage(self): def trigger_internal(self): if self._staged != Staged.yes: - raise RuntimeError("This detector is not ready to trigger." - "Call the stage() method before triggering.") + msg = ( + "This detector is not ready to trigger." + "Call the stage() method before triggering." + ) + raise RuntimeError(msg) self._status = DeviceStatus(self) self._acquisition_signal.put(1, wait=False) @@ -140,23 +143,26 @@ def trigger_internal(self): def trigger_external(self): if self._staged != Staged.yes: - raise RuntimeError("This detector is not ready to trigger." - "Call the stage() method before triggering.") + msg = ( + "This detector is not ready to trigger." + "Call the stage() method before triggering." + ) + raise RuntimeError(msg) self._status = DeviceStatus(self) self._status._finished() # TODO this timestamp is inaccurate! - if self.mode_settings.scan_type.get() != 'fly': + if self.mode_settings.scan_type.get() != "fly": # Don't dispatch images for fly-scans-they are bulk read at the end self.generate_datum(self._image_name, ttime.time(), {}) return self._status def trigger(self): - mode_trigger = getattr(self, f'trigger_{self.mode}') + mode_trigger = getattr(self, f"trigger_{self.mode}") return mode_trigger() - def _acquire_changed(self, value=None, old_value=None, **kwargs): - '''This is called when the 'acquire' signal changes.''' + def _acquire_changed(self, value=None, old_value=None, **kwargs): # noqa : ARG002 + """This is called when the 'acquire' signal changes.""" if self._status is None: return if (old_value == 1) and (value == 0): @@ -165,7 +171,6 @@ def _acquire_changed(self, value=None, old_value=None, **kwargs): class FileStoreBulkReadable(FileStoreIterativeWrite): - def _reset_data(self): self._datum_uids.clear() self._point_counter = itertools.count() @@ -173,8 +178,7 @@ def _reset_data(self): def bulk_read(self, timestamps): image_name = self.image_name - uids = [self.generate_datum(self.image_name, ts, {}) - for ts in timestamps] + uids = [self.generate_datum(self.image_name, ts, {}) for ts in timestamps] # clear so unstage will not save the images twice: self._reset_data() diff --git a/nslsii/detectors/utils.py b/src/nslsii/detectors/utils.py similarity index 57% rename from nslsii/detectors/utils.py rename to src/nslsii/detectors/utils.py index 7e4e174f..95fb0886 100644 --- a/nslsii/detectors/utils.py +++ b/src/nslsii/detectors/utils.py @@ -1,23 +1,24 @@ -from __future__ import print_function -import os +from __future__ import annotations +from pathlib import Path -def makedirs(path, mode=0o777): - '''Recursively make directories and set permissions''' + +def makedirs(path: Path, mode: int = 0o777) -> list[str]: + """Recursively make directories and set permissions""" # Permissions not working with os.makedirs - # See: http://stackoverflow.com/questions/5231901 - if not path or os.path.exists(path): + if path is None or str(path) == "" or path.exists(): return [] - head, tail = os.path.split(path) + head, _ = Path.split(path) ret = makedirs(head, mode) try: - os.mkdir(path) + Path.mkdir(path) except OSError as ex: - if 'File exists' not in str(ex): + if "File exists" not in str(ex): raise - os.chmod(path, mode) + Path.chmod(path, mode) ret.append(path) return ret @@ -27,17 +28,16 @@ def ordered_dict_move_to_beginning(od, key): return value = od[key] - items = list((k, v) for k, v in od.items() - if k != key) + items = [(k, v) for k, v in od.items() if k != key] od.clear() od[key] = value od.update(items) -def make_filename_add_subdirectory(fn, read_path, write_path, *, - make_directories=True, - hash_characters=5): - ''' +def make_filename_add_subdirectory( + fn, read_path, write_path, *, make_directories=True, hash_characters=5 +): + """ tag on a portion of the hash to reduce the number of files in one directory @@ -53,10 +53,10 @@ def make_filename_add_subdirectory(fn, read_path, write_path, *, Make directories and set permissions (on the read_path) hash_characters : int, optional Number of characters to use from the hash - ''' + """ hash_portion = fn[:hash_characters] - read_path = os.path.join(read_path, hash_portion, '') - write_path = os.path.join(write_path, hash_portion, '') + read_path = Path(read_path) / hash_portion + write_path = Path(write_path) / hash_portion if make_directories: makedirs(read_path) diff --git a/nslsii/detectors/webcam.py b/src/nslsii/detectors/webcam.py similarity index 89% rename from nslsii/detectors/webcam.py rename to src/nslsii/detectors/webcam.py index 2286727e..4db8a610 100644 --- a/nslsii/detectors/webcam.py +++ b/src/nslsii/detectors/webcam.py @@ -1,6 +1,9 @@ +from __future__ import annotations + import datetime import itertools import logging +import sys import time as ttime import warnings from collections import deque @@ -34,7 +37,8 @@ def __init__( **kwargs, ): warnings.warn( - f"This class {self.__class__.__name__} will be removed in the future." + f"This class {self.__class__.__name__} will be removed in the future.", + stacklevel=2, ) super().__init__(*args, **kwargs) @@ -72,7 +76,7 @@ def stage(self): self._resource_document.pop("run_start") self._asset_docs_cache.append(("resource", self._resource_document)) - logger.debug(f"{self._data_file = }") + logger.debug("%r", self._data_file) self._h5file_desc = h5py.File(self._data_file, "x") group = self._h5file_desc.create_group("/entry") @@ -96,29 +100,29 @@ def trigger(self, *args, **kwargs): i = 0 cap = cv2.VideoCapture(self._video_stream_url) while True: - logger.debug(f"Iteration: {i}") + logger.debug("Iteration: %r", i) i += 1 ret, frame = cap.read() frames.append(frame) times.append(ttime.time()) # cv2.imshow('Video', frame) - logger.debug(f"shape: {frame.shape}") + logger.debug("shape: %r", frame.shape) if ttime.monotonic() - start >= self.exposure_time.get(): break if cv2.waitKey(1) == 27: - exit(0) + sys.exit(0) frames = np.array(frames) - logger.debug(f"original shape: {frames.shape}") + logger.debug("original shape: %r", frames.shape) # Averaging over all frames and summing 3 RGB channels averaged = frames.mean(axis=0).sum(axis=-1) current_frame = next(self._counter) self._dataset.resize((current_frame + 1, *self._frame_shape)) - logger.debug(f"{self._dataset = }\n{self._dataset.shape = }") + logger.debug("%r\nshape=%r", self._dataset, self._dataset.shape) self._dataset[current_frame, :, :] = averaged datum_document = self._datum_factory(datum_kwargs={"frame": current_frame}) @@ -131,7 +135,7 @@ def trigger(self, *args, **kwargs): def describe(self): res = super().describe() - res[self.image.name].update(dict(shape=self._frame_shape)) + res[self.image.name].update({"shape": self._frame_shape}) return res def unstage(self): @@ -144,5 +148,5 @@ def unstage(self): def collect_asset_docs(self): items = list(self._asset_docs_cache) self._asset_docs_cache.clear() - for item in items: + for item in items: # noqa : UP028 yield item diff --git a/nslsii/detectors/xspress3.py b/src/nslsii/detectors/xspress3.py similarity index 53% rename from nslsii/detectors/xspress3.py rename to src/nslsii/detectors/xspress3.py index 037e987f..8eb811d5 100644 --- a/nslsii/detectors/xspress3.py +++ b/src/nslsii/detectors/xspress3.py @@ -1,47 +1,48 @@ -from __future__ import print_function, division +from __future__ import annotations + +import logging import time import time as ttime -import logging - -from .utils import makedirs - from collections import OrderedDict import h5py - -from ophyd.areadetector import (DetectorBase, CamBase, - EpicsSignalWithRBV as SignalWithRBV) -from ophyd import (Signal, EpicsSignal, EpicsSignalRO, DerivedSignal) - -from ophyd import (Device, Component as Cpt, FormattedComponent as FC, # noqa: F401 - DynamicDeviceComponent as DDC) -from ophyd.areadetector.plugins import PluginBase +from databroker.assets.handlers import XS3_XRF_DATA_KEY as XRF_DATA_KEY +from databroker.assets.handlers import Xspress3HDF5Handler +from ophyd import Component as Cpt +from ophyd import ( # noqa: F401 + DerivedSignal, + Device, + EpicsSignal, + EpicsSignalRO, + Signal, +) +from ophyd import DynamicDeviceComponent as DDC +from ophyd import FormattedComponent as FC +from ophyd.areadetector import ADBase, CamBase, DetectorBase +from ophyd.areadetector import EpicsSignalWithRBV as SignalWithRBV from ophyd.areadetector.filestore_mixins import FileStorePluginBase - -from ophyd.areadetector.plugins import HDF5Plugin -from ophyd.areadetector import ADBase -from ophyd.device import (BlueskyInterface, Staged) +from ophyd.areadetector.plugins import HDF5Plugin, PluginBase +from ophyd.device import BlueskyInterface, Staged from ophyd.status import DeviceStatus -from databroker.assets.handlers import (Xspress3HDF5Handler, - XS3_XRF_DATA_KEY as XRF_DATA_KEY) - +from .utils import makedirs logger = logging.getLogger(__name__) def ev_to_bin(ev): - '''Convert eV to bin number''' + """Convert eV to bin number""" return int(ev / 10) def bin_to_ev(bin_): - '''Convert bin number to eV''' + """Convert bin number to eV""" return int(bin_) * 10 class EvSignal(DerivedSignal): - '''A signal that converts a bin number into electron volts''' + """A signal that converts a bin number into electron volts""" + def __init__(self, parent_attr, *, parent=None, **kwargs): bin_signal = getattr(parent, parent_attr) super().__init__(derived_from=bin_signal, parent=parent, **kwargs) @@ -56,19 +57,26 @@ def put(self, ev_value, **kwargs): def describe(self): desc = super().describe() - desc[self.name]['units'] = 'eV' + desc[self.name]["units"] = "eV" return desc class Xspress3FileStore(FileStorePluginBase, HDF5Plugin): - '''Xspress3 acquisition -> filestore''' - num_capture_calc = Cpt(EpicsSignal, 'NumCapture_CALC') - num_capture_calc_disable = Cpt(EpicsSignal, 'NumCapture_CALC.DISA') + """Xspress3 acquisition -> filestore""" + + num_capture_calc = Cpt(EpicsSignal, "NumCapture_CALC") + num_capture_calc_disable = Cpt(EpicsSignal, "NumCapture_CALC.DISA") filestore_spec = Xspress3HDF5Handler.HANDLER_NAME - def __init__(self, basename, *, config_time=0.5, - mds_key_format='{self.settings.name}_ch{chan}', parent=None, - **kwargs): + def __init__( + self, + basename, + *, + config_time=0.5, + mds_key_format="{self.settings.name}_ch{chan}", + parent=None, + **kwargs, + ): super().__init__(basename, parent=parent, **kwargs) det = parent self.settings = det.settings @@ -76,19 +84,21 @@ def __init__(self, basename, *, config_time=0.5, # Use the EpicsSignal file_template from the detector self.stage_sigs[self.blocking_callbacks] = 1 self.stage_sigs[self.enable] = 1 - self.stage_sigs[self.compression] = 'zlib' - self.stage_sigs[self.file_template] = '%s%s_%6.6d.h5' + self.stage_sigs[self.compression] = "zlib" + self.stage_sigs[self.file_template] = "%s%s_%6.6d.h5" self._filestore_res = None - self.channels = list(range(1, len([_ for _ in det.component_names - if _.startswith('chan')]) + 1)) + self.channels = list( + range(1, len([_ for _ in det.component_names if _.startswith("chan")]) + 1) + ) # this was in original code, but I kinda-sorta nuked because # it was not needed for SRX and I could not guess what it did self._master = None self._config_time = config_time - self.mds_keys = {chan: mds_key_format.format(self=self, chan=chan) - for chan in self.channels} + self.mds_keys = { + chan: mds_key_format.format(self=self, chan=chan) for chan in self.channels + } def stop(self, success=False): ret = super().stop(success=success) @@ -121,28 +131,33 @@ def unstage(self): while self.capture.get() == 1: i += 1 if (i % 50) == 0: - logger.warning('Still capturing data .... waiting.') + logger.warning("Still capturing data .... waiting.") time.sleep(0.1) if i > 150: - logger.warning('Still capturing data .... giving up.') - logger.warning('Check that the xspress3 is configured to take the right ' - 'number of frames ' - f'(it is trying to take {self.parent.settings.num_images.get()})') + logger.warning("Still capturing data .... giving up.") + logger.warning( + "Check that the xspress3 is configured to take the right " + "number of frames (it is trying to take %s)", + self.parent.settings.num_images.get(), + ) self.capture.put(0) break except KeyboardInterrupt: self.capture.put(0) - logger.warning('Still capturing data .... interrupted.') + logger.warning("Still capturing data .... interrupted.") return super().unstage() def generate_datum(self, key, timestamp, datum_kwargs): - sn, n = next((f'channel{j}', j) - for j in self.channels - if getattr(self.parent, f'channel{j}').name == key) - datum_kwargs.update({'frame': self.parent._abs_trigger_count, - 'channel': int(sn[7:])}) + sn, n = next( + (f"channel{j}", j) + for j in self.channels + if getattr(self.parent, f"channel{j}").name == key + ) + datum_kwargs.update( + {"frame": self.parent._abs_trigger_count, "channel": int(sn[7:])} + ) self.mds_keys[n] = key super().generate_datum(key, timestamp, datum_kwargs) @@ -150,13 +165,14 @@ def stage(self): # if should external trigger ext_trig = self.parent.external_trig.get() - logger.debug('Stopping xspress3 acquisition') + logger.debug("Stopping xspress3 acquisition") # really force it to stop acquiring self.settings.acquire.put(0, wait=True) total_points = self.parent.total_points.get() if total_points < 1: - raise RuntimeError("You must set the total points") + msg = "You must set the total points" + raise RuntimeError(msg) spec_per_point = self.parent.spectra_per_point.get() total_capture = total_points * spec_per_point @@ -170,26 +186,27 @@ def stage(self): self.stage_sigs[self.num_capture_calc_disable] = 1 if ext_trig: - logger.debug('Setting up external triggering') - self.stage_sigs[self.settings.trigger_mode] = 'TTL Veto Only' + logger.debug("Setting up external triggering") + self.stage_sigs[self.settings.trigger_mode] = "TTL Veto Only" self.stage_sigs[self.settings.num_images] = total_capture else: - logger.debug('Setting up internal triggering') + logger.debug("Setting up internal triggering") # self.settings.trigger_mode.put('Internal') # self.settings.num_images.put(1) - self.stage_sigs[self.settings.trigger_mode] = 'Internal' + self.stage_sigs[self.settings.trigger_mode] = "Internal" self.stage_sigs[self.settings.num_images] = spec_per_point - self.stage_sigs[self.auto_save] = 'No' - logger.debug('Configuring other filestore stuff') + self.stage_sigs[self.auto_save] = "No" + logger.debug("Configuring other filestore stuff") - logger.debug('Making the filename') + logger.debug("Making the filename") filename, read_path, write_path = self.make_filename() - logger.debug('Setting up hdf5 plugin: ioc path: %s filename: %s', - write_path, filename) + logger.debug( + "Setting up hdf5 plugin: ioc path: %s filename: %s", write_path, filename + ) - logger.debug('Erasing old spectra') + logger.debug("Erasing old spectra") self.settings.erase.put(1, wait=True) # this must be set after self.settings.num_images because at the Epics @@ -200,15 +217,17 @@ def stage(self): # actually apply the stage_sigs ret = super().stage() - self._fn = self.file_template.get() % (self._fp, - self.file_name.get(), - self.file_number.get()) + self._fn = self.file_template.get() % ( + self._fp, + self.file_name.get(), + self.file_number.get(), + ) if not self.file_path_exists.get(): - raise IOError("Path {} does not exits on IOC!! Please Check" - .format(self.file_path.get())) + msg = f"Path {self.file_path.get()} does not exits on IOC!! Please Check" + raise OSError(msg) - logger.debug('Inserting the filestore resource: %s', self._fn) + logger.debug("Inserting the filestore resource: %s", self._fn) self._generate_resource({}) self._filestore_res = self._asset_docs_cache[-1][-1] @@ -221,19 +240,19 @@ def stage(self): return ret - def configure(self, total_points=0, master=None, external_trig=False, - **kwargs): + def configure(self, total_points=0, master=None, external_trig=False, **kwargs): raise NotImplementedError() def describe(self): # should this use a better value? - size = (self.width.get(), ) + size = (self.width.get(),) - spec_desc = {'external': 'FILESTORE:', - 'dtype': 'array', - 'shape': size, - 'source': 'FileStore:' - } + spec_desc = { + "external": "FILESTORE:", + "dtype": "array", + "shape": size, + "source": "FileStore:", + } desc = OrderedDict() for chan in self.channels: @@ -244,53 +263,59 @@ def describe(self): class Xspress3DetectorSettings(CamBase): - '''Quantum Detectors Xspress3 detector''' + """Quantum Detectors Xspress3 detector""" - def __init__(self, prefix, *, read_attrs=None, configuration_attrs=None, - **kwargs): + def __init__(self, prefix, *, read_attrs=None, configuration_attrs=None, **kwargs): if read_attrs is None: read_attrs = [] if configuration_attrs is None: - configuration_attrs = ['config_path', 'config_save_path', - ] - super().__init__(prefix, read_attrs=read_attrs, - configuration_attrs=configuration_attrs, **kwargs) - - config_path = Cpt(SignalWithRBV, 'CONFIG_PATH', string=True) - config_save_path = Cpt(SignalWithRBV, 'CONFIG_SAVE_PATH', string=True) - connect = Cpt(EpicsSignal, 'CONNECT') - connected = Cpt(EpicsSignal, 'CONNECTED') - ctrl_dtc = Cpt(SignalWithRBV, 'CTRL_DTC') - ctrl_mca_roi = Cpt(SignalWithRBV, 'CTRL_MCA_ROI') - debounce = Cpt(SignalWithRBV, 'DEBOUNCE') - disconnect = Cpt(EpicsSignal, 'DISCONNECT') - erase = Cpt(EpicsSignal, 'ERASE') + configuration_attrs = [ + "config_path", + "config_save_path", + ] + super().__init__( + prefix, + read_attrs=read_attrs, + configuration_attrs=configuration_attrs, + **kwargs, + ) + + config_path = Cpt(SignalWithRBV, "CONFIG_PATH", string=True) + config_save_path = Cpt(SignalWithRBV, "CONFIG_SAVE_PATH", string=True) + connect = Cpt(EpicsSignal, "CONNECT") + connected = Cpt(EpicsSignal, "CONNECTED") + ctrl_dtc = Cpt(SignalWithRBV, "CTRL_DTC") + ctrl_mca_roi = Cpt(SignalWithRBV, "CTRL_MCA_ROI") + debounce = Cpt(SignalWithRBV, "DEBOUNCE") + disconnect = Cpt(EpicsSignal, "DISCONNECT") + erase = Cpt(EpicsSignal, "ERASE") # erase_array_counters = Cpt(EpicsSignal, 'ERASE_ArrayCounters') # erase_attr_reset = Cpt(EpicsSignal, 'ERASE_AttrReset') # erase_proc_reset_filter = Cpt(EpicsSignal, 'ERASE_PROC_ResetFilter') - frame_count = Cpt(EpicsSignalRO, 'FRAME_COUNT_RBV') - invert_f0 = Cpt(SignalWithRBV, 'INVERT_F0') - invert_veto = Cpt(SignalWithRBV, 'INVERT_VETO') - max_frames = Cpt(EpicsSignalRO, 'MAX_FRAMES_RBV') - max_frames_driver = Cpt(EpicsSignalRO, 'MAX_FRAMES_DRIVER_RBV') - max_num_channels = Cpt(EpicsSignalRO, 'MAX_NUM_CHANNELS_RBV') - max_spectra = Cpt(SignalWithRBV, 'MAX_SPECTRA') - xsp_name = Cpt(EpicsSignal, 'NAME') - num_cards = Cpt(EpicsSignalRO, 'NUM_CARDS_RBV') - num_channels = Cpt(SignalWithRBV, 'NUM_CHANNELS') - num_frames_config = Cpt(SignalWithRBV, 'NUM_FRAMES_CONFIG') - reset = Cpt(EpicsSignal, 'RESET') - restore_settings = Cpt(EpicsSignal, 'RESTORE_SETTINGS') - run_flags = Cpt(SignalWithRBV, 'RUN_FLAGS') - save_settings = Cpt(EpicsSignal, 'SAVE_SETTINGS') - trigger_signal = Cpt(EpicsSignal, 'TRIGGER') + frame_count = Cpt(EpicsSignalRO, "FRAME_COUNT_RBV") + invert_f0 = Cpt(SignalWithRBV, "INVERT_F0") + invert_veto = Cpt(SignalWithRBV, "INVERT_VETO") + max_frames = Cpt(EpicsSignalRO, "MAX_FRAMES_RBV") + max_frames_driver = Cpt(EpicsSignalRO, "MAX_FRAMES_DRIVER_RBV") + max_num_channels = Cpt(EpicsSignalRO, "MAX_NUM_CHANNELS_RBV") + max_spectra = Cpt(SignalWithRBV, "MAX_SPECTRA") + xsp_name = Cpt(EpicsSignal, "NAME") + num_cards = Cpt(EpicsSignalRO, "NUM_CARDS_RBV") + num_channels = Cpt(SignalWithRBV, "NUM_CHANNELS") + num_frames_config = Cpt(SignalWithRBV, "NUM_FRAMES_CONFIG") + reset = Cpt(EpicsSignal, "RESET") + restore_settings = Cpt(EpicsSignal, "RESTORE_SETTINGS") + run_flags = Cpt(SignalWithRBV, "RUN_FLAGS") + save_settings = Cpt(EpicsSignal, "SAVE_SETTINGS") + trigger_signal = Cpt(EpicsSignal, "TRIGGER") # update = Cpt(EpicsSignal, 'UPDATE') # update_attr = Cpt(EpicsSignal, 'UPDATE_AttrUpdate') class Xspress3ROISettings(PluginBase): - '''Full areaDetector plugin settings''' - array_data = Cpt(EpicsSignalRO, 'ArrayData_RBV') + """Full areaDetector plugin settings""" + + array_data = Cpt(EpicsSignalRO, "ArrayData_RBV") @property def ad_root(self): @@ -302,21 +327,21 @@ def ad_root(self): class Xspress3ROI(ADBase): - '''A configurable Xspress3 EPICS ROI''' + """A configurable Xspress3 EPICS ROI""" # prefix: C{channel}_ MCA_ROI{self.roi_num} - bin_low = FC(SignalWithRBV, '{self.channel.prefix}{self.bin_suffix}_LLM') - bin_high = FC(SignalWithRBV, '{self.channel.prefix}{self.bin_suffix}_HLM') + bin_low = FC(SignalWithRBV, "{self.channel.prefix}{self.bin_suffix}_LLM") + bin_high = FC(SignalWithRBV, "{self.channel.prefix}{self.bin_suffix}_HLM") # derived from the bin signals, low and high electron volt settings: - ev_low = Cpt(EvSignal, parent_attr='bin_low') - ev_high = Cpt(EvSignal, parent_attr='bin_high') + ev_low = Cpt(EvSignal, parent_attr="bin_low") + ev_high = Cpt(EvSignal, parent_attr="bin_high") # C{channel}_ ROI{self.roi_num} - value = Cpt(EpicsSignalRO, 'Value_RBV') - value_sum = Cpt(EpicsSignalRO, 'ValueSum_RBV') + value = Cpt(EpicsSignalRO, "Value_RBV") + value_sum = Cpt(EpicsSignalRO, "ValueSum_RBV") - enable = Cpt(SignalWithRBV, 'EnableCallbacks') + enable = Cpt(SignalWithRBV, "EnableCallbacks") # ad_plugin = Cpt(Xspress3ROISettings, '') @property @@ -327,60 +352,70 @@ def ad_root(self): return root root = root.parent - def __init__(self, prefix, *, roi_num=0, use_sum=False, - read_attrs=None, configuration_attrs=None, parent=None, - bin_suffix=None, **kwargs): - + def __init__( + self, + prefix, + *, + roi_num=0, + use_sum=False, + read_attrs=None, + configuration_attrs=None, + parent=None, + bin_suffix=None, + **kwargs, + ): if read_attrs is None: - if use_sum: - read_attrs = ['value_sum'] - else: - read_attrs = ['value', 'value_sum'] + read_attrs = ["value_sum"] if use_sum else ["value", "value_sum"] if configuration_attrs is None: - configuration_attrs = ['ev_low', 'ev_high', 'enable'] + configuration_attrs = ["ev_low", "ev_high", "enable"] rois = parent channel = rois.parent self._channel = channel self._roi_num = roi_num self._use_sum = use_sum - self._ad_plugin = getattr(rois, 'ad_attr{:02d}'.format(roi_num)) + self._ad_plugin = getattr(rois, f"ad_attr{roi_num:02d}") if bin_suffix is None: - bin_suffix = 'MCA_ROI{}'.format(roi_num) + bin_suffix = f"MCA_ROI{roi_num}" self.bin_suffix = bin_suffix - super().__init__(prefix, parent=parent, read_attrs=read_attrs, - configuration_attrs=configuration_attrs, **kwargs) + super().__init__( + prefix, + parent=parent, + read_attrs=read_attrs, + configuration_attrs=configuration_attrs, + **kwargs, + ) @property def settings(self): - '''Full areaDetector settings''' + """Full areaDetector settings""" return self._ad_plugin @property def channel(self): - '''The Xspress3Channel instance associated with the ROI''' + """The Xspress3Channel instance associated with the ROI""" return self._channel @property def channel_num(self): - '''The channel number associated with the ROI''' + """The channel number associated with the ROI""" return self._channel.channel_num @property def roi_num(self): - '''The ROI number''' + """The ROI number""" return self._roi_num def clear(self): - '''Clear and disable this ROI''' + """Clear and disable this ROI""" self.configure(0, 0) def configure(self, ev_low, ev_high): - '''Configure the ROI with low and high eV + """Configure the ROI with low and high eV Parameters ---------- @@ -388,22 +423,31 @@ def configure(self, ev_low, ev_high): low electron volts for ROI ev_high : int high electron volts for ROI - ''' + """ ev_low = int(ev_low) ev_high = int(ev_high) enable = 1 if ev_high > ev_low else 0 - changed = any([self.ev_high.get() != ev_high, - self.ev_low.get() != ev_low, - self.enable.get() != enable]) + changed = any( + [ + self.ev_high.get() != ev_high, + self.ev_low.get() != ev_low, + self.enable.get() != enable, + ] + ) if not changed: return - logger.debug('Setting up EPICS ROI: name=%s ev=(%s, %s) ' - 'enable=%s prefix=%s channel=%s', - self.name, ev_low, ev_high, enable, self.prefix, - self._channel) + logger.debug( + "Setting up EPICS ROI: name=%s ev=(%s, %s) enable=%s prefix=%s channel=%s", + self.name, + ev_low, + ev_high, + enable, + self.prefix, + self._channel, + ) if ev_high <= self.ev_low.get(): self.ev_low.put(0) @@ -415,33 +459,32 @@ def configure(self, ev_low, ev_high): def make_rois(rois): defn = OrderedDict() for roi in rois: - attr = 'roi{:02d}'.format(roi) + attr = f"roi{roi:02d}" # cls prefix kwargs - defn[attr] = (Xspress3ROI, 'ROI{}:'.format(roi), dict(roi_num=roi)) + defn[attr] = (Xspress3ROI, f"ROI{roi}:", {"roi_num": roi}) # e.g., device.rois.roi01 = Xspress3ROI('ROI1:', roi_num=1) # AreaDetector NDPluginAttribute information - attr = 'ad_attr{:02d}'.format(roi) - defn[attr] = (Xspress3ROISettings, 'ROI{}:'.format(roi), - dict(read_attrs=[])) + attr = f"ad_attr{roi:02d}" + defn[attr] = (Xspress3ROISettings, f"ROI{roi}:", {"read_attrs": []}) # e.g., device.rois.roi01 = Xspress3ROI('ROI1:', roi_num=1) # TODO: 'roi01' and 'ad_attr_01' have the same prefix and could # technically be combined. Is this desirable? - defn['num_rois'] = (Signal, None, dict(value=len(rois))) + defn["num_rois"] = (Signal, None, {"value": len(rois)}) # e.g., device.rois.num_rois.get() => 16 return defn class Xspress3Channel(ADBase): - roi_name_format = 'Det{self.channel_num}_{roi_name}' - roi_sum_name_format = 'Det{self.channel_num}_{roi_name}_sum' + roi_name_format = "Det{self.channel_num}_{roi_name}" + roi_sum_name_format = "Det{self.channel_num}_{roi_name}_sum" rois = DDC(make_rois(range(1, 17))) - vis_enabled = Cpt(EpicsSignal, 'PluginControlVal') - extra_rois_enabled = Cpt(EpicsSignal, 'PluginControlValExtraROI') - + vis_enabled = Cpt(EpicsSignal, "PluginControlVal") + extra_rois_enabled = Cpt(EpicsSignal, "PluginControlValExtraROI") + def __init__(self, prefix, *, channel_num=None, **kwargs): self.channel_num = int(channel_num) @@ -450,10 +493,10 @@ def __init__(self, prefix, *, channel_num=None, **kwargs): @property def all_rois(self): for roi in range(1, self.rois.num_rois.get() + 1): - yield getattr(self.rois, 'roi{:02d}'.format(roi)) + yield getattr(self.rois, f"roi{roi:02d}") def set_roi(self, index, ev_low, ev_high, *, name=None): - '''Set specified ROI to (ev_low, ev_high) + """Set specified ROI to (ev_low, ev_high) Parameters ---------- @@ -467,12 +510,13 @@ def set_roi(self, index, ev_low, ev_high, *, name=None): The unformatted ROI name to set. Each channel specifies its own `roi_name_format` and `roi_sum_name_format` in which the name parameter will get expanded. - ''' + """ if isinstance(index, Xspress3ROI): roi = index else: if index <= 0: - raise ValueError('ROI index starts from 1') + msg = "ROI index starts from 1" + raise ValueError(msg) roi = list(self.all_rois)[index - 1] roi.configure(ev_low, ev_high) @@ -480,62 +524,77 @@ def set_roi(self, index, ev_low, ev_high, *, name=None): roi_name = self.roi_name_format.format(self=self, roi_name=name) roi.name = roi_name roi.value.name = roi_name - roi.value_sum.name = self.roi_sum_name_format.format(self=self, - roi_name=name) + roi.value_sum.name = self.roi_sum_name_format.format( + self=self, roi_name=name + ) def clear_all_rois(self): - '''Clear all ROIs''' + """Clear all ROIs""" for roi in self.all_rois: roi.clear() class Xspress3Detector(DetectorBase): - settings = Cpt(Xspress3DetectorSettings, '') - - external_trig = Cpt(Signal, value=False, - doc='Use external triggering') - total_points = Cpt(Signal, value=-1, - doc='The total number of points to acquire overall') - spectra_per_point = Cpt(Signal, value=1, - doc='Number of spectra per point') - make_directories = Cpt(Signal, value=False, - doc='Make directories on the DAQ side') - rewindable = Cpt(Signal, value=False, - doc='Xspress3 cannot safely be rewound in bluesky') + settings = Cpt(Xspress3DetectorSettings, "") + + external_trig = Cpt(Signal, value=False, doc="Use external triggering") + total_points = Cpt( + Signal, value=-1, doc="The total number of points to acquire overall" + ) + spectra_per_point = Cpt(Signal, value=1, doc="Number of spectra per point") + make_directories = Cpt(Signal, value=False, doc="Make directories on the DAQ side") + rewindable = Cpt( + Signal, value=False, doc="Xspress3 cannot safely be rewound in bluesky" + ) # XF:03IDC-ES{Xsp:1} C1_ ... # channel1 = Cpt(Xspress3Channel, 'C1_', channel_num=1) data_key = XRF_DATA_KEY - def __init__(self, prefix, *, read_attrs=None, configuration_attrs=None, - name=None, parent=None, - # to remove? - file_path='', ioc_file_path='', default_channels=None, - channel_prefix=None, - roi_sums=False, - # to remove? - **kwargs): - + def __init__( + self, + prefix, + *, + read_attrs=None, + configuration_attrs=None, + name=None, + parent=None, + # to remove? + file_path="", # noqa : ARG002 + ioc_file_path="", # noqa : ARG002 + default_channels=None, # noqa : ARG002 + channel_prefix=None, # noqa : ARG002 + roi_sums=False, # noqa : ARG002 + # to remove? + **kwargs, + ): if read_attrs is None: - read_attrs = ['channel1', ] + read_attrs = [ + "channel1", + ] if configuration_attrs is None: - configuration_attrs = ['channel1.rois', 'settings'] + configuration_attrs = ["channel1.rois", "settings"] - super().__init__(prefix, read_attrs=read_attrs, - configuration_attrs=configuration_attrs, - name=name, parent=parent, **kwargs) + super().__init__( + prefix, + read_attrs=read_attrs, + configuration_attrs=configuration_attrs, + name=name, + parent=parent, + **kwargs, + ) # get all sub-device instances - sub_devices = {attr: getattr(self, attr) - for attr in self._sub_devices} + sub_devices = {attr: getattr(self, attr) for attr in self._sub_devices} # filter those sub-devices, just giving channels - channels = {dev.channel_num: dev - for attr, dev in sub_devices.items() - if isinstance(dev, Xspress3Channel) - } + channels = { + dev.channel_num: dev + for attr, dev in sub_devices.items() + if isinstance(dev, Xspress3Channel) + } # make an ordered dictionary with the channels in order self._channels = OrderedDict(sorted(channels.items())) @@ -546,8 +605,8 @@ def channels(self): @property def all_rois(self): - for ch_num, channel in self._channels.items(): - for roi in channel.all_rois: + for _, channel in self._channels.items(): + for roi in channel.all_rois: # noqa : UP028 yield roi @property @@ -556,8 +615,8 @@ def enabled_rois(self): if roi.enable.get(): yield roi - def read_hdf5(self, fn, *, rois=None, max_retries=2): - '''Read ROI data from an HDF5 file using the current ROI configuration + def read_hdf5(self, fn, *, rois=None, max_retries=2): # noqa : ARG002 + """Read ROI data from an HDF5 file using the current ROI configuration Parameters ---------- @@ -565,32 +624,33 @@ def read_hdf5(self, fn, *, rois=None, max_retries=2): HDF5 filename to load rois : sequence of Xspress3ROI instances, optional - ''' + """ if rois is None: rois = self.enabled_rois num_points = self.settings.num_images.get() - if isinstance(fn, h5py.File): - hdf = fn - else: - hdf = h5py.File(fn, 'r') + hdf = fn if isinstance(fn, h5py.File) else h5py.File(fn, "r") RoiTuple = Xspress3ROI.get_device_tuple() handler = Xspress3HDF5Handler(hdf, key=self.data_key) for roi in self.enabled_rois: - roi_data = handler.get_roi(chan=roi.channel_num, - bin_low=roi.bin_low.get(), - bin_high=roi.bin_high.get(), - max_points=num_points) - - roi_info = RoiTuple(bin_low=roi.bin_low.get(), - bin_high=roi.bin_high.get(), - ev_low=roi.ev_low.get(), - ev_high=roi.ev_high.get(), - value=roi_data, - value_sum=None, - enable=None) + roi_data = handler.get_roi( + chan=roi.channel_num, + bin_low=roi.bin_low.get(), + bin_high=roi.bin_high.get(), + max_points=num_points, + ) + + roi_info = RoiTuple( + bin_low=roi.bin_low.get(), + bin_high=roi.bin_high.get(), + ev_low=roi.ev_low.get(), + ev_high=roi.ev_high.get(), + value=roi_data, + value_sum=None, + enable=None, + ) yield roi.name, roi_info @@ -602,6 +662,7 @@ class XspressTrigger(BlueskyInterface): `acquire_changed(self, value=None, old_value=None, **kwargs)` """ + # TODO ** # count_time = self.settings.acquire_period @@ -623,7 +684,7 @@ def unstage(self): self._status = None return ret - def _acquire_changed(self, value=None, old_value=None, **kwargs): + def _acquire_changed(self, value=None, old_value=None, **kwargs): # noqa : ARG002 "This is called when the 'acquire' signal changes." if self._status is None: return @@ -633,14 +694,15 @@ def _acquire_changed(self, value=None, old_value=None, **kwargs): def trigger(self): if self._staged != Staged.yes: - raise RuntimeError("not staged") + msg = "not staged" + raise RuntimeError(msg) self._status = DeviceStatus(self) self._acquisition_signal.put(1, wait=False) trigger_time = ttime.time() for sn in self.read_attrs: - if sn.startswith('channel') and '.' not in sn: + if sn.startswith("channel") and "." not in sn: ch = getattr(self, sn) self.generate_datum(ch.name, trigger_time, {}) diff --git a/src/nslsii/detectors/zebra.py b/src/nslsii/detectors/zebra.py new file mode 100644 index 00000000..2dfaa793 --- /dev/null +++ b/src/nslsii/detectors/zebra.py @@ -0,0 +1,371 @@ +from __future__ import annotations + +import logging +from enum import IntEnum +from typing import ClassVar + +from ophyd import Component as Cpt +from ophyd import Device, DeviceStatus, EpicsSignal, EpicsSignalRO, Signal +from ophyd import FormattedComponent as FC +from ophyd.utils import set_and_wait + +from .trigger_mixins import ModalBase + +logger = logging.getLogger(__name__) + + +def _get_configuration_attrs(inst, *, signal_class=Signal): + cls = inst.__class__ + return [ + sig_name + for sig_name in cls.component_names + if issubclass(getattr(cls, sig_name).cls, signal_class) + ] + + +class ZebraInputEdge(IntEnum): + FALLING = 1 + RISING = 0 + + +class ZebraAddresses(IntEnum): + DISCONNECT = 0 + IN1_TTL = 1 + IN1_NIM = 2 + IN1_LVDS = 3 + IN2_TTL = 4 + IN2_NIM = 5 + IN2_LVDS = 6 + IN3_TTL = 7 + IN3_OC = 8 + IN3_LVDS = 9 + IN4_TTL = 10 + IN4_CMP = 11 + IN4_PECL = 12 + IN5_ENCA = 13 + IN5_ENCB = 14 + IN5_ENCZ = 15 + IN5_CONN = 16 + IN6_ENCA = 17 + IN6_ENCB = 18 + IN6_ENCZ = 19 + IN6_CONN = 20 + IN7_ENCA = 21 + IN7_ENCB = 22 + IN7_ENCZ = 23 + IN7_CONN = 24 + IN8_ENCA = 25 + IN8_ENCB = 26 + IN8_ENCZ = 27 + IN8_CONN = 28 + PC_ARM = 29 + PC_GATE = 30 + PC_PULSE = 31 + AND1 = 32 + AND2 = 33 + AND3 = 34 + AND4 = 35 + OR1 = 36 + OR2 = 37 + OR3 = 38 + OR4 = 39 + GATE1 = 40 + GATE2 = 41 + GATE3 = 42 + GATE4 = 43 + DIV1_OUTD = 44 + DIV2_OUTD = 45 + DIV3_OUTD = 46 + DIV4_OUTD = 47 + DIV1_OUTN = 48 + DIV2_OUTN = 49 + DIV3_OUTN = 50 + DIV4_OUTN = 51 + PULSE1 = 52 + PULSE2 = 53 + PULSE3 = 54 + PULSE4 = 55 + QUAD_OUTA = 56 + QUAD_OUTB = 57 + CLOCK_1KHZ = 58 + CLOCK_1MHZ = 59 + SOFT_IN1 = 60 + SOFT_IN2 = 61 + SOFT_IN3 = 62 + SOFT_IN4 = 63 + + +class EpicsSignalWithRBV(EpicsSignal): + # An EPICS signal that uses the Zebra convention of 'pvname' being the + # setpoint and 'pvname:RBV' being the read-back + + def __init__(self, prefix, **kwargs): + super().__init__(prefix + ":RBV", write_pv=prefix, **kwargs) + + +class ZebraPulse(Device): + width = Cpt(EpicsSignalWithRBV, "WID") + input_addr = Cpt(EpicsSignalWithRBV, "INP") + input_str = Cpt(EpicsSignalRO, "INP:STR", string=True) + input_status = Cpt(EpicsSignalRO, "INP:STA") + delay = Cpt(EpicsSignalWithRBV, "DLY") + delay_sync = Cpt(EpicsSignal, "DLY:SYNC") + time_units = Cpt(EpicsSignalWithRBV, "PRE", string=True) + output = Cpt(EpicsSignal, "OUT") + + input_edge = FC(EpicsSignal, "{self._zebra_prefix}POLARITY:{self._edge_addr}") + + _edge_addrs: ClassVar[dict[int, str]] = { + 1: "BC", + 2: "BD", + 3: "BE", + 4: "BF", + } + + def __init__( + self, + prefix, + *, + index=None, + parent=None, + configuration_attrs=None, + read_attrs=None, + **kwargs, + ): + if read_attrs is None: + read_attrs = [] + if configuration_attrs is None: + configuration_attrs = _get_configuration_attrs(self) + + zebra = parent + self.index = index + self._zebra_prefix = zebra.prefix + self._edge_addr = self._edge_addrs[index] + + super().__init__( + prefix, + configuration_attrs=configuration_attrs, + read_attrs=read_attrs, + parent=parent, + **kwargs, + ) + + +class ZebraOutputBase(Device): + """The base of all zebra outputs (1~8) + + Front outputs + # TTL LVDS NIM PECL OC ENC + 1 o o o + 2 o o o + 3 o o o + 4 o o o + + Rear outputs + # TTL LVDS NIM PECL OC ENC + 5 o + 6 o + 7 o + 8 o + + """ + + def __init__( + self, prefix, *, index=None, read_attrs=None, configuration_attrs=None, **kwargs + ): + self.index = index + + if read_attrs is None: + read_attrs = [] + if configuration_attrs is None: + configuration_attrs = _get_configuration_attrs(self) + + super().__init__( + prefix, + read_attrs=read_attrs, + configuration_attrs=configuration_attrs, + **kwargs, + ) + + +class ZebraOutputType(Device): + """Shared by all output types (ttl, lvds, nim, pecl, out)""" + + addr = Cpt(EpicsSignalWithRBV, "") + status = Cpt(EpicsSignalRO, ":STA") + string = Cpt(EpicsSignalRO, ":STR", string=True) + sync = Cpt(EpicsSignal, ":SYNC") + write_output = Cpt(EpicsSignal, ":SET") + + def __init__(self, prefix, *, read_attrs=None, configuration_attrs=None, **kwargs): + if read_attrs is None: + read_attrs = [] + if configuration_attrs is None: + configuration_attrs = _get_configuration_attrs(self) + + super().__init__( + prefix, + read_attrs=read_attrs, + configuration_attrs=configuration_attrs, + **kwargs, + ) + + +class ZebraFrontOutput12(ZebraOutputBase): + ttl = Cpt(ZebraOutputType, "TTL") + lvds = Cpt(ZebraOutputType, "LVDS") + nim = Cpt(ZebraOutputType, "NIM") + + +class ZebraFrontOutput3(ZebraOutputBase): + ttl = Cpt(ZebraOutputType, "TTL") + lvds = Cpt(ZebraOutputType, "LVDS") + open_collector = Cpt(ZebraOutputType, "OC") + + +class ZebraFrontOutput4(ZebraOutputBase): + ttl = Cpt(ZebraOutputType, "TTL") + nim = Cpt(ZebraOutputType, "NIM") + pecl = Cpt(ZebraOutputType, "PECL") + + +class ZebraRearOutput(ZebraOutputBase): + enca = Cpt(ZebraOutputType, "ENCA") + encb = Cpt(ZebraOutputType, "ENCB") + encz = Cpt(ZebraOutputType, "ENCZ") + conn = Cpt(ZebraOutputType, "CONN") + + +class ZebraGateInput(Device): + addr = Cpt(EpicsSignalWithRBV, "") + string = Cpt(EpicsSignalRO, ":STR", string=True) + status = Cpt(EpicsSignalRO, ":STA") + sync = Cpt(EpicsSignal, ":SYNC") + write_input = Cpt(EpicsSignal, ":SET") + + # Input edge index depends on the gate number (these are set in __init__) + edge = FC(EpicsSignal, "{self._zebra_prefix}POLARITY:B{self._input_edge_idx}") + + def __init__( + self, + prefix, + *, + index=None, + parent=None, + configuration_attrs=None, + read_attrs=None, + **kwargs, + ): + if read_attrs is None: + read_attrs = [] + if configuration_attrs is None: + configuration_attrs = _get_configuration_attrs(self) + + gate = parent + zebra = gate.parent + + self.index = index + self._zebra_prefix = zebra.prefix + self._input_edge_idx = gate._input_edge_idx[self.index] + + super().__init__( + prefix, + read_attrs=read_attrs, + configuration_attrs=configuration_attrs, + parent=parent, + **kwargs, + ) + + +class ZebraGate(Device): + input1 = Cpt(ZebraGateInput, "INP1", index=1) + input2 = Cpt(ZebraGateInput, "INP2", index=2) + output = Cpt(EpicsSignal, "OUT") + + def __init__( + self, prefix, *, index=None, read_attrs=None, configuration_attrs=None, **kwargs + ): + self.index = index + self._input_edge_idx = {1: index - 1, 2: 4 + index - 1} + + if read_attrs is None: + read_attrs = [] + if configuration_attrs is None: + configuration_attrs = ["output"] + + super().__init__( + prefix, + configuration_attrs=configuration_attrs, + read_attrs=read_attrs, + **kwargs, + ) + + def set_input_edges(self, edge1, edge2): + set_and_wait(self.input1.edge, int(edge1)) + set_and_wait(self.input2.edge, int(edge2)) + + +class Zebra(ModalBase, Device): + soft_input1 = Cpt(EpicsSignal, "SOFT_IN:B0") + soft_input2 = Cpt(EpicsSignal, "SOFT_IN:B1") + soft_input3 = Cpt(EpicsSignal, "SOFT_IN:B2") + soft_input4 = Cpt(EpicsSignal, "SOFT_IN:B3") + + pulse1 = Cpt(ZebraPulse, "PULSE1_", index=1) + pulse2 = Cpt(ZebraPulse, "PULSE2_", index=2) + pulse3 = Cpt(ZebraPulse, "PULSE3_", index=3) + pulse4 = Cpt(ZebraPulse, "PULSE4_", index=4) + + output1 = Cpt(ZebraFrontOutput12, "OUT1_", index=1) + output2 = Cpt(ZebraFrontOutput12, "OUT2_", index=2) + output3 = Cpt(ZebraFrontOutput3, "OUT3_", index=3) + output4 = Cpt(ZebraFrontOutput4, "OUT4_", index=4) + + output5 = Cpt(ZebraRearOutput, "OUT5_", index=5) + output6 = Cpt(ZebraRearOutput, "OUT6_", index=6) + output7 = Cpt(ZebraRearOutput, "OUT7_", index=7) + output8 = Cpt(ZebraRearOutput, "OUT8_", index=8) + + gate1 = Cpt(ZebraGate, "GATE1_", index=1) + gate2 = Cpt(ZebraGate, "GATE2_", index=2) + gate3 = Cpt(ZebraGate, "GATE3_", index=3) + gate4 = Cpt(ZebraGate, "GATE4_", index=4) + + addresses = ZebraAddresses + + def __init__(self, prefix, *, configuration_attrs=None, read_attrs=None, **kwargs): + if read_attrs is None: + read_attrs = [] + if configuration_attrs is None: + configuration_attrs = _get_configuration_attrs(self) + + super().__init__( + prefix, + configuration_attrs=configuration_attrs, + read_attrs=read_attrs, + **kwargs, + ) + + self.pulse = dict(self._get_indexed_devices(ZebraPulse)) + self.output = dict(self._get_indexed_devices(ZebraOutputBase)) + self.gate = dict(self._get_indexed_devices(ZebraGate)) + + def _get_indexed_devices(self, cls): + for attr in self._sub_devices: + dev = getattr(self, attr) + if isinstance(dev, cls): + yield dev.index, dev + + def mode_internal(self): + super().mode_internal() + # handle the scan type here + + def mode_external(self): + super().mode_external() + # handle the scan type here + + def trigger(self): + # Re-implement this to trigger as desired in bluesky + status = DeviceStatus(self) + status._finished() + return status diff --git a/nslsii/devices.py b/src/nslsii/devices.py similarity index 50% rename from nslsii/devices.py rename to src/nslsii/devices.py index 314e0a5f..54e3f753 100644 --- a/nslsii/devices.py +++ b/src/nslsii/devices.py @@ -1,9 +1,12 @@ -import time +from __future__ import annotations + import datetime -from ophyd import (Device, Component as Cpt, - EpicsSignal, EpicsSignalRO, DeviceStatus) +import time + +from ophyd import Component as Cpt +from ophyd import Device, DeviceStatus, EpicsSignal, EpicsSignalRO -_time_fmtstr = '%Y-%m-%d %H:%M:%S' +_time_fmtstr = "%Y-%m-%d %H:%M:%S" class TwoButtonShutter(Device): @@ -11,30 +14,28 @@ class TwoButtonShutter(Device): # the value coming out of the PV does not match what is shown in CSS RETRY_PERIOD = 0.5 MAX_ATTEMPTS = 10 - open_cmd = Cpt(EpicsSignal, 'Cmd:Opn-Cmd', string=True) - open_val = 'Open' + open_cmd = Cpt(EpicsSignal, "Cmd:Opn-Cmd", string=True) + open_val = "Open" - close_cmd = Cpt(EpicsSignal, 'Cmd:Cls-Cmd', string=True) - close_val = 'Not Open' + close_cmd = Cpt(EpicsSignal, "Cmd:Cls-Cmd", string=True) + close_val = "Not Open" - status = Cpt(EpicsSignalRO, 'Pos-Sts', string=True) - fail_to_close = Cpt(EpicsSignalRO, 'Sts:FailCls-Sts', string=True) - fail_to_open = Cpt(EpicsSignalRO, 'Sts:FailOpn-Sts', string=True) - enabled_status = Cpt(EpicsSignalRO, 'Enbl-Sts', string=True) + status = Cpt(EpicsSignalRO, "Pos-Sts", string=True) + fail_to_close = Cpt(EpicsSignalRO, "Sts:FailCls-Sts", string=True) + fail_to_open = Cpt(EpicsSignalRO, "Sts:FailOpn-Sts", string=True) + enabled_status = Cpt(EpicsSignalRO, "Enbl-Sts", string=True) # user facing commands - open_str = 'Open' - close_str = 'Close' + open_str = "Open" + close_str = "Close" def set(self, val): if self._set_st is not None: - raise RuntimeError(f'trying to set {self.name}' - ' while a set is in progress') + msg = f"trying to set {self.name} while a set is in progress" + raise RuntimeError(msg) - cmd_map = {self.open_str: self.open_cmd, - self.close_str: self.close_cmd} - target_map = {self.open_str: self.open_val, - self.close_str: self.close_val} + cmd_map = {self.open_str: self.open_cmd, self.close_str: self.close_cmd} + target_map = {self.open_str: self.open_val, self.close_str: self.close_val} cmd_sig = cmd_map[val] target_val = target_map[val] @@ -45,16 +46,14 @@ def set(self, val): return st self._set_st = st - print(self.name, val, id(st)) + print(self.name, val, id(st)) # noqa : T201 enums = self.status.enum_strs - def shutter_cb(value, timestamp, **kwargs): - try: + def shutter_cb(value, timestamp, **kwargs): # noqa : ARG001 + import contextlib # noqa : PLC0415 + + with contextlib.suppress(ValueError, TypeError): value = enums[int(value)] - except (ValueError, TypeError): - # we are here because value is a str not int - # just move on - ... if value == target_val: self._set_st = None self.status.clear_sub(shutter_cb) @@ -63,31 +62,29 @@ def shutter_cb(value, timestamp, **kwargs): cmd_enums = cmd_sig.enum_strs count = 0 - def cmd_retry_cb(value, timestamp, **kwargs): + def cmd_retry_cb(value, timestamp, **kwargs): # noqa : ARG001 nonlocal count - try: + import contextlib # noqa : PLC0415 + + with contextlib.suppress(ValueError, TypeError): value = cmd_enums[int(value)] - except (ValueError, TypeError): - # we are here because value is a str not int - # just move on - ... count += 1 if count > self.MAX_ATTEMPTS: cmd_sig.clear_sub(cmd_retry_cb) self._set_st = None self.status.clear_sub(shutter_cb) st._finished(success=False) - if value == 'None': + if value == "None": if not st.done: time.sleep(self.RETRY_PERIOD) cmd_sig.set(1) - ts = datetime.datetime.fromtimestamp(timestamp) \ - .strftime(_time_fmtstr) + ts = datetime.datetime.fromtimestamp(timestamp).strftime( + _time_fmtstr + ) if count > 2: - msg = '** ({}) Had to reactuate shutter while {}ing' - print(msg.format(ts, val if val != 'Close' - else val[:-1])) + msg = "** ({}) Had to reactuate shutter while {}ing" + print(msg.format(ts, val if val != "Close" else val[:-1])) # noqa : T201 else: cmd_sig.clear_sub(cmd_retry_cb) @@ -97,27 +94,29 @@ def cmd_retry_cb(value, timestamp, **kwargs): return st - def stop(self, *, success=False): - import time + def stop(self, *, success=False): # noqa : ARG002 + import time # noqa : PLC0415 + prev_st = self._set_st if prev_st is not None: while not prev_st.done: - time.sleep(.1) - self._was_open = (self.open_val == self.status.get()) - st = self.set('Close') + time.sleep(0.1) + self._was_open = self.open_val == self.status.get() + st = self.set("Close") while not st.done: - time.sleep(.5) + time.sleep(0.5) def resume(self): - import time + import time # noqa : PLC0415 + prev_st = self._set_st if prev_st is not None: while not prev_st.done: - time.sleep(.1) + time.sleep(0.1) if self._was_open: - st = self.set('Open') + st = self.set("Open") while not st.done: - time.sleep(.5) + time.sleep(0.5) def unstage(self): self._was_open = False @@ -127,4 +126,4 @@ def __init__(self, *args, **kwargs): self._was_open = False super().__init__(*args, **kwargs) self._set_st = None - self.read_attrs = ['status'] + self.read_attrs = ["status"] diff --git a/nslsii/epics_utils.py b/src/nslsii/epics_utils.py similarity index 66% rename from nslsii/epics_utils.py rename to src/nslsii/epics_utils.py index 9dc1e363..b2900e9d 100644 --- a/nslsii/epics_utils.py +++ b/src/nslsii/epics_utils.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import argparse import socket from socket import gaierror, herror @@ -29,9 +31,18 @@ def get_ioc_hostname(pvname): def main(): # Used by the `sync-experiment` command - parser = argparse.ArgumentParser(description="Get the IOC hostname based on the provided PV") - parser.add_argument("-p", "--pv", dest="pvname", type=str, help="PV to query information about", required=True) + parser = argparse.ArgumentParser( + description="Get the IOC hostname based on the provided PV" + ) + parser.add_argument( + "-p", + "--pv", + dest="pvname", + type=str, + help="PV to query information about", + required=True, + ) args = parser.parse_args() hostname = get_ioc_hostname(args.pvname) - print(f"IOC hostname for '{args.pvname}' is '{hostname}'.") + print(f"IOC hostname for '{args.pvname}' is '{hostname}'.") # noqa : T201 diff --git a/nslsii/detectors/__init__.py b/src/nslsii/iocs/__init__.py similarity index 100% rename from nslsii/detectors/__init__.py rename to src/nslsii/iocs/__init__.py diff --git a/nslsii/iocs/caproto_saver.py b/src/nslsii/iocs/caproto_saver.py similarity index 81% rename from nslsii/iocs/caproto_saver.py rename to src/nslsii/iocs/caproto_saver.py index bc9de4cb..dd64f9eb 100644 --- a/nslsii/iocs/caproto_saver.py +++ b/src/nslsii/iocs/caproto_saver.py @@ -1,14 +1,14 @@ from __future__ import annotations -from collections import deque -from io import BytesIO import os import re import textwrap import threading import time as ttime import uuid +from collections import deque from enum import Enum +from io import BytesIO from pathlib import Path import numpy as np @@ -16,15 +16,14 @@ from caproto import ChannelType from caproto.ioc_examples.mini_beamline import no_reentry from caproto.server import PVGroup, pvproperty, run, template_arg_parser +from event_model import compose_resource from ophyd import Component as Cpt from ophyd import Device, EpicsSignal, EpicsSignalRO, Kind, Signal from ophyd.status import SubscriptionStatus -from event_model import compose_resource - -from .utils import now, save_hdf5_nd, save_image - from PIL import Image +from .utils import now, save_hdf5_nd + class AcqStatuses(Enum): """Enum class for acquisition statuses.""" @@ -32,6 +31,7 @@ class AcqStatuses(Enum): IDLE = "idle" ACQUIRING = "acquiring" + class DirExistsStatuses(Enum): DOES_NOT_EXIST = "does not exist" PERMISSION_ERROR = "insufficient permissions" @@ -43,10 +43,12 @@ class UIDOptions(Enum): SHORT = "short" FULL = "full" + class OnOffStates(Enum): DISABLE = "disable" ENABLE = "enable" + class CaprotoSaveIOC(PVGroup): """Generic Caproto Save IOC""" @@ -77,21 +79,21 @@ class CaprotoSaveIOC(PVGroup): doc="Record specifying whether or not the target directory exists or not", dtype=ChannelType.ENUM, read_only=True, - enum_strings=[x.value for x in DirExistsStatuses] + enum_strings=[x.value for x in DirExistsStatuses], ) uid_type = pvproperty( value=UIDOptions.NONE.value, doc="UUID to include automatically in file name", dtype=ChannelType.ENUM, - enum_strings=[x.value for x in UIDOptions] + enum_strings=[x.value for x in UIDOptions], ) use_frame_num = pvproperty( - value = OnOffStates.DISABLE.value, - doc = "Enable auto-incrementing frame counter suffix for filenames", + value=OnOffStates.DISABLE.value, + doc="Enable auto-incrementing frame counter suffix for filenames", dtype=ChannelType.ENUM, - enum_strings=[x.value for x in OnOffStates] + enum_strings=[x.value for x in OnOffStates], ) # TODO: check non-negative value in @frame_num.putter. @@ -118,7 +120,7 @@ def __init__(self, *args, update_rate=10.0, **kwargs): queue = pvproperty(value=0, doc="A PV to facilitate threading-based queue") @queue.startup - async def queue(self, instance, async_lib): + async def queue(self, instance, async_lib): # noqa : ARG002 """The startup behavior of the count property to set up threading queues.""" # pylint: disable=unused-argument self._request_queue = async_lib.ThreadsafeQueue(maxsize=1) @@ -135,41 +137,33 @@ async def queue(self, instance, async_lib): ) thread.start() - async def _update_full_file_path(self, write_dir=None, file_name=None, use_frame_num=None, uid_type=None): - - if use_frame_num is None: - use_num = self.use_frame_num.value - else: - use_num = use_frame_num - + async def _update_full_file_path( + self, write_dir=None, file_name=None, use_frame_num=None, uid_type=None + ): + use_num = self.use_frame_num.value if use_frame_num is None else use_frame_num + frame_num_str = "" if use_num == OnOffStates.ENABLE.value: frame_num = self.frame_num.value frame_num_str = f"_{frame_num:06}" - if uid_type is None: - uid_to_use = self.uid_type.value - else: - uid_to_use = uid_type + uid_to_use = self.uid_type.value if uid_type is None else uid_type + uid_str = "" if uid_to_use == UIDOptions.SHORT.value: uid_str = f"_{str(uuid.uuid4())[:8]}" elif uid_to_use == UIDOptions.FULL.value: - uid_str = f"_{str(uuid.uuid4())}" - + uid_str = f"_{uuid.uuid4()!s}" if write_dir is None: local_write_dir = Path(self.write_dir.value) else: local_write_dir = Path(write_dir) - if file_name is None: - full_file_name = self.file_name.value - else: - full_file_name = file_name + full_file_name = self.file_name.value if file_name is None else file_name try: - filename_and_ext = os.path.splitext(full_file_name) + filename_and_ext = Path.splitext(full_file_name) base_filename = filename_and_ext[0] extension = filename_and_ext[1] except IndexError: @@ -177,47 +171,50 @@ async def _update_full_file_path(self, write_dir=None, file_name=None, use_frame base_filename = full_file_name extension = "" - full_file_path = local_write_dir / f"{base_filename}{frame_num_str}{uid_str}{extension}" + full_file_path = ( + local_write_dir / f"{base_filename}{frame_num_str}{uid_str}{extension}" + ) full_file_path = self._sanitizer.sub("_", str(full_file_path)) - print(f"{now()}: {full_file_path = }") + print(f"{now()}: {full_file_path = }") # noqa : T201 await self.full_file_path.write(full_file_path) - - async def _use_frame_num_callback(self, instance, value): + async def _use_frame_num_callback(self, instance, value): # noqa : ARG002 await self._update_full_file_path(use_frame_num=value) return value - async def _uid_type_callback(self, instance, value): + async def _uid_type_callback(self, instance, value): # noqa : ARG002 await self._update_full_file_path(uid_type=value) return value - async def _file_name_callback(self, instance, value): + async def _file_name_callback(self, instance, value): # noqa : ARG002 await self._update_full_file_path(file_name=value) return value - async def _write_dir_callback(self, instance, value): + async def _write_dir_callback(self, instance, value): # noqa : ARG002 """The stage method to perform preparation of a dataset to save the data.""" local_write_dir = Path(value) - if os.path.exists(local_write_dir): + if Path.exists(local_write_dir): if os.access(local_write_dir, os.W_OK): await self.directory_exists.write(DirExistsStatuses.EXISTS.value) await self._update_full_file_path(write_dir=value) else: - await self.directory_exists.write(DirExistsStatuses.PERMISSION_ERROR.value) + await self.directory_exists.write( + DirExistsStatuses.PERMISSION_ERROR.value + ) else: await self.directory_exists.write(DirExistsStatuses.DOES_NOT_EXIST.value) - if self.directory_exists.value == DirExistsStatuses.EXISTS.value: return value - else: - print(f"Directory access error for directory {value}! - {self.directory_exists.value}") - return "" + print( # noqa : T201 + f"Directory access error for directory {value}! - {self.directory_exists.value}" + ) + return "" @write_dir.putter async def write_dir(self, *args, **kwargs): @@ -228,27 +225,24 @@ async def write_dir(self, *args, **kwargs): async def file_name(self, *args, **kwargs): """The file name callback method.""" return await self._file_name_callback(*args, **kwargs) - @uid_type.putter async def uid_type(self, *args, **kwargs): """The file name callback method.""" return await self._uid_type_callback(*args, **kwargs) - @use_frame_num.putter async def use_frame_num(self, *args, **kwargs): """The file name callback method.""" return await self._use_frame_num_callback(*args, **kwargs) - async def _get_current_dataset(self, frame): + async def _get_current_dataset(self, frame): # noqa : ARG002 """The method to return a desired dataset. See https://scikit-image.org/docs/stable/auto_examples/data/plot_3d.html for details about the dataset returned by the base class' method. """ - return np.random.random((480, 640)) - + return np.random.default_rng().random((480, 640)) @acquire.putter @no_reentry @@ -264,13 +258,13 @@ async def acquire(self, instance, value): instance.value in [True, AcqStatuses.ACQUIRING.value] and value == AcqStatuses.ACQUIRING.value ): - print( + print( # noqa : T201 f"The device is already acquiring. Please wait until the '{AcqStatuses.IDLE.value}' status." ) return True - if (self.directory_exists.value != DirExistsStatuses.EXISTS.value): - print("Target write directory does not exist or cannot be written to!") + if self.directory_exists.value != DirExistsStatuses.EXISTS.value: + print("Target write directory does not exist or cannot be written to!") # noqa : T201 return False await self.acquire.write(AcqStatuses.ACQUIRING.value) @@ -295,10 +289,9 @@ async def acquire(self, instance, value): return False - - async def on_startup(self, async_lib): + async def on_startup(self, async_lib): # noqa : ARG002 for key in self.pvdb: - print(key) + print(key) # noqa : T201 await self._write_dir_callback(None, "/tmp") @@ -312,7 +305,7 @@ def saver(request_queue, response_queue): frame_number = received["frame_number"] try: save_hdf5_nd(fname=filename, data=data, mode="x", group_path="enc1") - print( + print( # noqa : T201 f"{now()}: saved {frame_number=} {data.shape} data into:\n {filename}" ) @@ -321,7 +314,7 @@ def saver(request_queue, response_queue): except Exception as exc: # pylint: disable=broad-exception-caught success = False error_message = exc - print( + print( # noqa : T201 f"Cannot save file {filename!r} due to the following exception:\n{exc}" ) @@ -339,12 +332,13 @@ def check_args(parser, split_args): ioc_opts, run_opts = split_args(parsed_args) return ioc_opts, run_opts + class AxisWebcamCaprotoSaver(CaprotoSaveIOC): """""" def __init__(self, *args, camera_host=None, **kwargs): self._camera_host = camera_host - print(f"{camera_host = }") + print(f"{camera_host = }") # noqa : T201 super().__init__(*args, **kwargs) @staticmethod @@ -360,17 +354,16 @@ def check_args(parser, split_args): ioc_opts, run_opts = split_args(parsed_args) - ioc_opts['camera_host'] = parsed_args.camera_host + ioc_opts["camera_host"] = parsed_args.camera_host return ioc_opts, run_opts - - async def _get_current_dataset(self, *args, **kwargs): # pylint: disable=unused-argument + async def _get_current_dataset(self, *args, **kwargs): # noqa : ARG002 # pylint: disable=unused-argument url = f"http://{self._camera_host}/axis-cgi/jpg/image.cgi" resp = requests.get(url, timeout=10) img = Image.open(BytesIO(resp.content)) dataset = np.asarray(img).sum(axis=-1) - print(f"{now()}: {dataset.shape}") + print(f"{now()}: {dataset.shape}") # noqa : T201 return dataset @@ -384,15 +377,15 @@ def saver(request_queue, response_queue): # 'frame_number' is not used for this exporter. try: save_hdf5_nd(fname=filename, data=data, dtype="|u1", mode="a") - #TODO: Change all of these prints to use the caproto logger instead - print(f"{now()}: saved data into: {filename}") + # TODO: Change all of these prints to use the caproto logger instead + print(f"{now()}: saved data into: {filename}") # noqa : T201 success = True error_message = "" except Exception as exc: # pylint: disable=broad-exception-caught success = False error_message = exc - print( + print( # noqa : T201 f"Cannot save file {filename!r} due to the following exception:\n{exc}" ) @@ -408,10 +401,10 @@ class ExternalFileReference(Signal): def describe(self): resource_document_data = super().describe() resource_document_data[self.name].update( - dict( - external="FILESTORE:", - dtype="array", - ) + { + "external": "FILESTORE:", + "dtype": "array", + } ) return resource_document_data @@ -430,7 +423,15 @@ class CaprotoSaverDevice(Device): data = Cpt(ExternalFileReference, kind=Kind.normal) - def __init__(self, *args, md=None, extension='h5', handler_spec="AD_HDF5", root_dir=None, **kwargs): + def __init__( + self, + *args, + md=None, + extension="h5", + handler_spec="AD_HDF5", + root_dir=None, + **kwargs, + ): super().__init__(*args, **kwargs) if root_dir is None: msg = "The 'root_dir' kwarg cannot be None" @@ -449,19 +450,20 @@ def _update_paths(self): @property def root_path_str(self): - beamline = os.getenv("ENDSTATION_ACRONYM", os.getenv("BEAMLINE_ACRONYM", "TST")).lower() - # These three beamlines have a -new suffix in their + beamline = os.getenv( + "ENDSTATION_ACRONYM", os.getenv("BEAMLINE_ACRONYM", "TST") + ).lower() + # These three beamlines have a -new suffix in their if beamline in ["xpd", "fxi", "qas"]: beamline = f"{beamline}-new" - root_path = f"/nsls2/data/{beamline}/proposals/{self._md.get('cycle', '')}/{self._md.get('data_session', '')}/assets/{self.name}" - return root_path - + return f"/nsls2/data/{beamline}/proposals/{self._md.get('cycle', '')}/{self._md.get('data_session', '')}/assets/{self.name}" + @property def shape(self): """Property that contains the shape of the data""" return (1080, 1920) - + @property def dtype_numpy(self): """dtype_str for use in the descriptor""" @@ -498,23 +500,16 @@ def stage(self): # Update caproto IOC parameters: - def describe(self): res = super().describe() - res[self.data.name].update( - {"shape": self.shape, "dtype_str": self.dtype_numpy} - ) + res[self.data.name].update({"shape": self.shape, "dtype_str": self.dtype_numpy}) return res - def trigger(self): - - def done_callback(value, old_value, **kwargs): + def done_callback(value, old_value, **kwargs): # noqa : ARG001 """The callback function used by ophyd's SubscriptionStatus.""" # print(f"{old_value = } -> {value = }") - if old_value == "acquiring" and value == "idle": - return True - return False + return bool(old_value == "acquiring" and value == "idle") status = SubscriptionStatus(self.acquire, run=False, callback=done_callback) @@ -535,8 +530,6 @@ def unstage(self): class TwoDimCaprotoCam(CaprotoSaverDevice): - - def __init__(self, *args, shape=(1080, 1920), dtype_numpy="|u1", **kwargs): super().__init__(*args, **kwargs) self._shape = shape @@ -552,18 +545,24 @@ def dtype_numpy(self): def start_caproto_ioc(cls, parser, split_args): - ioc_options, run_options = cls.check_args(parser, split_args) ioc = cls(**ioc_options) run(ioc.pvdb, startup_hook=ioc.on_startup, **run_options) + def start_axis_ioc(): parser, split_args = template_arg_parser( default_prefix="", desc=textwrap.dedent(AxisWebcamCaprotoSaver.__doc__) ) - parser.add_argument("-c", "--camera-host", help="URL of the axis camera stream", required=True, type=str) + parser.add_argument( + "-c", + "--camera-host", + help="URL of the axis camera stream", + required=True, + type=str, + ) start_caproto_ioc(AxisWebcamCaprotoSaver, parser, split_args) if __name__ == "__main__": - start_axis_ioc() \ No newline at end of file + start_axis_ioc() diff --git a/src/nslsii/iocs/eps_two_state_ioc_sim.py b/src/nslsii/iocs/eps_two_state_ioc_sim.py new file mode 100644 index 00000000..82ab3381 --- /dev/null +++ b/src/nslsii/iocs/eps_two_state_ioc_sim.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python3 # noqa : EXE001 +from __future__ import annotations + +import contextvars +import functools + +from caproto import ChannelType +from caproto.server import PVGroup, pvproperty, run, template_arg_parser + +internal_process = contextvars.ContextVar("internal_process", default=False) + + +def no_reentry(func): + @functools.wraps(func) + async def inner(*args, **kwargs): + if internal_process.get(): + return None + try: + internal_process.set(True) + return await func(*args, **kwargs) + finally: + internal_process.set(False) + + return inner + + +class EPSTwoStateIOC(PVGroup): + """ + Simulates an EPS Two State device including multiple-attempt issue + for two-state device. + + This IOC is used to simulate an EPS Two State Device, for testing + or development purposes. Known EPS two state devices include Photon + shutters, gate valves and Pneumatic actuators at NSLS-II. It simulates + known issues with some of these including: A hardware error (when some + attempts at sending the command fail and we need to 'kick' the device + a few times to get it to actuate), A position status error (it sometimes + does not reach the final state but remains 'between states') and + an enable state change error (there is an 'enable' PV controlled by + the control room that determines if the device can be operated or not). + A parameter (described below) allows each of these error paths to be + tested against. + + Parameters + ---------- + retries : int, optional + Number of attempts required for changing state, + default is 2 + enbl_sts_val: str, optional + Enumerated string that enables the state change, + default is True + hw_error_val: str, optional + Enumerated string that activates the hardware error, + default is False + sts_error_val: str, optional + Enumerated string that activates the Pos-Sts error, + default is False + """ + + def __init__( + self, + retries=2, + enbl_sts_val="True", + hw_error_val="False", + sts_error_val="False", + **kwargs, + ): + super().__init__(**kwargs) + + self._max_retries = retries + self._num_retries = 0 + + self._enbl_sts_val = enbl_sts_val + + self._hw_error_val = hw_error_val + self._sts_error_val = sts_error_val + + # Pos-Sts two-state PV + + _pos_states: ClassVar[list[str]] = ["Open", "Not Open"] # two position states + + pos_sts = pvproperty( + value="Open", + enum_strings=_pos_states, + dtype=ChannelType.ENUM, + read_only=True, + name="Pos-Sts", + ) + + # Opn-Cmd and Cls-Cmd PVs used by client for changing state + + _cmd_states: ClassVar[list[str]] = ["None", "Done"] # two command states + + state1_cmd = pvproperty( + value=_cmd_states[0], + enum_strings=["None", "Open"], + dtype=ChannelType.ENUM, + name="Cmd:Opn-Cmd", + ) + state2_cmd = pvproperty( + value=_cmd_states[0], + enum_strings=["None", "Close"], + dtype=ChannelType.ENUM, + name="Cmd:Cls-Cmd", + ) + + _fail_states: ClassVar[list[str]] = ["False", "True"] + + fail_to_state1 = pvproperty( + value=_fail_states[0], + enum_strings=_fail_states, + dtype=ChannelType.ENUM, + read_only=True, + name="Sts:FailOpn-Sts", + ) + fail_to_state2 = pvproperty( + value=_fail_states[0], + enum_strings=_fail_states, + dtype=ChannelType.ENUM, + read_only=True, + name="Sts:FailCls-Sts", + ) + + # Enbl-Sts PV that enables/disables the state change + + _enbl_states: ClassVar[list[str]] = ["False", "True"] + + enbl_sts = pvproperty( + value="", enum_strings=_enbl_states, dtype=ChannelType.ENUM, name="Enbl-Sts" + ) + + # Hardware error status + + _hw_error_states: ClassVar[list[str]] = ["False", "True"] + + hw_error_sts = pvproperty( + value="", + enum_strings=_hw_error_states, + dtype=ChannelType.ENUM, + name="HwError-Sts", + ) + + # Pos-Sts error status + + from typing import ClassVar # noqa : PLC0415 + + _sts_error_states: ClassVar[list[str]] = ["False", "True"] + + sts_error_sts = pvproperty( + value="", + enum_strings=_sts_error_states, + dtype=ChannelType.ENUM, + name="StsError-Sts", + ) + + # PV Startup/Putter Methods + + @enbl_sts.startup + async def enbl_sts(self, instance, async_lib): # noqa : ARG002 + await instance.write(value=self._enbl_sts_val) + + @hw_error_sts.startup + async def hw_error_sts(self, instance, async_lib): # noqa : ARG002 + await instance.write(value=self._hw_error_val) + + @sts_error_sts.startup + async def sts_error_sts(self, instance, async_lib): # noqa : ARG002 + await instance.write(value=self._sts_error_val) + + @state1_cmd.startup + async def state1_cmd(self, instance, async_lib): + instance.async_lib = async_lib + + @state1_cmd.putter + @no_reentry + async def state1_cmd(self, instance, value): + if value == "Open": + await self.state1_cmd.write(value) + await instance.async_lib.library.sleep(1) + await self.pos_sts.write("Open") + return "None" + + @state2_cmd.startup + async def state2_cmd(self, instance, async_lib): + instance.async_lib = async_lib + + @state2_cmd.putter + @no_reentry + async def state2_cmd(self, instance, value): + if value == "Close": + await self.state2_cmd.write(value) + await instance.async_lib.library.sleep(1) + await self.pos_sts.write("Not Open") + return "None" + + @enbl_sts.putter + async def enbl_sts(self, instance, value): # noqa : ARG002 + self._enbl_sts_val = value + return value + + @hw_error_sts.putter + async def hw_error_sts(self, instance, value): # noqa : ARG002 + self._hw_error_val = value + return value + + @sts_error_sts.putter + async def sts_error_sts(self, instance, value): # noqa : ARG002 + self._sts_error_val = value + return value + + # Internal Methods + + async def _state_cmd_put(self, instance, value, state_val, fail_to_state): # noqa : ARG002 + if value == self._cmd_states[0]: # if None -> do nothing + return self._cmd_states[0] + if self._pos_sts_val == state_val: # if in state -> do nothing + return self._cmd_states[0] + if self._enbl_sts_val == "False": # if changes not enabled -> fail + await fail_to_state.write(value="True") + return self._cmd_states[0] + self._num_retries += 1 + if self._num_retries < self._max_retries: + return self._cmd_states[0] + self._num_retries = 0 + if self._hw_error_val == "True": # if hw error -> fail + await fail_to_state.write(value="True") + return self._cmd_states[1] + await fail_to_state.write(value="False") + if self._sts_error_val == "True": # if sts error -> don't change sts + return self._cmd_states[1] + await self.pos_sts.write(value=state_val) + self._pos_sts_val = state_val + return self._cmd_states[0] + + +if __name__ == "__main__": + parser, split_args = template_arg_parser( + default_prefix="eps2state:", desc="EPS Two State IOC." + ) + + retries_help = "Number of attempts required for changing state" + enable_help = "State change is enabled" + hwerror_help = "HW error is activated" + stserror_help = "Pos-Sts error is activated" + + parser.add_argument( + "--retries", help=retries_help, required=False, default=2, type=int + ) + parser.add_argument( + "--enable", help=enable_help, required=False, default="True", type=str + ) + parser.add_argument( + "--hwerror", help=hwerror_help, required=False, default="False", type=str + ) + parser.add_argument( + "--stserror", help=stserror_help, required=False, default="False", type=str + ) + + args = parser.parse_args() + ioc_options, run_options = split_args(args) + + ioc = EPSTwoStateIOC( + retries=args.retries, + enbl_sts_val=args.enable, + hw_error_val=args.hwerror, + sts_error_val=args.stserror, + **ioc_options, + ) + + run(ioc.pvdb, **run_options) diff --git a/nslsii/iocs/tests/test_epstwostate_ioc.py b/src/nslsii/iocs/tests/test_epstwostate_ioc.py similarity index 53% rename from nslsii/iocs/tests/test_epstwostate_ioc.py rename to src/nslsii/iocs/tests/test_epstwostate_ioc.py index 9fb2c273..ce6491f4 100644 --- a/nslsii/iocs/tests/test_epstwostate_ioc.py +++ b/src/nslsii/iocs/tests/test_epstwostate_ioc.py @@ -1,139 +1,139 @@ +from __future__ import annotations + import os import subprocess import sys import time from ophyd import Device, EpicsSignal, EpicsSignalRO -from ophyd.device import (Component as Cpt, - FormattedComponent as FmtCpt) +from ophyd.device import Component as Cpt +from ophyd.device import FormattedComponent as FmtCpt class EPSTwoStateDevice(Device): - def __init__(self, *, prefix, name, **kwargs): super().__init__(prefix=prefix, name=name, **kwargs) - status = Cpt(EpicsSignalRO, 'Pos-Sts', string=True) + status = Cpt(EpicsSignalRO, "Pos-Sts", string=True) - opn_cmd = FmtCpt(EpicsSignal, - '{self.prefix}Cmd:Opn-Cmd', - string=True, kind='omitted') - cls_cmd = FmtCpt(EpicsSignal, - '{self.prefix}Cmd:Cls-Cmd', - string=True, kind='omitted') + opn_cmd = FmtCpt( + EpicsSignal, "{self.prefix}Cmd:Opn-Cmd", string=True, kind="omitted" + ) + cls_cmd = FmtCpt( + EpicsSignal, "{self.prefix}Cmd:Cls-Cmd", string=True, kind="omitted" + ) - fail_to_opn = Cpt(EpicsSignalRO, 'Sts:FailOpn-Sts', - string=True) + fail_to_opn = Cpt(EpicsSignalRO, "Sts:FailOpn-Sts", string=True) - fail_to_cls = Cpt(EpicsSignalRO, 'Sts:FailCls-Sts', - string=True) + fail_to_cls = Cpt(EpicsSignalRO, "Sts:FailCls-Sts", string=True) - enbl_sts = Cpt(EpicsSignal, 'Enbl-Sts', string=True, - kind='omitted') + enbl_sts = Cpt(EpicsSignal, "Enbl-Sts", string=True, kind="omitted") - hw_error_sts = Cpt(EpicsSignal, 'HwError-Sts', string=True, - kind='omitted') + hw_error_sts = Cpt(EpicsSignal, "HwError-Sts", string=True, kind="omitted") - sts_error_sts = Cpt(EpicsSignal, 'StsError-Sts', string=True, - kind='omitted') + sts_error_sts = Cpt(EpicsSignal, "StsError-Sts", string=True, kind="omitted") def test_epstwostate_ioc(): - stdout = subprocess.PIPE stdin = None - ioc_process = subprocess.Popen([sys.executable, '-m', - 'caproto.tests.example_runner', - 'nslsii.iocs.eps_two_state_ioc_sim'], - stdout=stdout, stdin=stdin, - env=os.environ) + ioc_process = subprocess.Popen( + [ + sys.executable, + "-m", + "caproto.tests.example_runner", + "nslsii.iocs.eps_two_state_ioc_sim", + ], + stdout=stdout, + stdin=stdin, + env=os.environ, + ) - print('nslsii.iocs.epc_two_state_ioc_sim is now running') + print("nslsii.iocs.epc_two_state_ioc_sim is now running") # noqa : T201 time.sleep(5) # Wrap the rest in a try-except to ensure the ioc is killed before exiting try: - - eps = EPSTwoStateDevice(prefix='eps2state:', name='eps') + eps = EPSTwoStateDevice(prefix="eps2state:", name="eps") # 1. check the ioc-device connection and initial values sts_val = eps.status.get() - assert sts_val == 'Open' + assert sts_val == "Open" opn_cmd_val = eps.opn_cmd.get() - assert opn_cmd_val == 'None' + assert opn_cmd_val == "None" cls_cmd_val = eps.cls_cmd.get() - assert cls_cmd_val == 'None' + assert cls_cmd_val == "None" fail_to_opn_val = eps.fail_to_opn.get() - assert fail_to_opn_val == 'False' + assert fail_to_opn_val == "False" fail_to_cls_val = eps.fail_to_cls.get() - assert fail_to_cls_val == 'False' + assert fail_to_cls_val == "False" enbl_sts_val = eps.enbl_sts.get() - assert enbl_sts_val == 'True' + assert enbl_sts_val == "True" hw_error_val = eps.hw_error_sts.get() - assert hw_error_val == 'False' + assert hw_error_val == "False" sts_error_val = eps.sts_error_sts.get() - assert sts_error_val == 'False' + assert sts_error_val == "False" # 2. try to close with one attempt eps.cls_cmd.put(1) cls_cmd_val = eps.cls_cmd.get() - assert cls_cmd_val == 'None' + assert cls_cmd_val == "Close" fail_to_cls_val = eps.fail_to_cls.get() - assert fail_to_cls_val == 'False' + assert fail_to_cls_val == "False" sts_val = eps.status.get() - assert sts_val == 'Open' + assert sts_val == "Open" # 3. try to close with second attempt eps.cls_cmd.put(1) cls_cmd_val = eps.cls_cmd.get() - assert cls_cmd_val == 'None' + assert cls_cmd_val == "Close" fail_to_cls_val = eps.fail_to_cls.get() - assert fail_to_cls_val == 'False' + assert fail_to_cls_val == "False" sts_val = eps.status.get() - assert sts_val == 'Closed' + assert sts_val == "Closed" # 4. try to open with one attempt eps.opn_cmd.put(1) opn_cmd_val = eps.opn_cmd.get() - assert opn_cmd_val == 'None' + assert opn_cmd_val == "None" fail_to_opn_val = eps.fail_to_opn.get() - assert fail_to_opn_val == 'False' + assert fail_to_opn_val == "False" sts_val = eps.status.get() - assert sts_val == 'Closed' + assert sts_val == "Closed" # 5. try to open with second attempt eps.opn_cmd.put(1) opn_cmd_val = eps.opn_cmd.get() - assert opn_cmd_val == 'None' + assert opn_cmd_val == "None" fail_to_opn_val = eps.fail_to_opn.get() - assert fail_to_opn_val == 'False' + assert fail_to_opn_val == "False" sts_val = eps.status.get() - assert sts_val == 'Open' + assert sts_val == "Open" # 6. disable changes and try to close @@ -143,13 +143,13 @@ def test_epstwostate_ioc(): eps.cls_cmd.put(1) cls_cmd_val = eps.cls_cmd.get() - assert cls_cmd_val == 'None' + assert cls_cmd_val == "Close" fail_to_cls_val = eps.fail_to_cls.get() - assert fail_to_cls_val == 'True' + assert fail_to_cls_val == "True" sts_val = eps.status.get() - assert sts_val == 'Open' + assert sts_val == "Open" # 7. enable changes, enable the hw error, and try to close @@ -160,13 +160,13 @@ def test_epstwostate_ioc(): eps.cls_cmd.put(1) cls_cmd_val = eps.cls_cmd.get() - assert cls_cmd_val == 'Done' + assert cls_cmd_val == "Done" fail_to_cls_val = eps.fail_to_cls.get() - assert fail_to_cls_val == 'True' + assert fail_to_cls_val == "True" sts_val = eps.status.get() - assert sts_val == 'Open' + assert sts_val == "Open" # 8. disable the hw error, enable the sts error, and try to close @@ -177,13 +177,13 @@ def test_epstwostate_ioc(): eps.cls_cmd.put(1) cls_cmd_val = eps.cls_cmd.get() - assert cls_cmd_val == 'Done' + assert cls_cmd_val == "Done" fail_to_cls_val = eps.fail_to_cls.get() - assert fail_to_cls_val == 'False' + assert fail_to_cls_val == "False" sts_val = eps.status.get() - assert sts_val == 'Open' + assert sts_val == "Open" # 9. disable the sts error and try to close @@ -193,13 +193,13 @@ def test_epstwostate_ioc(): eps.cls_cmd.put(1) cls_cmd_val = eps.cls_cmd.get() - assert cls_cmd_val == 'None' + assert cls_cmd_val == "None" fail_to_cls_val = eps.fail_to_cls.get() - assert fail_to_cls_val == 'False' + assert fail_to_cls_val == "False" sts_val = eps.status.get() - assert sts_val == 'Closed' + assert sts_val == "Closed" finally: # Ensure that for any exception the ioc sub-process is terminated diff --git a/nslsii/iocs/thermo_sim.py b/src/nslsii/iocs/thermo_sim.py similarity index 52% rename from nslsii/iocs/thermo_sim.py rename to src/nslsii/iocs/thermo_sim.py index 14acee5f..68d0b159 100644 --- a/nslsii/iocs/thermo_sim.py +++ b/src/nslsii/iocs/thermo_sim.py @@ -1,9 +1,12 @@ -#!/usr/bin/env python3 -from caproto.server import pvproperty, PVGroup, ioc_arg_parser, run -import numpy as np +#!/usr/bin/env python3 # noqa : EXE001 +from __future__ import annotations + import time from textwrap import dedent +import numpy as np +from caproto.server import PVGroup, ioc_arg_parser, pvproperty, run + class Thermo(PVGroup): """ @@ -32,40 +35,43 @@ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._T0 = time.monotonic() - readback = pvproperty(value=0, dtype=float, read_only=True, - name='T-RB', - mock_record='ai') + readback = pvproperty( + value=0, dtype=float, read_only=True, name="T-RB", mock_record="ai" + ) - setpoint = pvproperty(value=100, dtype=float, name='T-SP') + setpoint = pvproperty(value=100, dtype=float, name="T-SP") K = pvproperty(value=10, dtype=float) omega = pvproperty(value=np.pi, dtype=float) Tvar = pvproperty(value=10, dtype=float) - @readback.scan(period=.1, use_scan_field=True) - async def readback(self, instance, async_lib): - - def t_rbv(T0, setpoint, K, omega, Tvar,): + @readback.scan(period=0.1, use_scan_field=True) + async def readback(self, instance, async_lib): # noqa : ARG002 + def t_rbv( + T0, # noqa : ARG001 + setpoint, + K, + omega, + Tvar, + ): t = time.monotonic() - return ((Tvar * - np.exp(-(t - self._T0) / K) * - np.sin(omega * t)) + - setpoint) + return (Tvar * np.exp(-(t - self._T0) / K) * np.sin(omega * t)) + setpoint - T = t_rbv(T0=self._T0, - **{k: getattr(self, k).value - for k in ['setpoint', 'K', 'omega', 'Tvar']}) + T = t_rbv( + T0=self._T0, + **{k: getattr(self, k).value for k in ["setpoint", "K", "omega", "Tvar"]}, + ) await instance.write(value=T) @setpoint.putter - async def setpoint(self, instance, value): + async def setpoint(self, instance, value): # noqa : ARG002 self._T0 = time.monotonic() return value -if __name__ == '__main__': +if __name__ == "__main__": ioc_options, run_options = ioc_arg_parser( - default_prefix='thermo:', - desc=dedent(Thermo.__doc__)) + default_prefix="thermo:", desc=dedent(Thermo.__doc__) + ) ioc = Thermo(**ioc_options) run(ioc.pvdb, **run_options) diff --git a/nslsii/iocs/utils.py b/src/nslsii/iocs/utils.py similarity index 95% rename from nslsii/iocs/utils.py rename to src/nslsii/iocs/utils.py index a1ff9c20..5834ed8f 100644 --- a/nslsii/iocs/utils.py +++ b/src/nslsii/iocs/utils.py @@ -15,7 +15,7 @@ def now(as_object=False): return _now.isoformat() -def save_image(fname, data, file_format="jpeg", mode="x"): # pylint: disable=unused-argument +def save_image(fname, data, file_format="jpeg", mode="x"): # noqa : ARG001 # pylint: disable=unused-argument """The function to export the image data (e.g., to a JPEG file.""" data.save(fname, file_format=file_format) @@ -86,4 +86,4 @@ def save_hdf5_nd( dataset.resize((frame_num + 1, *frame_shape)) dataset[frame_num, ...] = data - dataset.flush() \ No newline at end of file + dataset.flush() diff --git a/nslsii/kafka_utils.py b/src/nslsii/kafka_utils.py similarity index 87% rename from nslsii/kafka_utils.py rename to src/nslsii/kafka_utils.py index 01bac5fc..4bd3405c 100644 --- a/nslsii/kafka_utils.py +++ b/src/nslsii/kafka_utils.py @@ -1,5 +1,6 @@ -import logging +from __future__ import annotations +import logging from collections import namedtuple from pathlib import Path @@ -27,11 +28,11 @@ def _read_bluesky_kafka_config_file(config_file_path): ------- dict of configuration details """ - import yaml + import yaml # noqa : PLC0415 # read the Kafka Producer configuration details if Path(config_file_path).exists(): - with open(config_file_path) as f: + with Path.open(config_file_path) as f: bluesky_kafka_config = yaml.safe_load(f) else: raise FileNotFoundError(config_file_path) @@ -49,9 +50,8 @@ def _read_bluesky_kafka_config_file(config_file_path): ] if missing_required_sections: - raise Exception( - f"Bluesky Kafka configuration file '{config_file_path}' is missing required section(s) `{missing_required_sections}`" - ) + msg = f"Bluesky Kafka configuration file '{config_file_path}' is missing required section(s) `{missing_required_sections}`" + raise Exception(msg) return bluesky_kafka_config @@ -97,16 +97,16 @@ def _subscribe_kafka_publisher( subscription token corresponding to the RunRouter subscribed to the RunEngine by this function """ - from bluesky_kafka import Publisher - from bluesky_kafka.utils import list_topics - from event_model import RunRouter + from bluesky_kafka import Publisher # noqa : PLC0415 + from bluesky_kafka.utils import list_topics # noqa : PLC0415 + from event_model import RunRouter # noqa : PLC0415 topic = f"{beamline_name.lower()}.bluesky.runengine.documents" if _publisher_factory is None: _publisher_factory = Publisher - def kafka_publisher_factory(start_name, start_doc): + def kafka_publisher_factory(start_name, start_doc): # noqa: ARG001 # create a Kafka Publisher for a single run # in response to a start document @@ -159,16 +159,13 @@ def publish_or_abort_run(name_, doc_): logging.getLogger("nslsii").info( "RE will publish documents to Kafka topic '%s'", topic ) - - subscribe_kafka_publisher_details = _SubscribeKafkaPublisherDetails( + return _SubscribeKafkaPublisherDetails( beamline_topic=topic, bootstrap_servers=bootstrap_servers, producer_config=producer_config, re_subscribe_token=runrouter_token, ) - return subscribe_kafka_publisher_details - """ A namedtuple for holding details of the publisher created by @@ -222,12 +219,13 @@ def _subscribe_kafka_queue_thread_publisher( un-subscribe the function from the RunEngine, in case someone ever wants to do that. """ - from bluesky_kafka import BlueskyKafkaException - from bluesky_kafka.tools.queue_thread import build_kafka_publisher_queue_and_thread + from bluesky_kafka.tools.queue_thread import ( # noqa : PLC0415 + build_kafka_publisher_queue_and_thread, + ) nslsii_logger = logging.getLogger("nslsii") beamline_runengine_topic = None - kafka_publisher_token = None + kafka_publisher_token = None # noqa : F841 publisher_thread_stop_event = None kafka_publisher_re_token = None publisher_queue_thread_details = None @@ -245,7 +243,7 @@ def _subscribe_kafka_queue_thread_publisher( publisher_queue_timeout=publisher_queue_timeout, ) - publisher_thread_stop_event = ( + publisher_thread_stop_event = ( # noqa : F841 publisher_queue_thread_details.publisher_thread_stop_event ) @@ -269,14 +267,10 @@ def _subscribe_kafka_queue_thread_publisher( beamline_runengine_topic, ) - subscribe_kafka_queue_thread_publisher_details = ( - _SubscribeKafkaQueueThreadPublisherDetails( - beamline_topic=beamline_runengine_topic, - bootstrap_servers=bootstrap_servers, - producer_config=producer_config, - publisher_queue_thread_details=publisher_queue_thread_details, - re_subscribe_token=kafka_publisher_re_token, - ) + return _SubscribeKafkaQueueThreadPublisherDetails( + beamline_topic=beamline_runengine_topic, + bootstrap_servers=bootstrap_servers, + producer_config=producer_config, + publisher_queue_thread_details=publisher_queue_thread_details, + re_subscribe_token=kafka_publisher_re_token, ) - - return subscribe_kafka_queue_thread_publisher_details diff --git a/nslsii/md_dict.py b/src/nslsii/md_dict.py similarity index 95% rename from nslsii/md_dict.py rename to src/nslsii/md_dict.py index fd5ed4ff..3f914e3c 100644 --- a/nslsii/md_dict.py +++ b/src/nslsii/md_dict.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import logging import re from collections import ChainMap, UserDict @@ -7,7 +9,6 @@ import msgpack_numpy import redis - msgpack_numpy.patch() redis_dict_log = logging.getLogger("nslsii.md_dict.RunEngineRedisDict") @@ -96,14 +97,14 @@ def __init__( ) if packed_local_md is None: redis_dict_log.info("no local metadata found in Redis") - self._local_md = dict() + self._local_md = {} self._set_local_metadata_on_server() else: redis_dict_log.info("unpacking local metadata from Redis") self._local_md = self._get_local_metadata_from_server() redis_dict_log.debug("unpacked local metadata:\n%s", self._local_md) - self._global_md = dict() + self._global_md = {} for global_key in self._global_keys: global_value = self._redis_global_client.get(global_key) if global_value is None: @@ -154,10 +155,11 @@ def __setitem__(self, key, value): # everything is good pass else: - raise ValueError( + msg = ( f"expected value for key '{key}' to have type '{expected_value_type}'" - f"but '{value}' has type '{type(value)}'" + f" but '{value}' has type '{type(value)}'" ) + raise ValueError(msg) # update the global key-value pair explicitly in self._global_md # because it can not be updated through the self.data ChainMap # since self._global_md is not the first dictionary in that ChainMap @@ -180,10 +182,10 @@ def __setitem__(self, key, value): def __delitem__(self, key): if key in self._global_keys: - raise KeyError(f"deleting key {key} is not allowed") - else: - del self._local_md[key] - self._set_local_metadata_on_server() + msg = f"deleting key {key} is not allowed" + raise KeyError(msg) + del self._local_md[key] + self._set_local_metadata_on_server() # tell everyone a (local) key-value has been changed self._publish_metadata_update_message(key) @@ -227,9 +229,8 @@ def _parse_message_data(klass, message): message_data_match = klass._message_data_pattern.match(decoded_message_data) if message_data_match is None: - raise ValueError( - f"message[data]=`{decoded_message_data}` could not be parsed" - ) + msg = f"message[data]=`{decoded_message_data}` could not be parsed" + raise ValueError(msg) return message_data_match.group("key"), message_data_match.group("uuid") def _handle_update_message(self, message): diff --git a/nslsii/iocs/__init__.py b/src/nslsii/motors/__init__.py similarity index 100% rename from nslsii/iocs/__init__.py rename to src/nslsii/motors/__init__.py diff --git a/nslsii/motors/delta_tau.py b/src/nslsii/motors/delta_tau.py similarity index 93% rename from nslsii/motors/delta_tau.py rename to src/nslsii/motors/delta_tau.py index b7e477c5..f1b5bb27 100644 --- a/nslsii/motors/delta_tau.py +++ b/src/nslsii/motors/delta_tau.py @@ -2,6 +2,8 @@ Ophyd devices and signals for Delta Tau devices, such as Programmable Multi-Axis Controller (PMAC-PC) """ +from __future__ import annotations + import logging from ophyd import Component as Cpt @@ -33,7 +35,8 @@ def set(self, value, *args, **kwargs): """ if value != 1: logging.getLogger(__name__).warning( - "The value of the PMACKiller should only ever be set to 1. " "Changing the setpoint to 1 now." + "The value of the PMACKiller should only ever be set to 1. " + "Changing the setpoint to 1 now." ) value = 1 self.kill.set(value, *args, **kwargs) diff --git a/nslsii/ophyd_async/__init__.py b/src/nslsii/ophyd_async/__init__.py similarity index 66% rename from nslsii/ophyd_async/__init__.py rename to src/nslsii/ophyd_async/__init__.py index 86505b03..5648e66f 100644 --- a/nslsii/ophyd_async/__init__.py +++ b/src/nslsii/ophyd_async/__init__.py @@ -1,19 +1,20 @@ +from __future__ import annotations + from .providers import ( - YMDGranularity, - ProposalNumScanNumPathProvider, - ProposalNumYMDPathProvider, - ShortUUIDFilenameProvider, AcqModeFilenameProvider, DeviceNameFilenameProvider, NSLS2PathProvider, + ProposalNumScanNumPathProvider, # noqa : F401 + ProposalNumYMDPathProvider, + ShortUUIDFilenameProvider, + YMDGranularity, # noqa : F401 ) __all__ = [ - "YMDGranularity" - "ProposalNumScanNumPathProvider", - "ProposalNumYMDPathProvider", - "ShortUUIDFilenameProvider", "AcqModeFilenameProvider", "DeviceNameFilenameProvider", "NSLS2PathProvider", + "ProposalNumYMDPathProvider", + "ShortUUIDFilenameProvider", + "YMDGranularityProposalNumScanNumPathProvider", ] diff --git a/nslsii/ophyd_async/devices/__init__.py b/src/nslsii/ophyd_async/devices/__init__.py similarity index 88% rename from nslsii/ophyd_async/devices/__init__.py rename to src/nslsii/ophyd_async/devices/__init__.py index 06f47fda..bea8d2fb 100644 --- a/nslsii/ophyd_async/devices/__init__.py +++ b/src/nslsii/ophyd_async/devices/__init__.py @@ -1,17 +1,19 @@ +from __future__ import annotations + from rbd9103 import ( RBD9103, - RBD9103Range, + RBD9103Filter, RBD9103Input, - RBD9103SamplingMode, RBD9103InRangeState, - RBD9103Filter, + RBD9103Range, + RBD9103SamplingMode, ) __all__ = [ "RBD9103", - "RBD9103Range", + "RBD9103Filter", + "RBD9103InRangeState", "RBD9103Input", + "RBD9103Range", "RBD9103SamplingMode", - "RBD9103InRangeState", - "RBD9103Filter", ] diff --git a/nslsii/ophyd_async/devices/rbd9103.py b/src/nslsii/ophyd_async/devices/rbd9103.py similarity index 93% rename from nslsii/ophyd_async/devices/rbd9103.py rename to src/nslsii/ophyd_async/devices/rbd9103.py index f729fbfd..46ad818b 100644 --- a/nslsii/ophyd_async/devices/rbd9103.py +++ b/src/nslsii/ophyd_async/devices/rbd9103.py @@ -1,13 +1,16 @@ +from __future__ import annotations + +from typing import Annotated as A + from ophyd_async.core import ( - StandardReadable, + AsyncStatus, SignalR, SignalRW, + StandardReadable, StrictEnum, - AsyncStatus, ) from ophyd_async.core import StandardReadableFormat as Format -from ophyd_async.epics.signal import PvSuffix, EpicsDevice -from typing import Annotated as A +from ophyd_async.epics.signal import EpicsDevice, PvSuffix class RBD9103Range(StrictEnum): @@ -95,9 +98,8 @@ async def stage(self): set_sampling_rate < self._min_sampling_rate or set_sampling_rate > self._max_sampling_rate ): - raise ValueError( - f"Sampling rate must be between {self._min_sampling_rate} and {self._max_sampling_rate} ms" - ) + msg = f"Sampling rate must be between {self._min_sampling_rate} and {self._max_sampling_rate} ms" + raise ValueError(msg) sampling = await self.sample.get_value() if sampling: diff --git a/nslsii/ophyd_async/providers.py b/src/nslsii/ophyd_async/providers.py similarity index 81% rename from nslsii/ophyd_async/providers.py rename to src/nslsii/ophyd_async/providers.py index 0ade5d61..78dbab29 100644 --- a/nslsii/ophyd_async/providers.py +++ b/src/nslsii/ophyd_async/providers.py @@ -1,14 +1,16 @@ +from __future__ import annotations + +import os from datetime import date from enum import Enum from pathlib import Path -from typing import Optional + +import shortuuid from ophyd_async.core import ( FilenameProvider, - PathProvider, PathInfo, + PathProvider, ) -import os -import shortuuid class YMDGranularity(int, Enum): @@ -46,11 +48,10 @@ def get_beamline_proposals_dir(self): beamline_tla = os.getenv( "ENDSTATION_ACRONYM", os.getenv("BEAMLINE_ACRONYM", "") ).lower() - beamline_proposals_dir = Path(f"/nsls2/data/{beamline_tla}/proposals/") - return beamline_proposals_dir + return Path(f"/nsls2/data/{beamline_tla}/proposals/") - def generate_directory_path(self, device_name: Optional[str] = None): + def generate_directory_path(self, device_name: str | None = None): """Helper function that generates ymd path structure""" current_date_template = "" @@ -66,12 +67,9 @@ def generate_directory_path(self, device_name: Optional[str] = None): if device_name is None: ymd_dir_path = current_date else: - ymd_dir_path = os.path.join( - device_name, - current_date, - ) + ymd_dir_path = Path(device_name) / current_date - directory_path = ( + return ( self._beamline_proposals_dir / self._metadata_dict["cycle"] / self._metadata_dict["data_session"] @@ -79,9 +77,7 @@ def generate_directory_path(self, device_name: Optional[str] = None): / ymd_dir_path ) - return directory_path - - def __call__(self, device_name: str = None) -> PathInfo: + def __call__(self, device_name: str | None = None) -> PathInfo: directory_path = self.generate_directory_path(device_name=device_name) return PathInfo( @@ -110,7 +106,7 @@ def __init__( **kwargs, ) - def __call__(self, device_name: Optional[str] = None) -> PathInfo: + def __call__(self, device_name: str | None = None) -> PathInfo: directory_path = self.generate_directory_path(device_name=device_name) final_dir_path = ( @@ -132,12 +128,11 @@ def __init__(self, separator="_", **kwargs): self._separator = separator super().__init__(**kwargs) - def __call__(self, device_name: Optional[str] = None) -> str: + def __call__(self, device_name: str | None = None) -> str: sid = shortuuid.uuid() if device_name is not None: return f"{device_name}{self._separator}{sid}" - else: - return sid + return sid class AcqModeFilenameProvider(ShortUUIDFilenameProvider): @@ -145,7 +140,8 @@ def __init__(self, initial_mode, **kwargs): if not isinstance(initial_mode, Enum) or not isinstance( initial_mode.value, str ): - raise TypeError("Initial acquisition mode type must be a string enum!") + msg = "Initial acquisition mode type must be a string enum!" + raise TypeError(msg) self._mode = initial_mode self._mode_type = type(initial_mode) @@ -153,24 +149,21 @@ def __init__(self, initial_mode, **kwargs): def switch_mode(self, new_mode): if not isinstance(new_mode, self._mode_type): - raise RuntimeError( - f"{new_mode} is not a valid option for {self._mode_type}!" - ) - else: - self._mode = new_mode + msg = f"{new_mode} is not a valid option for {self._mode_type}!" + raise RuntimeError(msg) + self._mode = new_mode - def __call__(self, **kwargs): + def __call__(self, **kwargs): # noqa : ARG002 return super().__call__(device_name=self._mode.value) class DeviceNameFilenameProvider(FilenameProvider): """Filename provider that uses device name as filename""" - def __call__(self, device_name: Optional[str] = None) -> str: + def __call__(self, device_name: str | None = None) -> str: if device_name is None: - raise RuntimeError( - f"Device name must be passed in when calling {type(self).__name__}!" - ) + msg = f"Device name must be passed in when calling {type(self).__name__}!" + raise RuntimeError(msg) return device_name diff --git a/nslsii/motors/__init__.py b/src/nslsii/plans/__init__.py similarity index 100% rename from nslsii/motors/__init__.py rename to src/nslsii/plans/__init__.py diff --git a/nslsii/plans/maia.py b/src/nslsii/plans/maia.py similarity index 88% rename from nslsii/plans/maia.py rename to src/nslsii/plans/maia.py index 1b349ad4..86b3237a 100644 --- a/nslsii/plans/maia.py +++ b/src/nslsii/plans/maia.py @@ -1,8 +1,9 @@ -import numpy as np +from __future__ import annotations -import bluesky.plans as bp import bluesky.plan_stubs as bps +import bluesky.plans as bp import bluesky.preprocessors as bpp +import numpy as np sample_md = {"sample": {"name": "Ni mesh", "owner": "stolen"}} @@ -70,17 +71,17 @@ def fly_maia( "shape": [ynum, xnum], "motors": [m.name for m in [hf_stage.y, hf_stage.x]], "num_steps": xnum * ynum, - "plan_args": dict( - ystart=ystart, - ystop=ystop, - ynum=ynum, - xstart=xstart, - xstop=xstop, - xnum=xnum, - dwell=dwell, - group=repr(group), - md=md, - ), + "plan_args": { + "ystart": ystart, + "ystop": ystop, + "ynum": ynum, + "xstart": xstart, + "xstop": xstop, + "xnum": xnum, + "dwell": dwell, + "group": repr(group), + "md": md, + }, "extents": [[ystart, ystop], [xstart, xstop]], "snaking": [False, True], "plan_name": "fly_maia", @@ -92,13 +93,13 @@ def fly_maia( sample_md = md.get("sample", {}) for k in ["info", "name", "owner", "serial", "type"]: v = sample_md.get(k, "") - sig = getattr(maia, "meta_val_sample_{}_sp.value".format(k)) + sig = getattr(maia, f"meta_val_sample_{k}_sp.value") yield from bp.mv(sig, str(v)) scan_md = md.get("scan", {}) for k in ["region", "info", "seq_num", "seq_total"]: v = scan_md.get(k, "") - sig = getattr(maia, "meta_val_scan_{}_sp.value".format(k)) + sig = getattr(maia, f"meta_val_scan_{k}_sp.value") yield from bp.mv(sig, str(v)) if group is not None: @@ -114,7 +115,7 @@ def fly_maia( x_pitch = abs(xstop - xstart) / (xnum - 1) y_pitch = abs(ystop - ystart) / (ynum - 1) - # TODO compute this based on someting + # TODO compute this based on something spd_x = x_pitch / dwell yield from bp.mv(hf_stage.x, xstart, hf_stage.y, ystart) @@ -147,13 +148,10 @@ def fly_maia( eng_kev = yield from bps.rd(energy.energy.readback) if eng_kev is not None: - yield from bp.mv( - maia.meta_val_beam_energy_sp.value, "{:.2f}".format(eng_kev * 1000) - ) + yield from bp.mv(maia.meta_val_beam_energy_sp.value, f"{eng_kev * 1000:.2f}") @bpp.reset_positions_decorator([hf_stage.x.velocity]) def _raster_plan(): - # set the motors to the right speed yield from bp.mv(hf_stage.x.velocity, spd_x) @@ -191,11 +189,11 @@ def _cleanup_plan(): yield from bp.close_run() yield from bp.mv(maia.meta_val_scan_crossref_sp.value, "") for k in ["info", "name", "owner", "serial", "type"]: - sig = getattr(maia, "meta_val_sample_{}_sp.value".format(k)) + sig = getattr(maia, f"meta_val_sample_{k}_sp.value") yield from bp.mv(sig, "") for k in ["region", "info", "seq_num", "seq_total"]: - sig = getattr(maia, "meta_val_scan_{}_sp.value".format(k)) + sig = getattr(maia, f"meta_val_scan_{k}_sp.value") yield from bp.mv(sig, "") yield from bp.mv(maia.meta_val_beam_energy_sp.value, "") yield from bp.mv(maia.meta_val_scan_dwell.value, "") @@ -225,17 +223,17 @@ def fly_maia_finger_sync( "shape": [ynum, xnum], "motors": [m.name for m in [hf_stage.y, hf_stage.x]], "num_steps": xnum * ynum, - "plan_args": dict( - ystart=ystart, - ystop=ystop, - ynum=ynum, - xstart=xstart, - xstop=xstop, - xnum=xnum, - dwell=dwell, - group=repr(group), - md=md, - ), + "plan_args": { + "ystart": ystart, + "ystop": ystop, + "ynum": ynum, + "xstart": xstart, + "xstop": xstop, + "xnum": xnum, + "dwell": dwell, + "group": repr(group), + "md": md, + }, "extents": [[ystart, ystop], [xstart, xstop]], "snaking": [False, True], "plan_name": "fly_maia", @@ -253,14 +251,13 @@ def fly_maia_finger_sync( # Pitch must match what raster driver uses for pitch ... x_pitch = abs(xstop - xstart) / (xnum - 1) - # TODO compute this based on someting + # TODO compute this based on something spd_x = x_pitch / dwell yield from bp.mv(hf_stage.x, xstart, hf_stage.y, ystart) @bpp.reset_positions_decorator([hf_stage.x.velocity]) def _raster_plan(): - # set the motors to the right speed yield from bp.mv(hf_stage.x.velocity, spd_x) diff --git a/nslsii/plans/__init__.py b/src/nslsii/py.typed similarity index 100% rename from nslsii/plans/__init__.py rename to src/nslsii/py.typed diff --git a/nslsii/re_subs.py b/src/nslsii/re_subs.py similarity index 68% rename from nslsii/re_subs.py rename to src/nslsii/re_subs.py index 97891dd1..a961757f 100644 --- a/nslsii/re_subs.py +++ b/src/nslsii/re_subs.py @@ -1,13 +1,17 @@ +from __future__ import annotations + import json import os from pathlib import Path -class BlueskyDocJSONWriter: - def __init__(self, write_directory: Path | None = None, flush_on_each_doc: bool = True): +class BlueskyDocJSONWriter: + def __init__( + self, write_directory: Path | None = None, flush_on_each_doc: bool = True + ): self._write_json_file: bool = False self._flush_on_each_doc = flush_on_each_doc - self._output_file_name: str | None = None + self._output_file_name: str | None = None self._document_cache = [] self._write_directory: Path = Path("/tmp") if write_directory is not None: @@ -18,14 +22,12 @@ def set_write_directory(self, write_directory: Path): Set the directory to write JSON files to. """ - if not os.path.exists(write_directory): - raise FileNotFoundError( - f"Directory does not exist: {write_directory}" - ) - elif not os.access(write_directory, os.W_OK): - raise PermissionError( - f"Cannot write to directory: {write_directory}" - ) + if not Path.exists(write_directory): + msg = f"Directory does not exist: {write_directory}" + raise FileNotFoundError(msg) + if not os.access(write_directory, os.W_OK): + msg = f"Cannot write to directory: {write_directory}" + raise PermissionError(msg) self._write_directory = write_directory @@ -49,13 +51,15 @@ def disable_writing(self): def __call__(self, name: str, doc: dict): if self._write_json_file: if name == "start": - self._output_file_name = os.path.join(self._write_directory, f"{doc['uid']}.json") + self._output_file_name = ( + Path(self._write_directory) / f"{doc['uid']}.json" + ) if self._output_file_name is not None: self._document_cache.append({name: doc}) if self._flush_on_each_doc or name == "stop": - with open(self._output_file_name, "w") as fp: + with Path.open(self._output_file_name, "w") as fp: json.dump( self._document_cache, fp, @@ -91,7 +95,7 @@ def disable_printing(self): def __call__(self, name: str, doc: dict): if self._print_docs_to_stdout: - print("========= Emitting Doc =============") - print(f"{name = }") - print(f"{json.dumps(doc, indent=4)}") - print("============ Done ==================") + print("========= Emitting Doc =============") # noqa: T201 + print(f"{name = }") # noqa: T201 + print(f"{json.dumps(doc, indent=4)}") # noqa: T201 + print("============ Done ==================") # noqa: T201 diff --git a/src/nslsii/sync_experiment/.DS_Store b/src/nslsii/sync_experiment/.DS_Store new file mode 100644 index 00000000..5008ddfc Binary files /dev/null and b/src/nslsii/sync_experiment/.DS_Store differ diff --git a/src/nslsii/sync_experiment/__init__.py b/src/nslsii/sync_experiment/__init__.py new file mode 100644 index 00000000..056b52fb --- /dev/null +++ b/src/nslsii/sync_experiment/__init__.py @@ -0,0 +1,8 @@ +from __future__ import annotations + +from .sync_experiment import ( + main, # noqa : F401 + switch_redis_proposal, # noqa : F401 + sync_experiment, # noqa : F401 + validate_proposal, # noqa : F401 +) diff --git a/nslsii/sync_experiment/__main__.py b/src/nslsii/sync_experiment/__main__.py similarity index 66% rename from nslsii/sync_experiment/__main__.py rename to src/nslsii/sync_experiment/__main__.py index d12b24c1..8271770c 100644 --- a/nslsii/sync_experiment/__main__.py +++ b/src/nslsii/sync_experiment/__main__.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from .sync_experiment import main if __name__ == "__main__": diff --git a/nslsii/sync_experiment/sync_experiment.py b/src/nslsii/sync_experiment/sync_experiment.py similarity index 75% rename from nslsii/sync_experiment/sync_experiment.py rename to src/nslsii/sync_experiment/sync_experiment.py index 9fcfcacc..147b39b7 100644 --- a/nslsii/sync_experiment/sync_experiment.py +++ b/src/nslsii/sync_experiment/sync_experiment.py @@ -1,11 +1,13 @@ +from __future__ import annotations + import argparse import json -import os import re import warnings from datetime import datetime from getpass import getpass -from typing import Any, Dict, Union, Optional +from pathlib import Path +from typing import Any import httpx import redis @@ -21,7 +23,7 @@ def get_current_cycle() -> str: cycle_response = nslsii_api_client.get( - f"/v1/facility/nsls2/cycles/current" + "/v1/facility/nsls2/cycles/current" ).raise_for_status() return cycle_response.json()["cycle"] @@ -37,15 +39,14 @@ def is_commissioning_proposal(proposal_number, beamline) -> bool: return proposal_number in commissioning_proposals -def validate_proposal(data_session_value, beamline) -> Dict[str, Any]: +def validate_proposal(data_session_value, beamline) -> dict[str, Any]: proposal_data = {} data_session_match = data_session_re.match(data_session_value) if data_session_match is None: - raise ValueError( - f"RE.md['data_session']='{data_session_value}' " - f"is not matched by regular expression '{data_session_re.pattern}'" - ) + msg = f"RE.md['data_session']='{data_session_value}' " + msg += f"is not matched by regular expression '{data_session_re.pattern}'" + raise ValueError(msg) try: current_cycle = get_current_cycle() @@ -56,23 +57,16 @@ def validate_proposal(data_session_value, beamline) -> Dict[str, Any]: ).raise_for_status() proposal_data = proposal_response.json()["proposal"] if "error_message" in proposal_data: - raise ValueError( - f"while verifying data_session '{data_session_value}' " - f"an error was returned by {proposal_response.url}: " - f"{proposal_data}" - ) - else: - if ( - not proposal_commissioning - and current_cycle not in proposal_data["cycles"] - ): - raise ValueError( - f"Proposal {data_session_value} is not valid in the current NSLS2 cycle ({current_cycle})." - ) - if beamline.upper() not in proposal_data["instruments"]: - raise ValueError( - f"Wrong beamline ({beamline.upper()}) for proposal {data_session_value} ({', '.join(proposal_data['instruments'])})." - ) + msg = f"while verifying data_session '{data_session_value}' " + msg += f"an error was returned by {proposal_response.url}: " + msg += f"{proposal_data}" + raise ValueError(msg) + if not proposal_commissioning and current_cycle not in proposal_data["cycles"]: + msg = f"Proposal {data_session_value} is not valid in the current NSLS2 cycle ({current_cycle})." + raise ValueError(msg) + if beamline.upper() not in proposal_data["instruments"]: + msg = f"Wrong beamline ({beamline.upper()}) for proposal {data_session_value} ({', '.join(proposal_data['instruments'])})." + raise ValueError(msg) # data_session is valid! except httpx.RequestError as rerr: @@ -80,14 +74,15 @@ def validate_proposal(data_session_value, beamline) -> Dict[str, Any]: warnings.warn( f"while verifying data_session '{data_session_value}' " f"the request {rerr.request.url!r} failed with " - f"'{rerr}'" + f"'{rerr}'", + stacklevel=2, ) return proposal_data config_files = [ - os.path.expanduser("~/.config/n2sn_tools.yml"), + Path.expanduser("~/.config/n2sn_tools.yml"), "/etc/n2sn_tools.yml", ] @@ -98,20 +93,22 @@ def authenticate( config = None for fn in config_files: try: - with open(fn) as f: + with Path.open(fn) as f: config = yaml.safe_load(f) - except IOError: + except OSError: pass else: break if config is None: - raise RuntimeError("Unable to open a config file") + msg = "Unable to open a config file" + raise RuntimeError(msg) server = config.get("common", {}).get("server") if server is None: - raise RuntimeError(f"Server name not found!") + msg = "Server name not found!" + raise RuntimeError(msg) auth_server = Server(server, use_ssl=True) @@ -124,36 +121,32 @@ def authenticate( auto_bind=True, raise_exceptions=True, ) - print(f"\nAuthenticated as : {connection.extend.standard.who_am_i()}") + print(f"\nAuthenticated as : {connection.extend.standard.who_am_i()}") # noqa : T201 except LDAPInvalidCredentialsResult: - raise RuntimeError(f"Invalid credentials for user '{username}'.") from None + msg = f"Invalid credentials for user '{username}'." + raise RuntimeError(msg) from None except LDAPSocketOpenError: - print(f"{server} server connection failed...") + print(f"{server} server connection failed...") # noqa : T201 def should_they_be_here(username, new_data_session, beamline): user_access_json = nslsii_api_client.get(f"/v1/data-session/{username}").json() - if "nsls2" in user_access_json["facility_all_access"]: - return True - - elif beamline.lower() in user_access_json["beamline_all_access"]: - return True - - elif new_data_session in user_access_json["data_sessions"]: - return True - - return False + return ( + "nsls2" in user_access_json["facility_all_access"] + or beamline.lower() in user_access_json["beamline_all_access"] + or new_data_session in user_access_json["data_sessions"] + ) class AuthorizationError(Exception): ... def switch_redis_proposal( - proposal_number: Union[int, str], + proposal_number: int | str, beamline: str, - username: Optional[str] = None, + username: str | None = None, prefix: str = "", ) -> RedisJSONDict: """Update information in RedisJSONDict for a specific beamline @@ -191,15 +184,14 @@ def switch_redis_proposal( else get_current_cycle() ) warnings.warn( - f"Experiment {new_data_session} was already started by the same user." + f"Experiment {new_data_session} was already started by the same user.", + stacklevel=2, ) else: - if not should_they_be_here(username, new_data_session, beamline): - raise AuthorizationError( - f"User '{username}' is not allowed to take data on proposal {new_data_session}" - ) + msg = f"User '{username}' is not allowed to take data on proposal {new_data_session}" + raise AuthorizationError(msg) proposal_data = validate_proposal(new_data_session, beamline) users = proposal_data.pop("users") @@ -207,7 +199,7 @@ def switch_redis_proposal( for user in users: if user.get("is_pi"): pi_name = ( - f'{user.get("first_name", "")} {user.get("last_name", "")}'.strip() + f"{user.get('first_name', '')} {user.get('last_name', '')}".strip() ) md["data_session"] = new_data_session # e.g. "pass-123456" md["username"] = username @@ -227,13 +219,12 @@ def switch_redis_proposal( "pi_name": pi_name, } - print(f"Started experiment {md['data_session']} by {md['username']}.") + print(f"Started experiment {md['data_session']} by {md['username']}.") # noqa : T201 return md def sync_experiment(proposal_number, beamline, verbose=False, prefix=""): - # Authenticate the user username = input("Username : ") authenticate(username) @@ -249,7 +240,7 @@ def sync_experiment(proposal_number, beamline, verbose=False, prefix=""): ) if verbose: - print(json.dumps(md, indent=2)) + print(json.dumps(md, indent=2)) # noqa : T201 return md diff --git a/nslsii/temperature_controllers.py b/src/nslsii/temperature_controllers.py similarity index 77% rename from nslsii/temperature_controllers.py rename to src/nslsii/temperature_controllers.py index 88fa8361..b555649e 100644 --- a/nslsii/temperature_controllers.py +++ b/src/nslsii/temperature_controllers.py @@ -1,9 +1,13 @@ -from ophyd import DeviceStatus, Device, Component as Cpt, EpicsSignal, Signal +from __future__ import annotations + import threading +from ophyd import Component as Cpt +from ophyd import Device, DeviceStatus, EpicsSignal, Signal + class Eurotherm(Device): - '''This class is used for integrating with Eurotherm controllers. + """This class is used for integrating with Eurotherm controllers. This is used for Eurotherm controllers and is designed to ensure that the set returns 'done' status only after the temperature has reached @@ -18,7 +22,7 @@ class Eurotherm(Device): ---------- pv_prefix : str. The PV prefix that is common to the readback and setpoint PV's. - ''' + """ def __init__(self, pv_prefix, **kwargs): super().__init__(pv_prefix, **kwargs) @@ -29,20 +33,21 @@ def __init__(self, pv_prefix, **kwargs): self._cid = None # Setup some new signals required for the moving indicator logic - equilibrium_time = Cpt(Signal, value=5, kind='config') - timeout = Cpt(Signal, value=500, kind='config') - tolerance = Cpt(Signal, value=1, kind='config') + equilibrium_time = Cpt(Signal, value=5, kind="config") + timeout = Cpt(Signal, value=500, kind="config") + tolerance = Cpt(Signal, value=1, kind="config") # Add the readback and setpoint components - setpoint = Cpt(EpicsSignal, 'T-SP', kind='normal') - readback = Cpt(EpicsSignal, 'T-RB', kind='hinted') + setpoint = Cpt(EpicsSignal, "T-SP", kind="normal") + readback = Cpt(EpicsSignal, "T-RB", kind="hinted") # define the new set method with the new moving indicator def set(self, value): # check that a set is not in progress, and if not set the lock. if not self._set_lock.acquire(blocking=False): - raise SetInProgress('attempting to set {} '.format(self.name) + - 'while a set is in progress') + raise SetInProgress( + f"attempting to set {self.name} " + "while a set is in progress" + ) # define some required values set_value = value @@ -57,8 +62,7 @@ def set(self, value): # setup a cleanup function for the timer, this matches including # timeout in `status` but also ensures that the callback is removed. def timer_cleanup(): - print('Set of {} timed out after {} s'.format(self.name, - self.timeout.get())) + print(f"Set of {self.name} timed out after {self.timeout.get()} s") # noqa : T201 self._set_lock.release() self.readback.clear_sub(status_indicator) status._finished(success=False) @@ -66,7 +70,7 @@ def timer_cleanup(): self._cb_timer = threading.Timer(self.timeout.get(), timer_cleanup) # set up the done moving indicator logic - def status_indicator(value, timestamp, **kwargs): + def status_indicator(value, timestamp, **kwargs): # noqa : ARG001 # add a Timer to ensure that timeout occurs. if not self._cb_timer.is_alive(): self._cb_timer.start() @@ -93,8 +97,8 @@ def status_indicator(value, timestamp, **kwargs): # hand the status object back to the RE return status - def stop(self, success=False): - # overide the lock, cancel the timer and remove the subscription on any + def stop(self, success=False): # noqa : ARG002 + # override the lock, cancel the timer and remove the subscription on any # in progress sets self._set_lock.release() self._cb_timer.cancel() @@ -103,5 +107,4 @@ def stop(self, success=False): self.set(self.readback.get()) -class SetInProgress(RuntimeError): - ... +class SetInProgress(RuntimeError): ... diff --git a/nslsii/transforms.py b/src/nslsii/transforms.py similarity index 57% rename from nslsii/transforms.py rename to src/nslsii/transforms.py index 233f9258..04872659 100644 --- a/nslsii/transforms.py +++ b/src/nslsii/transforms.py @@ -1,7 +1,9 @@ # DataBroker "transforms" for patching up documents # on their way out. +from __future__ import annotations + import copy -import os +from pathlib import Path def csx_fix_scaler_shape(d): @@ -12,11 +14,12 @@ def csx_fix_scaler_shape(d): Ensure that their shape is []. """ d = copy.deepcopy(d) - for k, v in list(d['data_keys'].items()): - if v['source'].startswith('PV:XF:23ID1-ES{Sclr:1}Wfrm'): - d['data_keys'][k]['shape'] = [] + for k, v in list(d["data_keys"].items()): + if v["source"].startswith("PV:XF:23ID1-ES{Sclr:1}Wfrm"): + d["data_keys"][k]["shape"] = [] return d + def srx_transform_resource(doc): """ This patch is used to update the root and resource path of resource documents @@ -24,9 +27,11 @@ def srx_transform_resource(doc): needed because root_map is not sufficient in this case. """ doc = dict(doc) - full_path = os.path.join(doc['root'], doc['resource_path']) - new_path = full_path.replace('/nsls2/xf05id1/XF05ID1', '/nsls2/data/srx/legacy/xf05id1/XF05ID1') - doc['root'] = '' - doc['resource_path'] = new_path + full_path = str(Path(doc["root"]) / doc["resource_path"]) + new_path = full_path.replace( + "/nsls2/xf05id1/XF05ID1", "/nsls2/data/srx/legacy/xf05id1/XF05ID1" + ) + doc["root"] = "" + doc["resource_path"] = new_path return doc diff --git a/nslsii/tests/conftest.py b/tests/conftest.py similarity index 76% rename from nslsii/tests/conftest.py rename to tests/conftest.py index 131aead1..ea8b927d 100644 --- a/nslsii/tests/conftest.py +++ b/tests/conftest.py @@ -1,17 +1,7 @@ -from contextlib import contextmanager # noqa - -import redis +from __future__ import annotations import pytest - -from bluesky.tests.conftest import RE # noqa -from bluesky_kafka import BlueskyConsumer # noqa -from bluesky_kafka.tests.conftest import ( # noqa - kafka_bootstrap_servers, - consume_documents_from_kafka_until_first_stop_document, - temporary_topics, -) -from ophyd.tests.conftest import hw # noqa +import redis from nslsii.md_dict import RunEngineRedisDict @@ -21,35 +11,35 @@ def pytest_addoption(parser): "--xs3-root-path", action="store", default=None, - help="path to bluesky 'root' directory where xspress3 writes data files" + help="path to bluesky 'root' directory where xspress3 writes data files", ) parser.addoption( "--xs3-path-template", action="store", default=None, - help="path to directory where xspress3 will write files" + help="path to directory where xspress3 will write files", ) parser.addoption( "--xs3-pv-prefix", action="store", default=None, - help="PV prefix for xspress3, for example `XF:05IDD-ES{Xsp:1}:`" + help="PV prefix for xspress3, for example `XF:05IDD-ES{Xsp:1}:`", ) parser.addoption( "--xs3-channel-numbers", action="store", default=None, - help="comma-separated xspress3 channel numbers, for example `1,2,3`" + help="comma-separated xspress3 channel numbers, for example `1,2,3`", ) parser.addoption( "--xs3-mcaroi-numbers", action="store", default=None, - help="comma-separated xspress3 mcaroi numbers, for example `1,2,3`" + help="comma-separated xspress3 mcaroi numbers, for example `1,2,3`", ) parser.addoption( @@ -80,9 +70,7 @@ def xs3_channel_numbers(request): comma_separated_numbers = request.config.getoption("--xs3-channel-numbers") if comma_separated_numbers is None: return None - else: - number_list = [int(n) for n in comma_separated_numbers.split(",")] - return number_list + return [int(n) for n in comma_separated_numbers.split(",")] @pytest.fixture @@ -90,9 +78,7 @@ def xs3_mcaroi_numbers(request): comma_separated_numbers = request.config.getoption("--xs3-mcaroi-numbers") if comma_separated_numbers is None: return None - else: - number_list = [int(n) for n in comma_separated_numbers.split(",")] - return number_list + return [int(n) for n in comma_separated_numbers.split(",")] @pytest.fixture @@ -121,11 +107,9 @@ def _factory(**kwargs): kwargs.keys() ) if len(disallowed_kwargs_preset) > 0: - raise KeyError( - f"{disallowed_kwargs_preset} given, but 'host', 'port', and 'db' may not be specified" - ) - else: - kwargs.update(redis_server_kwargs) + msg = f"{disallowed_kwargs_preset} given, but 'host', 'port', and 'db' may not be specified" + raise KeyError(msg) + kwargs.update(redis_server_kwargs) return RunEngineRedisDict(**kwargs) diff --git a/nslsii/tests/ophyd_async/test_ophyd_async_providers.py b/tests/ophyd_async/test_ophyd_async_providers.py similarity index 97% rename from nslsii/tests/ophyd_async/test_ophyd_async_providers.py rename to tests/ophyd_async/test_ophyd_async_providers.py index 6ec7f630..68debd89 100644 --- a/nslsii/tests/ophyd_async/test_ophyd_async_providers.py +++ b/tests/ophyd_async/test_ophyd_async_providers.py @@ -1,14 +1,17 @@ +from __future__ import annotations + +import os from datetime import datetime from enum import Enum + import pytest -import os from ophyd_async.core import StaticFilenameProvider from nslsii.ophyd_async import ( - ProposalNumYMDPathProvider, + DeviceNameFilenameProvider, ProposalNumScanNumPathProvider, + ProposalNumYMDPathProvider, ShortUUIDFilenameProvider, - DeviceNameFilenameProvider, YMDGranularity, ) from nslsii.ophyd_async.providers import AcqModeFilenameProvider @@ -27,12 +30,11 @@ def fp(): @pytest.fixture def dummy_re_md_dict(): - md = { + return { "data_session": "pass-000000", "cycle": "2024-3", "scan_id": 0, } - return md @pytest.mark.parametrize( @@ -107,7 +109,7 @@ def test_proposal_num_scan_num_path_provider(fp, dummy_re_md_dict): def test_device_name_filename_provider(): dev_name_fp = DeviceNameFilenameProvider() - assert "test" == dev_name_fp(device_name="test") + assert dev_name_fp(device_name="test") == "test" # Device name filename provider must be called with device_name kwarg with pytest.raises(RuntimeError): diff --git a/tests/test_ipynb.py b/tests/test_ipynb.py new file mode 100644 index 00000000..007af34c --- /dev/null +++ b/tests/test_ipynb.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +import os + + +def test_ipynb(): + from nslsii.common import ipynb # noqa: PLC0415 + + obj = ipynb.get_sys_info() + obj.data # noqa: B018 + obj.filename # noqa: B018 + obj.metadata # noqa: B018 + obj.url # noqa: B018 + obj.reload() + + +def test_touchbl(): + from nslsii.common import if_touch_beamline # noqa: PLC0415 + + if "TOUCHBEAMLINE" in os.environ: + del os.environ["TOUCHBEAMLINE"] + + assert not if_touch_beamline() + + os.environ["TOUCHBEAMLINE"] = "1" + + assert if_touch_beamline() diff --git a/nslsii/tests/test_logutils.py b/tests/test_logutils.py similarity index 94% rename from nslsii/tests/test_logutils.py rename to tests/test_logutils.py index 921f9b97..992a8da2 100644 --- a/nslsii/tests/test_logutils.py +++ b/tests/test_logutils.py @@ -1,12 +1,14 @@ +from __future__ import annotations + import datetime import io -import os import logging +import os +import shutil +import stat import subprocess from logging.handlers import SysLogHandler from pathlib import Path -import shutil -import stat from unittest.mock import MagicMock import appdirs @@ -215,23 +217,32 @@ def test_configure_bluesky_logging_syslog_logging(tmpdir): configure_bluesky_logging(ipython=ip) for logger_name in ("bluesky", "caproto", "nslsii", "ophyd", ip.log.name): assert any( - [ - isinstance(handler, SysLogHandler) - for handler in logging.getLogger(logger_name).handlers - ] + isinstance(handler, SysLogHandler) + for handler in logging.getLogger(logger_name).handlers ) # remember the time so we can ask journalctl for only the most recent log messages time_before_logging = datetime.datetime.now().time().isoformat(timespec="seconds") for logger_name in ("bluesky", "caproto", "nslsii", "ophyd", ip.log.name): - logging.getLogger(logger_name).info(f"{logger_name} log message %s", time_before_logging) + logging.getLogger(logger_name).info( + "%s log message %s", logger_name, time_before_logging + ) for logger_name in ("bluesky", "caproto", "nslsii", "ophyd", ip.log.name): journalctl_output = subprocess.run( - ["journalctl", f"SYSLOG_IDENTIFIER={logger_name}", f"--since={time_before_logging}", "--no-pager"], + [ + "journalctl", + f"SYSLOG_IDENTIFIER={logger_name}", + f"--since={time_before_logging}", + "--no-pager", + ], + check=False, capture_output=True, ) - assert f"{logger_name} log message {time_before_logging}" in journalctl_output.stdout.decode() + assert ( + f"{logger_name} log message {time_before_logging}" + in journalctl_output.stdout.decode() + ) def test_ipython_log_exception(): @@ -339,7 +350,7 @@ def test_configure_ipython_exc_logging_with_unwriteable_dir(tmpdir): def test_configure_ipython_exc_logging_file_exists(tmpdir): log_file_path = Path(tmpdir) / Path("bluesky_ipython.log") - with open(log_file_path, "w") as f: + with Path.open(log_file_path, "w") as f: f.write("log log log") ip = IPython.core.interactiveshell.InteractiveShell() @@ -355,7 +366,7 @@ def test_configure_ipython_exc_logging_file_exists(tmpdir): def test_configure_ipython_exc_logging_rotate(tmpdir): log_file_path = Path(tmpdir) / Path("bluesky_ipython.log") - with open(log_file_path, "w") as f: + with Path.open(log_file_path, "w") as f: f.write("log log log") ip = IPython.core.interactiveshell.InteractiveShell() diff --git a/nslsii/tests/test_re_subs.py b/tests/test_re_subs.py similarity index 76% rename from nslsii/tests/test_re_subs.py rename to tests/test_re_subs.py index 14a9606c..0a72b501 100644 --- a/nslsii/tests/test_re_subs.py +++ b/tests/test_re_subs.py @@ -1,7 +1,11 @@ -import pytest +from __future__ import annotations + import json +from pathlib import Path + +import pytest -from nslsii.re_subs import BlueskyDocStreamPrinter, BlueskyDocJSONWriter +from nslsii.re_subs import BlueskyDocJSONWriter, BlueskyDocStreamPrinter TEST_DOCS = [ ( @@ -95,13 +99,21 @@ @pytest.mark.parametrize( - "printing_enabled, expected_output", - [ - (True, [(f"name = '{name}'", json.dumps(doc, indent=4)) for name, doc in TEST_DOCS]), - (False, [("", "")] * len(TEST_DOCS)), - ], + ("printing_enabled", "expected_output"), + [ + ( + True, + [ + (f"name = '{name}'", json.dumps(doc, indent=4)) + for name, doc in TEST_DOCS + ], + ), + (False, [("", "")] * len(TEST_DOCS)), + ], ) -def test_bs_doc_stream_printer(capsys, printing_enabled: bool, expected_output: list[tuple[str, str]]): +def test_bs_doc_stream_printer( + capsys, printing_enabled: bool, expected_output: list[tuple[str, str]] +): """Test that the dump_docs_to_stdout function works as expected.""" doc_stream_printer = BlueskyDocStreamPrinter() @@ -120,19 +132,44 @@ def test_bs_doc_stream_printer(capsys, printing_enabled: bool, expected_output: @pytest.mark.parametrize( - "writing_enabled, flush_each_doc_enabled, expected_file_exists, expected_file_contents", + ( + "writing_enabled", + "flush_each_doc_enabled", + "expected_file_exists", + "expected_file_contents", + ), [ - (True, True, [True] * len(TEST_DOCS), [[{name: doc} for name, doc in TEST_DOCS[:i]] for i in range(1, len(TEST_DOCS) + 1)]), - (True, False, [False] * (len(TEST_DOCS) - 1) + [True], [None] * (len(TEST_DOCS) - 1) + [[{name: doc} for name, doc in TEST_DOCS]]), + ( + True, + True, + [True] * len(TEST_DOCS), + [ + [{name: doc} for name, doc in TEST_DOCS[:i]] + for i in range(1, len(TEST_DOCS) + 1) + ], + ), + ( + True, + False, + [False] * (len(TEST_DOCS) - 1) + [True], + [None] * (len(TEST_DOCS) - 1) + [[{name: doc} for name, doc in TEST_DOCS]], + ), (False, True, [False] * len(TEST_DOCS), [None] * len(TEST_DOCS)), (False, False, [False] * len(TEST_DOCS), [None] * len(TEST_DOCS)), ], ) -def test_json_bluesky_doc_writer(tmp_path, writing_enabled: bool, flush_each_doc_enabled: bool, - expected_file_exists: list[bool], expected_file_contents: list[dict | None]): +def test_json_bluesky_doc_writer( + tmp_path, + writing_enabled: bool, + flush_each_doc_enabled: bool, + expected_file_exists: list[bool], + expected_file_contents: list[dict | None], +): """Test that the JSONBlueskyDocWriter works as expected.""" - writer = BlueskyDocJSONWriter(write_directory=tmp_path, flush_on_each_doc=flush_each_doc_enabled) + writer = BlueskyDocJSONWriter( + write_directory=tmp_path, flush_on_each_doc=flush_each_doc_enabled + ) expected_filename = TEST_DOCS[0][1]["uid"] + ".json" if writing_enabled: @@ -145,7 +182,7 @@ def test_json_bluesky_doc_writer(tmp_path, writing_enabled: bool, flush_each_doc assert (tmp_path / expected_filename).exists() == expected_file_exists[i] if expected_file_contents[i] is not None: - with open(tmp_path / expected_filename) as fp: + with Path.open(tmp_path / expected_filename) as fp: data = json.load(fp) assert data == expected_file_contents[i] diff --git a/nslsii/tests/test_redis_dict.py b/tests/test_redis_dict.py similarity index 94% rename from nslsii/tests/test_redis_dict.py rename to tests/test_redis_dict.py index d37dbc10..60030af5 100644 --- a/nslsii/tests/test_redis_dict.py +++ b/tests/test_redis_dict.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import time from pprint import pformat @@ -36,7 +38,7 @@ def _get_waiting_messages(redis_subscriber): message_list.append(message) message = redis_subscriber.get_message() - print(f"_get_waiting_messages() returning\n{message_list}") + print(f"_get_waiting_messages() returning\n{message_list}") # noqa: T201 return message_list @@ -74,7 +76,7 @@ def test__parse_message_data(): assert uuid == "uuid" message = {"data": b"abcuuid"} - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 RunEngineRedisDict._parse_message_data(message) @@ -92,7 +94,7 @@ def test_local_float_value(redis_dict_factory): Test that a float is stored and retrieved. """ redis_dict = redis_dict_factory(re_md_channel_name="test_local_float_value") - import math + import math # noqa: PLC0415 redis_dict["local_float"] = math.pi assert redis_dict["local_float"] == math.pi @@ -137,7 +139,7 @@ def test_global_int_value(redis_dict_factory): # expect an exception because "scan_id" is # constrained to be an integer - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 redis_dict_1["scan_id"] = "one" assert redis_dict_1["scan_id"] == 0 @@ -188,7 +190,7 @@ def test_items(redis_dict_factory): redis_dict = redis_dict_factory(re_md_channel_name="test_items") # no global metadata exists yet - actual_global_items = {gk: gv for gk, gv in redis_dict.items()} + actual_global_items = dict(redis_dict.items()) assert actual_global_items == {} # set a value for each global key @@ -196,7 +198,7 @@ def test_items(redis_dict_factory): global_md_updates["scan_id"] = 1 redis_dict.update(global_md_updates) - actual_global_items = {gk: gv for gk, gv in redis_dict.items()} + actual_global_items = dict(redis_dict.items()) # _local_md should still be empty # since only global metadata was updated assert len(redis_dict._local_md) == 0 @@ -206,16 +208,16 @@ def test_items(redis_dict_factory): local_md_updates = {"one": 1, "two": "2"} redis_dict.update(local_md_updates) assert redis_dict._local_md == local_md_updates - expected_items = dict() + expected_items = {} expected_items.update(global_md_updates) expected_items.update(local_md_updates) - actual_items = {k: v for k, v in redis_dict.items()} + actual_items = dict(redis_dict.items()) assert actual_items == expected_items def test_one_message(redis_dict_factory): redis_dict = redis_dict_factory(re_md_channel_name="test_one_message") - print(redis_dict._local_md) + print(redis_dict._local_md) # noqa: T201 assert len(redis_dict._local_md) == 0 redis_subscriber = _build_redis_subscriber(redis_dict) @@ -227,7 +229,7 @@ def test_one_message(redis_dict_factory): redis_dict["generate_one_message"] = 1 # expect one message messages = _get_waiting_messages(redis_subscriber) - print(f"messages:\n {pformat(messages)}") + print(f"messages:\n {pformat(messages)}") # noqa: T201 assert len(messages) == 1 updated_key, publisher_uuid = redis_dict._parse_message_data(messages[0]) assert updated_key == "generate_one_message" @@ -236,7 +238,7 @@ def test_one_message(redis_dict_factory): def test_two_messages(redis_dict_factory): redis_dict = redis_dict_factory(re_md_channel_name="test_two_messages") - print(redis_dict._local_md) + print(redis_dict._local_md) # noqa: T201 assert len(redis_dict._local_md) == 0 redis_subscriber = _build_redis_subscriber(redis_dict) diff --git a/nslsii/tests/temperature_controllers_test.py b/tests/test_temperature_controllers.py similarity index 62% rename from nslsii/tests/temperature_controllers_test.py rename to tests/test_temperature_controllers.py index 93f4007b..fb8c7a35 100644 --- a/nslsii/tests/temperature_controllers_test.py +++ b/tests/test_temperature_controllers.py @@ -1,11 +1,15 @@ -from nslsii.temperature_controllers import Eurotherm, SetInProgress -from bluesky.plan_stubs import mv -from bluesky import RunEngine -from bluesky.utils import FailedStatus -import subprocess +from __future__ import annotations + import os +import subprocess import sys + import pytest +from bluesky import RunEngine +from bluesky.plan_stubs import mv +from bluesky.utils import FailedStatus + +from nslsii.temperature_controllers import Eurotherm, SetInProgress @pytest.fixture @@ -13,51 +17,57 @@ def RE(): return RunEngine() -@pytest.mark.xfail() +@pytest.mark.xfail def test_Eurotherm(RE): - '''Tests the Eurotherm ophyd device. + """Tests the Eurotherm ophyd device. Parameters ---------- RE : object Bluesky RunEngine for use in testing. - ''' + """ stdout = subprocess.PIPE stdin = None # Start up an IOC based on the thermo_sim device in caproto.ioc_examples - ioc_process = subprocess.Popen([sys.executable, '-m', - 'caproto.tests.example_runner', - 'nslsii.iocs.thermo_sim'], - stdout=stdout, stdin=stdin, - env=os.environ) + ioc_process = subprocess.Popen( + [ + sys.executable, + "-m", + "caproto.tests.example_runner", + "nslsii.iocs.thermo_sim", + ], + stdout=stdout, + stdin=stdin, + env=os.environ, + ) - print('caproto.ioc_examples.thermo_sim is now running') + print("caproto.ioc_examples.thermo_sim is now running") # noqa : T201 # Wrap the rest in a try-except to ensure the ioc is killed before exiting try: - euro = Eurotherm('thermo:', name='euro') - print('euro object is defined') + euro = Eurotherm("thermo:", name="euro") + print("euro object is defined") # noqa : T201 # move the Eurotherm. RE(mv(euro, 100)) # check that the readback value is within euro.tolerance of 100 assert abs(euro.readback.get() - 100) <= euro.tolerance.get() - assert len(euro.readback._callbacks['value']) == 0 # ensure cb is gone + assert len(euro.readback._callbacks["value"]) == 0 # ensure cb is gone # test that the set will fail after 'timeout' euro.timeout.set(1) with pytest.raises(FailedStatus): RE(mv(euro, 100)) # ensure callback is removed - assert len(euro.readback._callbacks['value']) == 0 + assert len(euro.readback._callbacks["value"]) == 0 euro.timeout.set(500) # reset to default for the following tests. # test that the lock prevents setting while set in progress - with pytest.raises(SetInProgress): - for i in range(2): # The previous set may or may not be complete + with pytest.raises(SetInProgress): # noqa : PT012 + for _i in range(2): # The previous set may or may not be complete euro.set(100) finally: diff --git a/nslsii/tests/test_xspress3.py b/tests/test_xspress3.py similarity index 98% rename from nslsii/tests/test_xspress3.py rename to tests/test_xspress3.py index 452dcc59..785b2306 100644 --- a/nslsii/tests/test_xspress3.py +++ b/tests/test_xspress3.py @@ -1,13 +1,14 @@ +from __future__ import annotations + import re import pytest - from ophyd import ADBase, Component, EpicsSignal, Kind, Signal from nslsii.areadetector.xspress3 import ( Mca, - McaSum, McaRoi, + McaSum, Sca, Xspress3Detector, build_channel_class, @@ -370,10 +371,7 @@ def test_extra_class_members(): channel_numbers=(3, 5), mcaroi_numbers=(4, 6), image_data_key="image", - extra_class_members={ - "ten": 10, - "a_signal": Component(EpicsSignal, "Signal") - }, + extra_class_members={"ten": 10, "a_signal": Component(EpicsSignal, "Signal")}, ) assert detector_class.ten == 10 @@ -392,7 +390,7 @@ def test_extra_class_members_failure(): name as one of the detector class members. """ with pytest.raises(TypeError): - detector_class = build_xspress3_class( + _ = build_xspress3_class( channel_numbers=(3, 5), mcaroi_numbers=(4, 6), image_data_key="image", @@ -427,7 +425,7 @@ def test_get_channel(): detector = detector_class(prefix="Xsp3:", name="xs3") channel03 = detector.get_channel(channel_number=3) - print(channel03) + print(channel03) # noqa: T201 assert channel03.mcaroi04.total_rbv.pvname == "Xsp3:MCA3ROI:4:Total_RBV" channel05 = detector.get_channel(channel_number=5) diff --git a/nslsii/tests/test_xspress3_hdf5plugin.py b/tests/test_xspress3_hdf5plugin.py similarity index 76% rename from nslsii/tests/test_xspress3_hdf5plugin.py rename to tests/test_xspress3_hdf5plugin.py index e2bff9f3..36052924 100644 --- a/nslsii/tests/test_xspress3_hdf5plugin.py +++ b/tests/test_xspress3_hdf5plugin.py @@ -1,10 +1,10 @@ +from __future__ import annotations + import datetime import pytest -from nslsii.areadetector.xspress3 import ( - Xspress3HDF5Plugin -) +from nslsii.areadetector.xspress3 import Xspress3HDF5Plugin def test__build_data_dir_path(): @@ -14,7 +14,7 @@ def test__build_data_dir_path(): the_full_data_dir_path = Xspress3HDF5Plugin._build_data_dir_path( the_datetime=datetime.datetime(year=2020, month=1, day=1), root_path=root_path, - path_template=path_template + path_template=path_template, ) assert the_full_data_dir_path == "/abc/def/ghi/jkl/mno/2020/01/01" @@ -27,7 +27,7 @@ def test__build_data_dir_path_relative_path_template(): the_full_data_dir_path = Xspress3HDF5Plugin._build_data_dir_path( the_datetime=datetime.datetime(year=2020, month=1, day=1), root_path=root_path, - path_template=path_template + path_template=path_template, ) assert the_full_data_dir_path == "/abc/def/ghi/jkl/mno/2020/01/01" @@ -36,9 +36,6 @@ def test__build_data_dir_path_relative_path_template(): @pytest.mark.skip("this test requires an IOC") def test_default_spec(): hdf5 = Xspress3HDF5Plugin( - name="hdf5", - root_path="", - path_template="", - resource_kwargs={} + name="hdf5", root_path="", path_template="", resource_kwargs={} ) - assert hdf5.spec == "XSP3" \ No newline at end of file + assert hdf5.spec == "XSP3" diff --git a/nslsii/tests/test_xspress3_with_hw.py b/tests/test_xspress3_with_hw.py similarity index 96% rename from nslsii/tests/test_xspress3_with_hw.py rename to tests/test_xspress3_with_hw.py index c8af686a..7ea9c0aa 100644 --- a/nslsii/tests/test_xspress3_with_hw.py +++ b/tests/test_xspress3_with_hw.py @@ -1,10 +1,11 @@ +from __future__ import annotations + import datetime -import os import re import time +from pathlib import Path import pytest - from area_detector_handlers.handlers import Xspress3HDF5Handler from bluesky import RunEngine from bluesky.plans import count @@ -13,8 +14,8 @@ from ophyd.areadetector import Xspress3Detector from nslsii.areadetector.xspress3 import ( - Xspress3Trigger, Xspress3HDF5Plugin, + Xspress3Trigger, build_xspress3_class, ) @@ -86,7 +87,7 @@ def test_trigger(xs3_pv_prefix, xs3_root_path, xs3_path_template): --xs3-root-path "/nsls2/lob1/lab3/" \ --xs3-path-template "/nsls2/lob1/lab3/xspress3/ophyd_testing/" """ - if xs3_root_path is None or not os.path.exists(xs3_root_path): + if xs3_root_path is None or not Path.exists(xs3_root_path): pytest.skip("xspress3 root path was not specified") if xs3_pv_prefix is None: pytest.skip("xspress3 PV prefix was not specified") @@ -175,7 +176,7 @@ def test_document_stream( --xs3-channel-numbers 1,2,3 \ --xs3-mcaroi-numbers 1,2,3 """ - if xs3_root_path is None or not os.path.exists(xs3_root_path): + if xs3_root_path is None or not Path.exists(xs3_root_path): pytest.skip("xspress3 root path was not specified") if xs3_pv_prefix is None: pytest.skip("xspress3 PV prefix was not specified") @@ -210,8 +211,6 @@ def append_document(name, document): ) xspress3 = xspress3_class(prefix=xs3_pv_prefix, name="xs3") - # - RE(count([xspress3])) # expect one datum document per channel @@ -226,9 +225,9 @@ def append_document(name, document): "stop", ) - actual_document_names = list() + actual_document_names = [] - filled_documents = list() + filled_documents = [] with Filler( {Xspress3HDF5Handler.HANDLER_NAME: Xspress3HDF5Handler}, inplace=True diff --git a/versioneer.py b/versioneer.py index f84667eb..1e3753e6 100644 --- a/versioneer.py +++ b/versioneer.py @@ -1,5 +1,5 @@ -# Version: 0.18 +# Version: 0.29 """The Versioneer - like a rocketeer, but for versions. @@ -7,18 +7,14 @@ ============== * like a rocketeer, but for versions! -* https://github.com/warner/python-versioneer +* https://github.com/python-versioneer/python-versioneer * Brian Warner -* License: Public Domain -* Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, 3.5, 3.6, and pypy -* [![Latest Version] -(https://pypip.in/version/versioneer/badge.svg?style=flat) -](https://pypi.python.org/pypi/versioneer/) -* [![Build Status] -(https://travis-ci.org/warner/python-versioneer.png?branch=master) -](https://travis-ci.org/warner/python-versioneer) - -This is a tool for managing a recorded version number in distutils-based +* License: Public Domain (Unlicense) +* Compatible with: Python 3.7, 3.8, 3.9, 3.10, 3.11 and pypy3 +* [![Latest Version][pypi-image]][pypi-url] +* [![Build Status][travis-image]][travis-url] + +This is a tool for managing a recorded version number in setuptools-based python projects. The goal is to remove the tedious and error-prone "update the embedded version string" step from your release process. Making a new release should be as easy as recording a new tag in your version-control @@ -27,9 +23,38 @@ ## Quick Install -* `pip install versioneer` to somewhere to your $PATH -* add a `[versioneer]` section to your setup.cfg (see below) -* run `versioneer install` in your source tree, commit the results +Versioneer provides two installation modes. The "classic" vendored mode installs +a copy of versioneer into your repository. The experimental build-time dependency mode +is intended to allow you to skip this step and simplify the process of upgrading. + +### Vendored mode + +* `pip install versioneer` to somewhere in your $PATH + * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is + available, so you can also use `conda install -c conda-forge versioneer` +* add a `[tool.versioneer]` section to your `pyproject.toml` or a + `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) + * Note that you will need to add `tomli; python_version < "3.11"` to your + build-time dependencies if you use `pyproject.toml` +* run `versioneer install --vendor` in your source tree, commit the results +* verify version information with `python setup.py version` + +### Build-time dependency mode + +* `pip install versioneer` to somewhere in your $PATH + * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is + available, so you can also use `conda install -c conda-forge versioneer` +* add a `[tool.versioneer]` section to your `pyproject.toml` or a + `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) +* add `versioneer` (with `[toml]` extra, if configuring in `pyproject.toml`) + to the `requires` key of the `build-system` table in `pyproject.toml`: + ```toml + [build-system] + requires = ["setuptools", "versioneer[toml]"] + build-backend = "setuptools.build_meta" + ``` +* run `versioneer install --no-vendor` in your source tree, commit the results +* verify version information with `python setup.py version` ## Version Identifiers @@ -61,7 +86,7 @@ for example `git describe --tags --dirty --always` reports things like "0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the 0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has -uncommitted changes. +uncommitted changes). The version identifier is used for multiple purposes: @@ -166,7 +191,7 @@ Some situations are known to cause problems for Versioneer. This details the most significant ones. More can be found on Github -[issues page](https://github.com/warner/python-versioneer/issues). +[issues page](https://github.com/python-versioneer/python-versioneer/issues). ### Subprojects @@ -180,7 +205,7 @@ `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI distributions (and upload multiple independently-installable tarballs). * Source trees whose main purpose is to contain a C library, but which also - provide bindings to Python (and perhaps other langauges) in subdirectories. + provide bindings to Python (and perhaps other languages) in subdirectories. Versioneer will look for `.git` in parent directories, and most operations should get the right version string. However `pip` and `setuptools` have bugs @@ -194,9 +219,9 @@ Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in some later version. -[Bug #38](https://github.com/warner/python-versioneer/issues/38) is tracking +[Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking this issue. The discussion in -[PR #61](https://github.com/warner/python-versioneer/pull/61) describes the +[PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the issue from the Versioneer side in more detail. [pip PR#3176](https://github.com/pypa/pip/pull/3176) and [pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve @@ -224,31 +249,20 @@ cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into a different virtualenv), so this can be surprising. -[Bug #83](https://github.com/warner/python-versioneer/issues/83) describes +[Bug #83](https://github.com/python-versioneer/python-versioneer/issues/83) describes this one, but upgrading to a newer version of setuptools should probably resolve it. -### Unicode version strings - -While Versioneer works (and is continually tested) with both Python 2 and -Python 3, it is not entirely consistent with bytes-vs-unicode distinctions. -Newer releases probably generate unicode version strings on py2. It's not -clear that this is wrong, but it may be surprising for applications when then -write these strings to a network connection or include them in bytes-oriented -APIs like cryptographic checksums. - -[Bug #71](https://github.com/warner/python-versioneer/issues/71) investigates -this question. - ## Updating Versioneer To upgrade your project to a new release of Versioneer, do the following: * install the new Versioneer (`pip install -U versioneer` or equivalent) -* edit `setup.cfg`, if necessary, to include any new configuration settings - indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. -* re-run `versioneer install` in your source tree, to replace +* edit `setup.cfg` and `pyproject.toml`, if necessary, + to include any new configuration settings indicated by the release notes. + See [UPGRADING](./UPGRADING.md) for details. +* re-run `versioneer install --[no-]vendor` in your source tree, to replace `SRC/_version.py` * commit any changed files @@ -265,35 +279,70 @@ direction and include code from all supported VCS systems, reducing the number of intermediate scripts. +## Similar projects + +* [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time + dependency +* [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of + versioneer +* [versioningit](https://github.com/jwodder/versioningit) - a PEP 518-based setuptools + plugin ## License To make Versioneer easier to embed, all its code is dedicated to the public domain. The `_version.py` that it creates is also in the public domain. -Specifically, both are released under the Creative Commons "Public Domain -Dedication" license (CC0-1.0), as described in -https://creativecommons.org/publicdomain/zero/1.0/ . +Specifically, both are released under the "Unlicense", as described in +https://unlicense.org/. + +[pypi-image]: https://img.shields.io/pypi/v/versioneer.svg +[pypi-url]: https://pypi.python.org/pypi/versioneer/ +[travis-image]: +https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg +[travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer """ +# pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring +# pylint:disable=missing-class-docstring,too-many-branches,too-many-statements +# pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error +# pylint:disable=too-few-public-methods,redefined-outer-name,consider-using-with +# pylint:disable=attribute-defined-outside-init,too-many-arguments -from __future__ import print_function -try: - import configparser -except ImportError: - import ConfigParser as configparser +import configparser import errno import json import os import re import subprocess import sys +from pathlib import Path +from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Union +from typing import NoReturn +import functools + +have_tomllib = True +if sys.version_info >= (3, 11): + import tomllib +else: + try: + import tomli as tomllib + except ImportError: + have_tomllib = False class VersioneerConfig: """Container for Versioneer configuration parameters.""" + VCS: str + style: str + tag_prefix: str + versionfile_source: str + versionfile_build: Optional[str] + parentdir_prefix: Optional[str] + verbose: Optional[bool] + -def get_root(): +def get_root() -> str: """Get the project root directory. We require that all commands are run from the project root, i.e. the @@ -301,13 +350,23 @@ def get_root(): """ root = os.path.realpath(os.path.abspath(os.getcwd())) setup_py = os.path.join(root, "setup.py") + pyproject_toml = os.path.join(root, "pyproject.toml") versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): + if not ( + os.path.exists(setup_py) + or os.path.exists(pyproject_toml) + or os.path.exists(versioneer_py) + ): # allow 'python path/to/setup.py COMMAND' root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) setup_py = os.path.join(root, "setup.py") + pyproject_toml = os.path.join(root, "pyproject.toml") versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): + if not ( + os.path.exists(setup_py) + or os.path.exists(pyproject_toml) + or os.path.exists(versioneer_py) + ): err = ("Versioneer was unable to run the project root directory. " "Versioneer requires setup.py to be executed from " "its immediate directory (like 'python setup.py COMMAND'), " @@ -321,42 +380,62 @@ def get_root(): # module-import table will cache the first one. So we can't use # os.path.dirname(__file__), as that will find whichever # versioneer.py was first imported, even in later projects. - me = os.path.realpath(os.path.abspath(__file__)) - me_dir = os.path.normcase(os.path.splitext(me)[0]) + my_path = os.path.realpath(os.path.abspath(__file__)) + me_dir = os.path.normcase(os.path.splitext(my_path)[0]) vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) - if me_dir != vsr_dir: + if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals(): print("Warning: build in %s is using versioneer.py from %s" - % (os.path.dirname(me), versioneer_py)) + % (os.path.dirname(my_path), versioneer_py)) except NameError: pass return root -def get_config_from_root(root): +def get_config_from_root(root: str) -> VersioneerConfig: """Read the project setup.cfg file to determine Versioneer config.""" - # This might raise EnvironmentError (if setup.cfg is missing), or + # This might raise OSError (if setup.cfg is missing), or # configparser.NoSectionError (if it lacks a [versioneer] section), or # configparser.NoOptionError (if it lacks "VCS="). See the docstring at # the top of versioneer.py for instructions on writing your setup.cfg . - setup_cfg = os.path.join(root, "setup.cfg") - parser = configparser.ConfigParser() - parser.read(setup_cfg) - VCS = parser.get("versioneer", "VCS") # mandatory - - def get(parser, name): - if parser.has_option("versioneer", name): - return parser.get("versioneer", name) - return None + root_pth = Path(root) + pyproject_toml = root_pth / "pyproject.toml" + setup_cfg = root_pth / "setup.cfg" + section: Union[Dict[str, Any], configparser.SectionProxy, None] = None + if pyproject_toml.exists() and have_tomllib: + try: + with open(pyproject_toml, 'rb') as fobj: + pp = tomllib.load(fobj) + section = pp['tool']['versioneer'] + except (tomllib.TOMLDecodeError, KeyError) as e: + print(f"Failed to load config from {pyproject_toml}: {e}") + print("Try to load it from setup.cfg") + if not section: + parser = configparser.ConfigParser() + with open(setup_cfg) as cfg_file: + parser.read_file(cfg_file) + parser.get("versioneer", "VCS") # raise error if missing + + section = parser["versioneer"] + + # `cast`` really shouldn't be used, but its simplest for the + # common VersioneerConfig users at the moment. We verify against + # `None` values elsewhere where it matters + cfg = VersioneerConfig() - cfg.VCS = VCS - cfg.style = get(parser, "style") or "" - cfg.versionfile_source = get(parser, "versionfile_source") - cfg.versionfile_build = get(parser, "versionfile_build") - cfg.tag_prefix = get(parser, "tag_prefix") - if cfg.tag_prefix in ("''", '""'): + cfg.VCS = section['VCS'] + cfg.style = section.get("style", "") + cfg.versionfile_source = cast(str, section.get("versionfile_source")) + cfg.versionfile_build = section.get("versionfile_build") + cfg.tag_prefix = cast(str, section.get("tag_prefix")) + if cfg.tag_prefix in ("''", '""', None): cfg.tag_prefix = "" - cfg.parentdir_prefix = get(parser, "parentdir_prefix") - cfg.verbose = get(parser, "verbose") + cfg.parentdir_prefix = section.get("parentdir_prefix") + if isinstance(section, configparser.SectionProxy): + # Make sure configparser translates to bool + cfg.verbose = section.getboolean("verbose") + else: + cfg.verbose = section.get("verbose") + return cfg @@ -365,37 +444,48 @@ class NotThisMethod(Exception): # these dictionaries contain VCS-specific tools -LONG_VERSION_PY = {} -HANDLERS = {} +LONG_VERSION_PY: Dict[str, str] = {} +HANDLERS: Dict[str, Dict[str, Callable]] = {} -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - def decorate(f): +def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator + """Create decorator to mark a method as the handler of a VCS.""" + def decorate(f: Callable) -> Callable: """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f + HANDLERS.setdefault(vcs, {})[method] = f return f return decorate -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): +def run_command( + commands: List[str], + args: List[str], + cwd: Optional[str] = None, + verbose: bool = False, + hide_stderr: bool = False, + env: Optional[Dict[str, str]] = None, +) -> Tuple[Optional[str], Optional[int]]: """Call the given command(s).""" assert isinstance(commands, list) - p = None - for c in commands: + process = None + + popen_kwargs: Dict[str, Any] = {} + if sys.platform == "win32": + # This hides the console window if pythonw.exe is used + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + popen_kwargs["startupinfo"] = startupinfo + + for command in commands: try: - dispcmd = str([c] + args) + dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) + process = subprocess.Popen([command] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None), **popen_kwargs) break - except EnvironmentError: - e = sys.exc_info()[1] + except OSError as e: if e.errno == errno.ENOENT: continue if verbose: @@ -406,26 +496,25 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, if verbose: print("unable to find command, tried %s" % (commands,)) return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: + stdout = process.communicate()[0].strip().decode() + if process.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) - return None, p.returncode - return stdout, p.returncode + return None, process.returncode + return stdout, process.returncode -LONG_VERSION_PY['git'] = ''' +LONG_VERSION_PY['git'] = r''' # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. -# This file is released into the public domain. Generated by -# versioneer-0.18 (https://github.com/warner/python-versioneer) +# This file is released into the public domain. +# Generated by versioneer-0.29 +# https://github.com/python-versioneer/python-versioneer """Git implementation of _version.py.""" @@ -434,9 +523,11 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, import re import subprocess import sys +from typing import Any, Callable, Dict, List, Optional, Tuple +import functools -def get_keywords(): +def get_keywords() -> Dict[str, str]: """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must @@ -452,8 +543,15 @@ def get_keywords(): class VersioneerConfig: """Container for Versioneer configuration parameters.""" + VCS: str + style: str + tag_prefix: str + parentdir_prefix: str + versionfile_source: str + verbose: bool + -def get_config(): +def get_config() -> VersioneerConfig: """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py @@ -471,13 +569,13 @@ class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" -LONG_VERSION_PY = {} -HANDLERS = {} +LONG_VERSION_PY: Dict[str, str] = {} +HANDLERS: Dict[str, Dict[str, Callable]] = {} -def register_vcs_handler(vcs, method): # decorator - """Decorator to mark a method as the handler for a particular VCS.""" - def decorate(f): +def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator + """Create decorator to mark a method as the handler of a VCS.""" + def decorate(f: Callable) -> Callable: """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} @@ -486,22 +584,35 @@ def decorate(f): return decorate -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): +def run_command( + commands: List[str], + args: List[str], + cwd: Optional[str] = None, + verbose: bool = False, + hide_stderr: bool = False, + env: Optional[Dict[str, str]] = None, +) -> Tuple[Optional[str], Optional[int]]: """Call the given command(s).""" assert isinstance(commands, list) - p = None - for c in commands: + process = None + + popen_kwargs: Dict[str, Any] = {} + if sys.platform == "win32": + # This hides the console window if pythonw.exe is used + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + popen_kwargs["startupinfo"] = startupinfo + + for command in commands: try: - dispcmd = str([c] + args) + dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) + process = subprocess.Popen([command] + args, cwd=cwd, env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None), **popen_kwargs) break - except EnvironmentError: - e = sys.exc_info()[1] + except OSError as e: if e.errno == errno.ENOENT: continue if verbose: @@ -512,18 +623,20 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, if verbose: print("unable to find command, tried %%s" %% (commands,)) return None, None - stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: - stdout = stdout.decode() - if p.returncode != 0: + stdout = process.communicate()[0].strip().decode() + if process.returncode != 0: if verbose: print("unable to run %%s (error)" %% dispcmd) print("stdout was %%s" %% stdout) - return None, p.returncode - return stdout, p.returncode + return None, process.returncode + return stdout, process.returncode -def versions_from_parentdir(parentdir_prefix, root, verbose): +def versions_from_parentdir( + parentdir_prefix: str, + root: str, + verbose: bool, +) -> Dict[str, Any]: """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both @@ -532,15 +645,14 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): """ rootdirs = [] - for i in range(3): + for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level + rootdirs.append(root) + root = os.path.dirname(root) # up a level if verbose: print("Tried directories %%s but none started with prefix %%s" %% @@ -549,41 +661,48 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): @register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): +def git_get_keywords(versionfile_abs: str) -> Dict[str, str]: """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. - keywords = {} + keywords: Dict[str, str] = {} try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: + with open(versionfile_abs, "r") as fobj: + for line in fobj: + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + except OSError: pass return keywords @register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): +def git_versions_from_keywords( + keywords: Dict[str, str], + tag_prefix: str, + verbose: bool, +) -> Dict[str, Any]: """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") + if "refnames" not in keywords: + raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because @@ -596,11 +715,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) + refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %%d @@ -609,7 +728,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) + tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%%s', no digits" %% ",".join(refs - tags)) if verbose: @@ -618,6 +737,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] + # Filter out refs that exactly match prefix or that don't start + # with a number once the prefix is stripped (mostly a concern + # when prefix is '') + if not re.match(r'\d', r): + continue if verbose: print("picking %%s" %% r) return {"version": r, @@ -633,7 +757,12 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): @register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): +def git_pieces_from_vcs( + tag_prefix: str, + root: str, + verbose: bool, + runner: Callable = run_command +) -> Dict[str, Any]: """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* @@ -644,8 +773,15 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) + # GIT_DIR can interfere with correct operation of Versioneer. + # It may be intended to be passed to the Versioneer-versioned project, + # but that should not change where we get our version from. + env = os.environ.copy() + env.pop("GIT_DIR", None) + runner = functools.partial(runner, env=env) + + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=not verbose) if rc != 0: if verbose: print("Directory %%s not under git control" %% root) @@ -653,24 +789,57 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%%s*" %% tag_prefix], - cwd=root) + describe_out, rc = runner(GITS, [ + "describe", "--tags", "--dirty", "--always", "--long", + "--match", f"{tag_prefix}[[:digit:]]*" + ], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() - pieces = {} + pieces: Dict[str, Any] = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], + cwd=root) + # --abbrev-ref was added in git-1.6.3 + if rc != 0 or branch_name is None: + raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") + branch_name = branch_name.strip() + + if branch_name == "HEAD": + # If we aren't exactly on a branch, pick a branch which represents + # the current commit. If all else fails, we are on a branchless + # commit. + branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) + # --contains was added in git-1.5.4 + if rc != 0 or branches is None: + raise NotThisMethod("'git branch --contains' returned error") + branches = branches.split("\n") + + # Remove the first line if we're running detached + if "(" in branches[0]: + branches.pop(0) + + # Strip off the leading "* " from the list of branches. + branches = [branch[2:] for branch in branches] + if "master" in branches: + branch_name = "master" + elif not branches: + branch_name = None + else: + # Pick the first branch that is returned. Good or bad. + branch_name = branches[0] + + pieces["branch"] = branch_name + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out @@ -687,7 +856,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: - # unparseable. Maybe git-describe is misbehaving? + # unparsable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%%s'" %% describe_out) return pieces @@ -712,26 +881,27 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): else: # HEX: no tags pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) - pieces["distance"] = int(count_out) # total number of commits + out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) + pieces["distance"] = len(out.split()) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%%ci", "HEAD"], - cwd=root)[0].strip() + date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces -def plus_or_dot(pieces): +def plus_or_dot(pieces: Dict[str, Any]) -> str: """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" -def render_pep440(pieces): +def render_pep440(pieces: Dict[str, Any]) -> str: """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you @@ -756,23 +926,71 @@ def render_pep440(pieces): return rendered -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. +def render_pep440_branch(pieces: Dict[str, Any]) -> str: + """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . + + The ".dev0" means not master branch. Note that .dev0 sorts backwards + (a feature branch will appear "older" than the master branch). Exceptions: - 1: no tags. 0.post.devDISTANCE + 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0" + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+untagged.%%d.g%%s" %% (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]: + """Split pep440 version string at the post-release segment. + + Returns the release segments before the post-release and the + post-release version number (or -1 if no post-release segment is present). + """ + vc = str.split(ver, ".post") + return vc[0], int(vc[1] or 0) if len(vc) == 2 else None + + +def render_pep440_pre(pieces: Dict[str, Any]) -> str: + """TAG[.postN.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post0.devDISTANCE + """ + if pieces["closest-tag"]: if pieces["distance"]: - rendered += ".post.dev%%d" %% pieces["distance"] + # update the post release segment + tag_version, post_version = pep440_split_post(pieces["closest-tag"]) + rendered = tag_version + if post_version is not None: + rendered += ".post%%d.dev%%d" %% (post_version + 1, pieces["distance"]) + else: + rendered += ".post0.dev%%d" %% (pieces["distance"]) + else: + # no commits, use the tag as the version + rendered = pieces["closest-tag"] else: # exception #1 - rendered = "0.post.dev%%d" %% pieces["distance"] + rendered = "0.post0.dev%%d" %% pieces["distance"] return rendered -def render_pep440_post(pieces): +def render_pep440_post(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards @@ -799,12 +1017,41 @@ def render_pep440_post(pieces): return rendered -def render_pep440_old(pieces): +def render_pep440_post_branch(pieces: Dict[str, Any]) -> str: + """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . + + The ".dev0" means not master branch. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%%d" %% pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%%s" %% pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0.post%%d" %% pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+g%%s" %% pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_old(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. - Eexceptions: + Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: @@ -821,7 +1068,7 @@ def render_pep440_old(pieces): return rendered -def render_git_describe(pieces): +def render_git_describe(pieces: Dict[str, Any]) -> str: """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. @@ -841,7 +1088,7 @@ def render_git_describe(pieces): return rendered -def render_git_describe_long(pieces): +def render_git_describe_long(pieces: Dict[str, Any]) -> str: """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. @@ -861,7 +1108,7 @@ def render_git_describe_long(pieces): return rendered -def render(pieces, style): +def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", @@ -875,10 +1122,14 @@ def render(pieces, style): if style == "pep440": rendered = render_pep440(pieces) + elif style == "pep440-branch": + rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) + elif style == "pep440-post-branch": + rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": @@ -893,7 +1144,7 @@ def render(pieces, style): "date": pieces.get("date")} -def get_versions(): +def get_versions() -> Dict[str, Any]: """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some @@ -914,7 +1165,7 @@ def get_versions(): # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): + for _ in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, @@ -941,41 +1192,48 @@ def get_versions(): @register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): +def git_get_keywords(versionfile_abs: str) -> Dict[str, str]: """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. - keywords = {} + keywords: Dict[str, str] = {} try: - f = open(versionfile_abs, "r") - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - f.close() - except EnvironmentError: + with open(versionfile_abs, "r") as fobj: + for line in fobj: + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) + if line.strip().startswith("git_date ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["date"] = mo.group(1) + except OSError: pass return keywords @register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): +def git_versions_from_keywords( + keywords: Dict[str, str], + tag_prefix: str, + verbose: bool, +) -> Dict[str, Any]: """Get version information from git keywords.""" - if not keywords: - raise NotThisMethod("no keywords at all, weird") + if "refnames" not in keywords: + raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] + # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because @@ -988,11 +1246,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = set([r.strip() for r in refnames.strip("()").split(",")]) + refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -1001,7 +1259,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) + tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: @@ -1010,6 +1268,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] + # Filter out refs that exactly match prefix or that don't start + # with a number once the prefix is stripped (mostly a concern + # when prefix is '') + if not re.match(r'\d', r): + continue if verbose: print("picking %s" % r) return {"version": r, @@ -1025,7 +1288,12 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): @register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): +def git_pieces_from_vcs( + tag_prefix: str, + root: str, + verbose: bool, + runner: Callable = run_command +) -> Dict[str, Any]: """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* @@ -1036,8 +1304,15 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) + # GIT_DIR can interfere with correct operation of Versioneer. + # It may be intended to be passed to the Versioneer-versioned project, + # but that should not change where we get our version from. + env = os.environ.copy() + env.pop("GIT_DIR", None) + runner = functools.partial(runner, env=env) + + _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, + hide_stderr=not verbose) if rc != 0: if verbose: print("Directory %s not under git control" % root) @@ -1045,24 +1320,57 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%s*" % tag_prefix], - cwd=root) + describe_out, rc = runner(GITS, [ + "describe", "--tags", "--dirty", "--always", "--long", + "--match", f"{tag_prefix}[[:digit:]]*" + ], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() - full_out, rc = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() - pieces = {} + pieces: Dict[str, Any] = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None + branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], + cwd=root) + # --abbrev-ref was added in git-1.6.3 + if rc != 0 or branch_name is None: + raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") + branch_name = branch_name.strip() + + if branch_name == "HEAD": + # If we aren't exactly on a branch, pick a branch which represents + # the current commit. If all else fails, we are on a branchless + # commit. + branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) + # --contains was added in git-1.5.4 + if rc != 0 or branches is None: + raise NotThisMethod("'git branch --contains' returned error") + branches = branches.split("\n") + + # Remove the first line if we're running detached + if "(" in branches[0]: + branches.pop(0) + + # Strip off the leading "* " from the list of branches. + branches = [branch[2:] for branch in branches] + if "master" in branches: + branch_name = "master" + elif not branches: + branch_name = None + else: + # Pick the first branch that is returned. Good or bad. + branch_name = branches[0] + + pieces["branch"] = branch_name + # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out @@ -1079,7 +1387,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: - # unparseable. Maybe git-describe is misbehaving? + # unparsable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces @@ -1104,19 +1412,20 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): else: # HEX: no tags pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) - pieces["distance"] = int(count_out) # total number of commits + out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) + pieces["distance"] = len(out.split()) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], - cwd=root)[0].strip() + date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() + # Use only the last line. Previous lines may contain GPG signature + # information. + date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces -def do_vcs_install(manifest_in, versionfile_source, ipy): +def do_vcs_install(versionfile_source: str, ipy: Optional[str]) -> None: """Git-specific installation logic for Versioneer. For Git, this means creating/changing .gitattributes to mark _version.py @@ -1125,36 +1434,40 @@ def do_vcs_install(manifest_in, versionfile_source, ipy): GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] - files = [manifest_in, versionfile_source] + files = [versionfile_source] if ipy: files.append(ipy) - try: - me = __file__ - if me.endswith(".pyc") or me.endswith(".pyo"): - me = os.path.splitext(me)[0] + ".py" - versioneer_file = os.path.relpath(me) - except NameError: - versioneer_file = "versioneer.py" - files.append(versioneer_file) + if "VERSIONEER_PEP518" not in globals(): + try: + my_path = __file__ + if my_path.endswith((".pyc", ".pyo")): + my_path = os.path.splitext(my_path)[0] + ".py" + versioneer_file = os.path.relpath(my_path) + except NameError: + versioneer_file = "versioneer.py" + files.append(versioneer_file) present = False try: - f = open(".gitattributes", "r") - for line in f.readlines(): - if line.strip().startswith(versionfile_source): - if "export-subst" in line.strip().split()[1:]: - present = True - f.close() - except EnvironmentError: + with open(".gitattributes", "r") as fobj: + for line in fobj: + if line.strip().startswith(versionfile_source): + if "export-subst" in line.strip().split()[1:]: + present = True + break + except OSError: pass if not present: - f = open(".gitattributes", "a+") - f.write("%s export-subst\n" % versionfile_source) - f.close() + with open(".gitattributes", "a+") as fobj: + fobj.write(f"{versionfile_source} export-subst\n") files.append(".gitattributes") run_command(GITS, ["add", "--"] + files) -def versions_from_parentdir(parentdir_prefix, root, verbose): +def versions_from_parentdir( + parentdir_prefix: str, + root: str, + verbose: bool, +) -> Dict[str, Any]: """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both @@ -1163,15 +1476,14 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): """ rootdirs = [] - for i in range(3): + for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} - else: - rootdirs.append(root) - root = os.path.dirname(root) # up a level + rootdirs.append(root) + root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % @@ -1180,7 +1492,7 @@ def versions_from_parentdir(parentdir_prefix, root, verbose): SHORT_VERSION_PY = """ -# This file was generated by 'versioneer.py' (0.18) from +# This file was generated by 'versioneer.py' (0.29) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. @@ -1197,12 +1509,12 @@ def get_versions(): """ -def versions_from_file(filename): +def versions_from_file(filename: str) -> Dict[str, Any]: """Try to determine the version from _version.py if present.""" try: with open(filename) as f: contents = f.read() - except EnvironmentError: + except OSError: raise NotThisMethod("unable to read _version.py") mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) @@ -1214,9 +1526,8 @@ def versions_from_file(filename): return json.loads(mo.group(1)) -def write_to_version_file(filename, versions): +def write_to_version_file(filename: str, versions: Dict[str, Any]) -> None: """Write the given version number to the given _version.py file.""" - os.unlink(filename) contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) with open(filename, "w") as f: @@ -1225,14 +1536,14 @@ def write_to_version_file(filename, versions): print("set %s to '%s'" % (filename, versions["version"])) -def plus_or_dot(pieces): +def plus_or_dot(pieces: Dict[str, Any]) -> str: """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" -def render_pep440(pieces): +def render_pep440(pieces: Dict[str, Any]) -> str: """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you @@ -1257,23 +1568,71 @@ def render_pep440(pieces): return rendered -def render_pep440_pre(pieces): - """TAG[.post.devDISTANCE] -- No -dirty. +def render_pep440_branch(pieces: Dict[str, Any]) -> str: + """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . + + The ".dev0" means not master branch. Note that .dev0 sorts backwards + (a feature branch will appear "older" than the master branch). Exceptions: - 1: no tags. 0.post.devDISTANCE + 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0" + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+untagged.%d.g%s" % (pieces["distance"], + pieces["short"]) + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]: + """Split pep440 version string at the post-release segment. + + Returns the release segments before the post-release and the + post-release version number (or -1 if no post-release segment is present). + """ + vc = str.split(ver, ".post") + return vc[0], int(vc[1] or 0) if len(vc) == 2 else None + + +def render_pep440_pre(pieces: Dict[str, Any]) -> str: + """TAG[.postN.devDISTANCE] -- No -dirty. + + Exceptions: + 1: no tags. 0.post0.devDISTANCE + """ + if pieces["closest-tag"]: if pieces["distance"]: - rendered += ".post.dev%d" % pieces["distance"] + # update the post release segment + tag_version, post_version = pep440_split_post(pieces["closest-tag"]) + rendered = tag_version + if post_version is not None: + rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) + else: + rendered += ".post0.dev%d" % (pieces["distance"]) + else: + # no commits, use the tag as the version + rendered = pieces["closest-tag"] else: # exception #1 - rendered = "0.post.dev%d" % pieces["distance"] + rendered = "0.post0.dev%d" % pieces["distance"] return rendered -def render_pep440_post(pieces): +def render_pep440_post(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards @@ -1300,12 +1659,41 @@ def render_pep440_post(pieces): return rendered -def render_pep440_old(pieces): +def render_pep440_post_branch(pieces: Dict[str, Any]) -> str: + """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . + + The ".dev0" means not master branch. + + Exceptions: + 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] + """ + if pieces["closest-tag"]: + rendered = pieces["closest-tag"] + if pieces["distance"] or pieces["dirty"]: + rendered += ".post%d" % pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += plus_or_dot(pieces) + rendered += "g%s" % pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + else: + # exception #1 + rendered = "0.post%d" % pieces["distance"] + if pieces["branch"] != "master": + rendered += ".dev0" + rendered += "+g%s" % pieces["short"] + if pieces["dirty"]: + rendered += ".dirty" + return rendered + + +def render_pep440_old(pieces: Dict[str, Any]) -> str: """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. - Eexceptions: + Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: @@ -1322,7 +1710,7 @@ def render_pep440_old(pieces): return rendered -def render_git_describe(pieces): +def render_git_describe(pieces: Dict[str, Any]) -> str: """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. @@ -1342,7 +1730,7 @@ def render_git_describe(pieces): return rendered -def render_git_describe_long(pieces): +def render_git_describe_long(pieces: Dict[str, Any]) -> str: """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. @@ -1362,7 +1750,7 @@ def render_git_describe_long(pieces): return rendered -def render(pieces, style): +def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", @@ -1376,10 +1764,14 @@ def render(pieces, style): if style == "pep440": rendered = render_pep440(pieces) + elif style == "pep440-branch": + rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) + elif style == "pep440-post-branch": + rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": @@ -1398,7 +1790,7 @@ class VersioneerBadRootError(Exception): """The project root directory is unknown or missing key files.""" -def get_versions(verbose=False): +def get_versions(verbose: bool = False) -> Dict[str, Any]: """Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'. @@ -1413,7 +1805,7 @@ def get_versions(verbose=False): assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" handlers = HANDLERS.get(cfg.VCS) assert handlers, "unrecognized VCS '%s'" % cfg.VCS - verbose = verbose or cfg.verbose + verbose = verbose or bool(cfg.verbose) # `bool()` used to avoid `None` assert cfg.versionfile_source is not None, \ "please set versioneer.versionfile_source" assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" @@ -1474,13 +1866,17 @@ def get_versions(verbose=False): "date": None} -def get_version(): +def get_version() -> str: """Get the short version string for this project.""" return get_versions()["version"] -def get_cmdclass(): - """Get the custom setuptools/distutils subclasses used by Versioneer.""" +def get_cmdclass(cmdclass: Optional[Dict[str, Any]] = None): + """Get the custom setuptools subclasses used by Versioneer. + + If the package uses a different cmdclass (e.g. one from numpy), it + should be provide as an argument. + """ if "versioneer" in sys.modules: del sys.modules["versioneer"] # this fixes the "python setup.py develop" case (also 'install' and @@ -1494,25 +1890,25 @@ def get_cmdclass(): # parent is protected against the child's "import versioneer". By # removing ourselves from sys.modules here, before the child build # happens, we protect the child from the parent's versioneer too. - # Also see https://github.com/warner/python-versioneer/issues/52 + # Also see https://github.com/python-versioneer/python-versioneer/issues/52 - cmds = {} + cmds = {} if cmdclass is None else cmdclass.copy() - # we add "version" to both distutils and setuptools - from distutils.core import Command + # we add "version" to setuptools + from setuptools import Command class cmd_version(Command): description = "report generated version string" - user_options = [] - boolean_options = [] + user_options: List[Tuple[str, str, str]] = [] + boolean_options: List[str] = [] - def initialize_options(self): + def initialize_options(self) -> None: pass - def finalize_options(self): + def finalize_options(self) -> None: pass - def run(self): + def run(self) -> None: vers = get_versions(verbose=True) print("Version: %s" % vers["version"]) print(" full-revisionid: %s" % vers.get("full-revisionid")) @@ -1522,7 +1918,7 @@ def run(self): print(" error: %s" % vers["error"]) cmds["version"] = cmd_version - # we override "build_py" in both distutils and setuptools + # we override "build_py" in setuptools # # most invocation pathways end up running build_py: # distutils/build -> build_py @@ -1537,18 +1933,25 @@ def run(self): # then does setup.py bdist_wheel, or sometimes setup.py install # setup.py egg_info -> ? + # pip install -e . and setuptool/editable_wheel will invoke build_py + # but the build_py command is not expected to copy any files. + # we override different "build_py" commands for both environments - if "setuptools" in sys.modules: - from setuptools.command.build_py import build_py as _build_py + if 'build_py' in cmds: + _build_py: Any = cmds['build_py'] else: - from distutils.command.build_py import build_py as _build_py + from setuptools.command.build_py import build_py as _build_py class cmd_build_py(_build_py): - def run(self): + def run(self) -> None: root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_py.run(self) + if getattr(self, "editable_mode", False): + # During editable installs `.py` and data files are + # not copied to build_lib + return # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: @@ -1558,8 +1961,40 @@ def run(self): write_to_version_file(target_versionfile, versions) cmds["build_py"] = cmd_build_py + if 'build_ext' in cmds: + _build_ext: Any = cmds['build_ext'] + else: + from setuptools.command.build_ext import build_ext as _build_ext + + class cmd_build_ext(_build_ext): + def run(self) -> None: + root = get_root() + cfg = get_config_from_root(root) + versions = get_versions() + _build_ext.run(self) + if self.inplace: + # build_ext --inplace will only build extensions in + # build/lib<..> dir with no _version.py to write to. + # As in place builds will already have a _version.py + # in the module dir, we do not need to write one. + return + # now locate _version.py in the new build/ directory and replace + # it with an updated value + if not cfg.versionfile_build: + return + target_versionfile = os.path.join(self.build_lib, + cfg.versionfile_build) + if not os.path.exists(target_versionfile): + print(f"Warning: {target_versionfile} does not exist, skipping " + "version update. This can happen if you are running build_ext " + "without first running build_py.") + return + print("UPDATING %s" % target_versionfile) + write_to_version_file(target_versionfile, versions) + cmds["build_ext"] = cmd_build_ext + if "cx_Freeze" in sys.modules: # cx_freeze enabled? - from cx_Freeze.dist import build_exe as _build_exe + from cx_Freeze.dist import build_exe as _build_exe # type: ignore # nczeczulin reports that py2exe won't like the pep440-style string # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. # setup(console=[{ @@ -1568,7 +2003,7 @@ def run(self): # ... class cmd_build_exe(_build_exe): - def run(self): + def run(self) -> None: root = get_root() cfg = get_config_from_root(root) versions = get_versions() @@ -1592,12 +2027,12 @@ def run(self): if 'py2exe' in sys.modules: # py2exe enabled? try: - from py2exe.distutils_buildexe import py2exe as _py2exe # py3 + from py2exe.setuptools_buildexe import py2exe as _py2exe # type: ignore except ImportError: - from py2exe.build_exe import py2exe as _py2exe # py2 + from py2exe.distutils_buildexe import py2exe as _py2exe # type: ignore class cmd_py2exe(_py2exe): - def run(self): + def run(self) -> None: root = get_root() cfg = get_config_from_root(root) versions = get_versions() @@ -1618,14 +2053,51 @@ def run(self): }) cmds["py2exe"] = cmd_py2exe + # sdist farms its file list building out to egg_info + if 'egg_info' in cmds: + _egg_info: Any = cmds['egg_info'] + else: + from setuptools.command.egg_info import egg_info as _egg_info + + class cmd_egg_info(_egg_info): + def find_sources(self) -> None: + # egg_info.find_sources builds the manifest list and writes it + # in one shot + super().find_sources() + + # Modify the filelist and normalize it + root = get_root() + cfg = get_config_from_root(root) + self.filelist.append('versioneer.py') + if cfg.versionfile_source: + # There are rare cases where versionfile_source might not be + # included by default, so we must be explicit + self.filelist.append(cfg.versionfile_source) + self.filelist.sort() + self.filelist.remove_duplicates() + + # The write method is hidden in the manifest_maker instance that + # generated the filelist and was thrown away + # We will instead replicate their final normalization (to unicode, + # and POSIX-style paths) + from setuptools import unicode_utils + normalized = [unicode_utils.filesys_decode(f).replace(os.sep, '/') + for f in self.filelist.files] + + manifest_filename = os.path.join(self.egg_info, 'SOURCES.txt') + with open(manifest_filename, 'w') as fobj: + fobj.write('\n'.join(normalized)) + + cmds['egg_info'] = cmd_egg_info + # we override different "sdist" commands for both environments - if "setuptools" in sys.modules: - from setuptools.command.sdist import sdist as _sdist + if 'sdist' in cmds: + _sdist: Any = cmds['sdist'] else: - from distutils.command.sdist import sdist as _sdist + from setuptools.command.sdist import sdist as _sdist class cmd_sdist(_sdist): - def run(self): + def run(self) -> None: versions = get_versions() self._versioneer_generated_versions = versions # unless we update this, the command will keep using the old @@ -1633,7 +2105,7 @@ def run(self): self.distribution.metadata.version = versions["version"] return _sdist.run(self) - def make_release_tree(self, base_dir, files): + def make_release_tree(self, base_dir: str, files: List[str]) -> None: root = get_root() cfg = get_config_from_root(root) _sdist.make_release_tree(self, base_dir, files) @@ -1686,21 +2158,26 @@ def make_release_tree(self, base_dir, files): """ -INIT_PY_SNIPPET = """ +OLD_SNIPPET = """ from ._version import get_versions __version__ = get_versions()['version'] del get_versions """ +INIT_PY_SNIPPET = """ +from . import {0} +__version__ = {0}.get_versions()['version'] +""" -def do_setup(): - """Main VCS-independent setup function for installing Versioneer.""" + +def do_setup() -> int: + """Do main VCS-independent setup function for installing Versioneer.""" root = get_root() try: cfg = get_config_from_root(root) - except (EnvironmentError, configparser.NoSectionError, + except (OSError, configparser.NoSectionError, configparser.NoOptionError) as e: - if isinstance(e, (EnvironmentError, configparser.NoSectionError)): + if isinstance(e, (OSError, configparser.NoSectionError)): print("Adding sample versioneer config to setup.cfg", file=sys.stderr) with open(os.path.join(root, "setup.cfg"), "a") as f: @@ -1720,62 +2197,37 @@ def do_setup(): ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") + maybe_ipy: Optional[str] = ipy if os.path.exists(ipy): try: with open(ipy, "r") as f: old = f.read() - except EnvironmentError: + except OSError: old = "" - if INIT_PY_SNIPPET not in old: + module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0] + snippet = INIT_PY_SNIPPET.format(module) + if OLD_SNIPPET in old: + print(" replacing boilerplate in %s" % ipy) + with open(ipy, "w") as f: + f.write(old.replace(OLD_SNIPPET, snippet)) + elif snippet not in old: print(" appending to %s" % ipy) with open(ipy, "a") as f: - f.write(INIT_PY_SNIPPET) + f.write(snippet) else: print(" %s unmodified" % ipy) else: print(" %s doesn't exist, ok" % ipy) - ipy = None - - # Make sure both the top-level "versioneer.py" and versionfile_source - # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so - # they'll be copied into source distributions. Pip won't be able to - # install the package without this. - manifest_in = os.path.join(root, "MANIFEST.in") - simple_includes = set() - try: - with open(manifest_in, "r") as f: - for line in f: - if line.startswith("include "): - for include in line.split()[1:]: - simple_includes.add(include) - except EnvironmentError: - pass - # That doesn't cover everything MANIFEST.in can do - # (http://docs.python.org/2/distutils/sourcedist.html#commands), so - # it might give some false negatives. Appending redundant 'include' - # lines is safe, though. - if "versioneer.py" not in simple_includes: - print(" appending 'versioneer.py' to MANIFEST.in") - with open(manifest_in, "a") as f: - f.write("include versioneer.py\n") - else: - print(" 'versioneer.py' already in MANIFEST.in") - if cfg.versionfile_source not in simple_includes: - print(" appending versionfile_source ('%s') to MANIFEST.in" % - cfg.versionfile_source) - with open(manifest_in, "a") as f: - f.write("include %s\n" % cfg.versionfile_source) - else: - print(" versionfile_source already in MANIFEST.in") + maybe_ipy = None # Make VCS-specific changes. For git, this means creating/changing # .gitattributes to mark _version.py for export-subst keyword # substitution. - do_vcs_install(manifest_in, cfg.versionfile_source, ipy) + do_vcs_install(cfg.versionfile_source, maybe_ipy) return 0 -def scan_setup_py(): +def scan_setup_py() -> int: """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False @@ -1812,10 +2264,14 @@ def scan_setup_py(): return errors +def setup_command() -> NoReturn: + """Set up Versioneer and exit with appropriate error code.""" + errors = do_setup() + errors += scan_setup_py() + sys.exit(1 if errors else 0) + + if __name__ == "__main__": cmd = sys.argv[1] if cmd == "setup": - errors = do_setup() - errors += scan_setup_py() - if errors: - sys.exit(1) + setup_command()