From 7b96947b3b2a8864b203a164ea6a52845c45caaf Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:24:30 -0700 Subject: [PATCH 01/30] MNT: updating LICENSE from template Performed by pcds-migration-tools AddFileFromTemplate --- LICENSE.md | 40 ++++++++++++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/LICENSE.md b/LICENSE.md index 9274422..e14da2c 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,11 +1,39 @@ -Copyright (c) 2022, The Board of Trustees of the Leland Stanford Junior University, through SLAC National Accelerator Laboratory (subject to receipt of any required approvals from the U.S. Dept. of Energy). All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: +Copyright (c) 2023, The Board of Trustees of the Leland Stanford Junior +University, through SLAC National Accelerator Laboratory (subject to receipt +of any required approvals from the U.S. Dept. of Energy). 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 Leland Stanford Junior University, SLAC National Accelerator Laboratory, U.S. Dept. of Energy 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 Leland Stanford Junior University, SLAC National + Accelerator Laboratory, U.S. Dept. of Energy 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 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER, THE UNITED STATES GOVERNMENT, OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER, THE UNITED STATES GOVERNMENT, +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT +OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING +IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY +OF SUCH DAMAGE. -You are under no obligation whatsoever to provide any bug fixes, patches, or upgrades to the features, functionality or performance of the source code ("Enhancements") to anyone; however, if you choose to make your Enhancements available either publicly, or directly to SLAC National Accelerator Laboratory, without imposing a separate written license agreement for such Enhancements, then you hereby grant the following license: a non-exclusive, royalty-free perpetual license to install, use, modify, prepare derivative works, incorporate into other computer software, distribute, and sublicense such Enhancements or derivative works thereof, in binary and source code form. +You are under no obligation whatsoever to provide any bug fixes, patches, or +upgrades to the features, functionality or performance of the source code +("Enhancements") to anyone; however, if you choose to make your Enhancements +available either publicly, or directly to SLAC National Accelerator Laboratory, +without imposing a separate written license agreement for such Enhancements, +then you hereby grant the following license: a non-exclusive, royalty-free +perpetual license to install, use, modify, prepare derivative works, incorporate +into other computer software, distribute, and sublicense such Enhancements or +derivative works thereof, in binary and source code form. From c2b8df8ddc55ad894df2f699fceb2e2234dc1096 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:24:30 -0700 Subject: [PATCH 02/30] MNT: updating AUTHORS.rst from template Performed by pcds-migration-tools AddFileFromTemplate --- AUTHORS.rst | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 AUTHORS.rst diff --git a/AUTHORS.rst b/AUTHORS.rst new file mode 100644 index 0000000..a99ffb4 --- /dev/null +++ b/AUTHORS.rst @@ -0,0 +1,13 @@ +======= +Credits +======= + +Maintainer +---------- + +* SLAC National Accelerator Laboratory <> + +Contributors +------------ + +Interested? See: `CONTRIBUTING.rst `_ From 2fae7b364fd88084b80dfef50d3dd2ee059975b3 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:24:30 -0700 Subject: [PATCH 03/30] MNT: updating CONTRIBUTING.rst from template Performed by pcds-migration-tools AddFileFromTemplate --- CONTRIBUTING.rst | 103 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 CONTRIBUTING.rst diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst new file mode 100644 index 0000000..6ef63b6 --- /dev/null +++ b/CONTRIBUTING.rst @@ -0,0 +1,103 @@ +============ +Contributing +============ + +Contributions are welcome, and they are greatly appreciated! Every little bit +helps, and credit will always be given. + +You can contribute in many ways: + +Types of Contributions +---------------------- + +Report Bugs +~~~~~~~~~~~ + +Report bugs at https://github.com/pcdshub/jet_tracking/issues. + +If you are reporting a bug, please include: + +* Any details about your local setup that might be helpful in troubleshooting. +* Detailed steps to reproduce the bug. + +Fix Bugs +~~~~~~~~ + +Look through the GitHub issues for bugs. Anything tagged with "bug" +is open to whoever wants to implement it. + +Implement Features +~~~~~~~~~~~~~~~~~~ + +Look through the GitHub issues for features. Anything tagged with "feature" +is open to whoever wants to implement it. + +Write Documentation +~~~~~~~~~~~~~~~~~~~ + +jet_tracking could always use more documentation, whether +as part of the official jet_tracking docs, in docstrings, +or even on the web in blog posts, articles, and such. + +Submit Feedback +~~~~~~~~~~~~~~~ + +The best way to send feedback is to file an issue at https://github.com/pcdshub/jet_tracking/issues. + +If you are proposing a feature: + +* Explain in detail how it would work. +* Keep the scope as narrow as possible, to make it easier to implement. +* Remember that this is a volunteer-driven project, and that contributions + are welcome :) + +Get Started! +------------ + +Ready to contribute? Here's how to set up `jet_tracking` for local development. + +1. Fork the `jet_tracking` repo on GitHub. +2. Clone your fork locally:: + + $ git clone git@github.com:your_name_here/jet_tracking.git + +3. Install your local copy into a new conda environment. Assuming you have conda installed, this is how you set up your fork for local development:: + + $ conda create -n jet_tracking python=3.9 pip + $ cd jet_tracking/ + $ pip install -e . + +4. Create a branch for local development:: + + $ git checkout -b name-of-your-bugfix-or-feature + + Now you can make your changes locally. + +5. Install and enable ``pre-commit`` for this repository:: + + $ pip install pre-commit + $ pre-commit install + +6. Add new tests for any additional functionality or bugs you may have discovered. And, of course, be sure that all previous tests still pass by running:: + + $ pytest -v + +7. Commit your changes and push your branch to GitHub:: + + $ git add . + $ git commit -m "Your detailed description of your changes." + $ git push origin name-of-your-bugfix-or-feature + +8. Submit a pull request through the GitHub website. + +Pull Request Guidelines +----------------------- + +Before you submit a pull request, check that it meets these guidelines: + +1. The pull request should include tests. +2. If the pull request adds functionality, the docs should be updated. Put your + new functionality into a function with a docstring, and add the feature to + the list in README.rst. +3. The pull request should work for Python 3.9 and up. Check the GitHub Actions status + and make sure that the tests pass for all supported Python versions. From 5f0883098a4f4dee4058619ed6ce87035bc1ee0e Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:24:30 -0700 Subject: [PATCH 04/30] MNT: updating .pre-commit-config.yaml from template Performed by pcds-migration-tools AddFileFromTemplate --- .pre-commit-config.yaml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index bf42b4b..712f148 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,8 +1,13 @@ # See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks +exclude: | + (?x)^( + jet_tracking/_version.py| + )$ + repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v3.3.0 + rev: v4.4.0 hooks: - id: no-commit-to-branch - id: trailing-whitespace @@ -18,11 +23,11 @@ repos: - id: debug-statements - repo: https://github.com/pycqa/flake8.git - rev: 3.8.4 + rev: 6.0.0 hooks: - id: flake8 - repo: https://github.com/timothycrosley/isort - rev: 5.6.4 + rev: 5.11.4 hooks: - id: isort From 8ec4f31c92eaaf986d4767f3414db4bf97d9871c Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:24:30 -0700 Subject: [PATCH 05/30] MNT: updating .flake8 from template Performed by pcds-migration-tools AddFileFromTemplate --- .flake8 | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 .flake8 diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..ebf1480 --- /dev/null +++ b/.flake8 @@ -0,0 +1,23 @@ +[flake8] +exclude = .git,__pycache__,build,dist,jet_tracking/_version.py +max-line-length = 88 +select = C,E,F,W,B,B950 +extend-ignore = E203, E501, E226, W503, W504 + +# Explanation section: +# B950 +# This takes into account max-line-length but only triggers when the value +# has been exceeded by more than 10% (96 characters). +# E203: Whitespace before ':' +# This is recommended by black in relation to slice formatting. +# E501: Line too long (82 > 79 characters) +# Our line length limit is 88 (above 79 defined in E501). Ignore it. +# E226: Missing whitespace around arithmetic operator +# This is a stylistic choice which you'll find everywhere in pcdsdevices, for +# example. Formulas can be easier to read when operators and operands +# have no whitespace between them. +# +# W503: Line break occurred before a binary operator +# W504: Line break occurred after a binary operator +# flake8 wants us to choose one of the above two. Our choice +# is to make no decision. From 88bdee7727113015ad2ad883e1bff779e49606ec Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:24:30 -0700 Subject: [PATCH 06/30] MNT: updating .coveragerc from template Performed by pcds-migration-tools AddFileFromTemplate --- .coveragerc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.coveragerc b/.coveragerc index 5d2c091..08912ec 100644 --- a/.coveragerc +++ b/.coveragerc @@ -3,9 +3,9 @@ source = jet_tracking [report] omit = - #tests - */tests/* - *test* #versioning .*version.* *_version.py + #tests + *test* + jet_tracking/tests/* From db45ac288070cc1abaaa2bb3cd196a717e4dd191 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:24:30 -0700 Subject: [PATCH 07/30] MNT: updating .git_archival.txt from template Performed by pcds-migration-tools AddFileFromTemplate --- .git_archival.txt | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .git_archival.txt diff --git a/.git_archival.txt b/.git_archival.txt new file mode 100644 index 0000000..8fb235d --- /dev/null +++ b/.git_archival.txt @@ -0,0 +1,4 @@ +node: $Format:%H$ +node-date: $Format:%cI$ +describe-name: $Format:%(describe:tags=true,match=*[0-9]*)$ +ref-names: $Format:%D$ From d278d699d8d991216f26dcc733bc8fab39234691 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:24:30 -0700 Subject: [PATCH 08/30] MNT: updating .gitattributes from template Performed by pcds-migration-tools AddFileFromTemplate --- .gitattributes | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitattributes b/.gitattributes index 0b880e3..00a7b00 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1 @@ -jet_tracking/_version.py export-subst +.git_archival.txt export-subst From 0c2f941b48de49333a62d8d0ffc2a3f39cf417f2 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:24:30 -0700 Subject: [PATCH 09/30] CI: migrate to GitHub actions Performed by pcds-migration-tools GitHubActionsMigration --- .github/workflows/standard.yml | 24 ++++++++++++++++++++++++ .travis.yml | 32 -------------------------------- 2 files changed, 24 insertions(+), 32 deletions(-) create mode 100644 .github/workflows/standard.yml delete mode 100644 .travis.yml diff --git a/.github/workflows/standard.yml b/.github/workflows/standard.yml new file mode 100644 index 0000000..a5f482f --- /dev/null +++ b/.github/workflows/standard.yml @@ -0,0 +1,24 @@ +name: PCDS Standard Testing + +on: + push: + pull_request: + release: + types: + - published + +jobs: + standard: + uses: pcdshub/pcds-ci-helpers/.github/workflows/python-standard.yml@master + with: + # The workflow needs to know the package name. This can be determined + # automatically if the repository name is the same as the import name. + package-name: "jet_tracking" + # Extras that will be installed for both conda/pip: + testing-extras: "" + # Extras to be installed only for conda-based testing: + conda-testing-extras: "" + # Extras to be installed only for pip-based testing: + pip-testing-extras: "PyQt5" + # Set if using setuptools-scm for the conda-build workflow + use-setuptools-scm: true diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 99d6060..0000000 --- a/.travis.yml +++ /dev/null @@ -1,32 +0,0 @@ -version: ~> 1.0 - -env: - global: - - OFFICIAL_REPO="pcdshub/jet_tracking" - # Doctr deploy key for pcdshub/jet_tracking - - secure: "V2DzajEtsKUl0+J4pziJWuGPQ4q4kUdKs0V7xIdDxnzO6RmuI49tulurfr/HwMa1Euitiuc1SfIpA+rbaPs0xysbZWAG2mpqT7s/RvFZ/+/rTKp/4GZkH8hvS7/8INQTFImwpHUWiG1L+3sv9+3SM0h3CorvWsBnknIkllHu7Qh2dqfW0bK7bgSjn2wGkgoP53QF3BQne08U2n7mMkD0stibzZCODPwUMNNJYDSa/4yjyPO0DOEVFs7iox3ToZ352OFKHsMO+awcMCFN8gP/c7Al+xp4IBGLX0s4U0AQGru+JqKae3zwukq2pDyWWgieH5QpAfm/Ht7KKH4hnzGtj9AL81dC9RkXDLV3iSN0SNPrVlrjJNnQi9gTxsXHd2NwVF0kXgo+7oX/zoEpIn+Z6wfOfseO+KFFFYYz3ASKS1U8UZo5qyAcCFPHl0T0WEcYZVvfre1GQkpRRVnNvfJdEAN2rWMi+ovKcVnH8rhc4uPwxdR5vSAcI1xKJMS7OUI0edAm2LvIOh4+ri2et5WR4ulhpaVm5/iDBxqYaz/vGWy+vu+Q9UzrZuGP4igt+SqMMlXkrAaJhAURaKSnqOiVUZI4JCeQ+0f88N2SkupsYAjIc040tEKsBaLgjBL1BnouR1owGwBqv6yeMail8nW0HBRZMGyH/SI4ZvK/HCWBGMg=" - # enable the usage of versions menu which allow versioning of the docs - # pages and not only the master branch - - DOCTR_VERSIONS_MENU="1" - # The name of the conda package - - CONDA_PACKAGE="jet_tracking" - # The folder containing the conda recipe (meta.yaml) - - CONDA_RECIPE_FOLDER="conda-recipe" - # Extra dependencies needed to run the test with Pip - - PIP_EXTRAS="PyQt5" - -import: - # This import enables a set of standard python jobs including: - # - Build - # - Anaconda Package Build - # - Tests - # - Python Linter - # - Package Linter - # - Documentation - # - Python 3.6 - PIP based - # - Python 3.6, 3.7 & 3.8 - Conda base - # - Deploy - # - Documentation using doctr - # - Conda Package - uploaded to pcds-dev and pcds-tag - # - PyPI - - pcdshub/pcds-ci-helpers:travis/shared_configs/standard-python-conda-latest.yml From e20778eff54dfa859c0a3b9476a0ea6572c91dc7 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:24:31 -0700 Subject: [PATCH 10/30] DOC: update Sphinx configuration Performed by pcds-migration-tools UpdateSphinx --- docs-requirements.txt | 1 + docs/source/conf.py | 87 ++++++++++++++++++++++++------------------- 2 files changed, 50 insertions(+), 38 deletions(-) diff --git a/docs-requirements.txt b/docs-requirements.txt index 2c2ff50..78a6c7a 100644 --- a/docs-requirements.txt +++ b/docs-requirements.txt @@ -7,3 +7,4 @@ sphinx sphinx_rtd_theme doctr doctr-versions-menu +sphinxcontrib-jquery diff --git a/docs/source/conf.py b/docs/source/conf.py index 6b484a0..7f9159e 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -25,9 +25,8 @@ # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # -module_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'../../') -sys.path.insert(0,module_path) - +module_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../") +sys.path.insert(0, module_path) # -- General configuration ------------------------------------------------ @@ -39,18 +38,21 @@ # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. -extensions = ['sphinx.ext.autodoc', - 'sphinx.ext.todo', - 'sphinx.ext.napoleon', - 'sphinx.ext.autosummary', - 'sphinx.ext.viewcode', - 'sphinx.ext.doctest', - 'sphinx.ext.viewcode', - 'sphinx.ext.githubpages', - 'sphinx.ext.intersphinx'] +extensions = [ + "sphinxcontrib.jquery", + "sphinx.ext.autodoc", + "sphinx.ext.todo", + "sphinx.ext.napoleon", + "sphinx.ext.autosummary", + "sphinx.ext.viewcode", + "sphinx.ext.doctest", + "sphinx.ext.viewcode", + "sphinx.ext.githubpages", + "sphinx.ext.intersphinx", +] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] autosummary_generate = True @@ -61,35 +63,35 @@ # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] -source_suffix = '.rst' +source_suffix = ".rst" # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = 'PCDS Jet Tracking' +project = "PCDS Jet Tracking" year = datetime.datetime.now().year -copyright = '{}, SLAC National Accelerator Laboratory'.format(year) -author = 'SLAC National Accelerator Laboratory' +copyright = "{}, SLAC National Accelerator Laboratory".format(year) +author = "SLAC National Accelerator Laboratory" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = jet_tracking.__version__ +version = str(jet_tracking.__version__) # The full version, including alpha/beta/rc tags. -release = jet_tracking.__version__ +release = str(jet_tracking.__version__) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. -language = None +language = "en" # The reST default role (used for this markup: `text`) -default_role = 'any' +default_role = "any" # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. @@ -97,7 +99,7 @@ exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False @@ -108,7 +110,7 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -html_theme = 'sphinx_rtd_theme' +html_theme = "sphinx_rtd_theme" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the @@ -128,7 +130,7 @@ # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. -htmlhelp_basename = 'jet_trackingdoc' +htmlhelp_basename = "jet_trackingdoc" # -- Options for LaTeX output --------------------------------------------- @@ -137,15 +139,12 @@ # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. # # 'preamble': '', - # Latex figure (float) alignment # # 'figure_align': 'htbp', @@ -155,8 +154,13 @@ # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'jet_tracking.tex', 'PCDS Jet Tracking Documentation', - 'SLAC National Accelerator Laboratory', 'manual'), + ( + master_doc, + "jet_tracking.tex", + "PCDS Jet Tracking Documentation", + "SLAC National Accelerator Laboratory", + "manual", + ), ] @@ -165,8 +169,7 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, 'jet_tracking', 'PCDS Jet Tracking Documentation', - [author], 1) + (master_doc, "jet_tracking", "PCDS Jet Tracking Documentation", [author], 1) ] @@ -176,13 +179,21 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'jet_tracking', 'PCDS Jet Tracking Documentation', - author, 'jet_tracking', 'Liquid jet positioning feedback and tracking.', - 'Miscellaneous'), + ( + master_doc, + "jet_tracking", + "PCDS Jet Tracking Documentation", + author, + "jet_tracking", + "Liquid jet positioning feedback and tracking.", + "Miscellaneous", + ), ] # -- Sources of external documentation to cross-referencing---------------- -intersphinx_mapping = {'ophyd': ('https://blueskyproject.io/ophyd', None), - 'python': ('https://docs.python.org/3', None), - 'numpy': ('https://numpy.org/doc/stable', None)} +intersphinx_mapping = { + "ophyd": ("https://blueskyproject.io/ophyd", None), + "python": ("https://docs.python.org/3", None), + "numpy": ("https://numpy.org/doc/stable", None), +} From 4eaeeab8a05008cf0a93bed222c75a09828344df Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:24:32 -0700 Subject: [PATCH 11/30] STY: update repository to Python 3.9+ standards Performed by pcds-migration-tools RunPyupgrade --- docs/source/conf.py | 3 +- jet_tracking/context.py | 2 +- jet_tracking/datastream.py | 4 +-- jet_tracking/gui/views/jetImageView.py | 2 +- jet_tracking/gui/views/jetTrackerView.py | 2 +- jet_tracking/gui/views/simultationView.py | 2 +- jet_tracking/gui/widgets/basicWidgets.py | 12 +++---- jet_tracking/gui/widgets/controlWidget.py | 2 +- jet_tracking/gui/widgets/controlWidgetUi.py | 2 +- jet_tracking/gui/widgets/editorWidget.py | 2 +- jet_tracking/gui/widgets/editorWidgetUi.py | 2 +- jet_tracking/gui/widgets/graphWidget.py | 2 +- jet_tracking/gui/widgets/graphWidgetUi.py | 2 +- jet_tracking/gui/widgets/jetImageWidget.py | 4 +-- jet_tracking/gui/widgets/simControlWidget.py | 2 +- .../gui/widgets/simControlWidgetUi.py | 2 +- jet_tracking/gui/windows/mainWindow.py | 2 +- jet_tracking/gui/windows/mainWindowUi.py | 2 +- jet_tracking/gui/windows/simWindowUi.py | 2 +- jet_tracking/gui/windows/simulationWindow.py | 2 +- jet_tracking/jetGraphing.py | 2 +- jet_tracking/jet_tracking_cal/jt_cal.py | 32 +++++++++---------- jet_tracking/main.py | 2 +- jet_tracking/motorMoving.py | 2 +- jet_tracking/mpi_scripts/mpi_driver.py | 2 +- jet_tracking/mpi_scripts/mpi_master.py | 6 ++-- jet_tracking/mpi_scripts/mpi_worker.py | 4 +-- jet_tracking/sketch/simJetImage.py | 2 +- jet_tracking/tools/ROI.py | 2 +- jet_tracking/tools/motorAlgorithm.py | 8 ++--- jet_tracking/tools/numGen.py | 2 +- jet_tracking/tools/simMotorMoving.py | 2 +- 32 files changed, 60 insertions(+), 61 deletions(-) diff --git a/docs/source/conf.py b/docs/source/conf.py index 7f9159e..32cea09 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -# -*- coding: utf-8 -*- # # PCDS Devices documentation build configuration file, created by # sphinx-quickstart on Mon Apr 3 21:34:53 2017. @@ -71,7 +70,7 @@ # General information about the project. project = "PCDS Jet Tracking" year = datetime.datetime.now().year -copyright = "{}, SLAC National Accelerator Laboratory".format(year) +copyright = f"{year}, SLAC National Accelerator Laboratory" author = "SLAC National Accelerator Laboratory" # The version info for the project you're documenting, acts as replacement for diff --git a/jet_tracking/context.py b/jet_tracking/context.py index 152b2de..3070000 100644 --- a/jet_tracking/context.py +++ b/jet_tracking/context.py @@ -10,7 +10,7 @@ log = logging.getLogger("jet_tracker") -class Context(object): +class Context: """ The Context class represents the context or environment in which the application operates. It stores various settings, configurations, and data related to the application's functionality. diff --git a/jet_tracking/datastream.py b/jet_tracking/datastream.py index a3d11a8..1e642d7 100644 --- a/jet_tracking/datastream.py +++ b/jet_tracking/datastream.py @@ -30,7 +30,7 @@ def __call__(cls, *args, **kwargs): if cls not in cls._instances: with lock: if cls not in cls._instances: - cls._instances[cls] = super(Singleton, cls).__call__( + cls._instances[cls] = super().__call__( *args, **kwargs) return cls._instances[cls] @@ -896,7 +896,7 @@ def __init__(self, signals): Args: signals (object): The signals object for emitting signals. """ - super(EventProcessor, self).__init__() + super().__init__() self.signals = signals self.flag_type = {} self.isCounting = False diff --git a/jet_tracking/gui/views/jetImageView.py b/jet_tracking/gui/views/jetImageView.py index 1d7c170..fa7e98a 100644 --- a/jet_tracking/gui/views/jetImageView.py +++ b/jet_tracking/gui/views/jetImageView.py @@ -10,7 +10,7 @@ class JetImageView(QWidget): def __init__(self, context, signals): - super(JetImageView, self).__init__() + super().__init__() self.signals = signals self.context = context self.camera = "" diff --git a/jet_tracking/gui/views/jetTrackerView.py b/jet_tracking/gui/views/jetTrackerView.py index 5c64aa1..c9163c5 100644 --- a/jet_tracking/gui/views/jetTrackerView.py +++ b/jet_tracking/gui/views/jetTrackerView.py @@ -31,7 +31,7 @@ def __init__(self, context, signals, parent=None): Adds the controlsDock and graphWidget to the mainLayout. Sets the layout of the widget using the setLayout method. """ - super(JetTrackerView, self).__init__(parent) + super().__init__(parent) self.signals = signals self.context = context self.parent = parent diff --git a/jet_tracking/gui/views/simultationView.py b/jet_tracking/gui/views/simultationView.py index d9b88bd..2fe202f 100644 --- a/jet_tracking/gui/views/simultationView.py +++ b/jet_tracking/gui/views/simultationView.py @@ -5,7 +5,7 @@ class SimulationView(QWidget): def __init__(self, context, signals, parent=None): - super(SimulationView, self).__init__(parent) + super().__init__(parent) self.signals = signals self.context = context self.parent = parent diff --git a/jet_tracking/gui/widgets/basicWidgets.py b/jet_tracking/gui/widgets/basicWidgets.py index e1f9d99..73e9ead 100644 --- a/jet_tracking/gui/widgets/basicWidgets.py +++ b/jet_tracking/gui/widgets/basicWidgets.py @@ -13,7 +13,7 @@ class LineEdit(QLineEdit): checkVal = pyqtSignal(float) def __init__(self, *args, **kwargs): - super(LineEdit, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.validator = QDoubleValidator() self.setValidator(self.validator) self.textChanged.connect(self.new_text) @@ -48,7 +48,7 @@ def valRange(self, x1, x2): class CollapsibleBox(QWidget): def __init__(self, title="", parent=None): - super(CollapsibleBox, self).__init__(parent) + super().__init__(parent) self.toggle_button = QToolButton( text=title, checkable=True, checked=False ) @@ -143,7 +143,7 @@ def setContentLayout(self, layout): class Label(QLabel): def __init__(self, parent=None): - super(Label, self).__init__(parent) + super().__init__(parent) def setTitleStylesheet(self): self.setStyleSheet("\ @@ -182,14 +182,14 @@ def setTrackingStylesheet(self): class QHLine(QFrame): def __init__(self): - super(QHLine, self).__init__() + super().__init__() self.setFrameShape(QFrame.HLine) self.setFrameShadow(QFrame.Sunken) class QVLine(QFrame): def __init__(self): - super(QVLine, self).__init__() + super().__init__() self.setFrameShape(QFrame.VLine) self.setFrameShadow(QFrame.Sunken) @@ -245,7 +245,7 @@ class QRangeSlider(QWidget): def __init__(self, parent=None, left_value=0, right_value=255, left_thumb_value=0, right_thumb_value=255): - super(QRangeSlider, self).__init__(parent) + super().__init__(parent) self.setSizePolicy( QSizePolicy.Preferred, diff --git a/jet_tracking/gui/widgets/controlWidget.py b/jet_tracking/gui/widgets/controlWidget.py index 4f7b3dd..e188fc8 100644 --- a/jet_tracking/gui/widgets/controlWidget.py +++ b/jet_tracking/gui/widgets/controlWidget.py @@ -25,7 +25,7 @@ def __init__(self, context, signals): signals: The signals object for emitting and receiving signals. """ - super(ControlsWidget, self).__init__() + super().__init__() log.debug("Supplying Thread information from init of Controls Widget") self.signals = signals self.context = context diff --git a/jet_tracking/gui/widgets/controlWidgetUi.py b/jet_tracking/gui/widgets/controlWidgetUi.py index 5ca3eb2..e06c95a 100644 --- a/jet_tracking/gui/widgets/controlWidgetUi.py +++ b/jet_tracking/gui/widgets/controlWidgetUi.py @@ -5,7 +5,7 @@ QSizePolicy, QTextEdit, QVBoxLayout, QComboBox) -class Controls_Ui(object): +class Controls_Ui: def setupUi(self, obj): ##################################################################### diff --git a/jet_tracking/gui/widgets/editorWidget.py b/jet_tracking/gui/widgets/editorWidget.py index 4fc2109..7f775e7 100644 --- a/jet_tracking/gui/widgets/editorWidget.py +++ b/jet_tracking/gui/widgets/editorWidget.py @@ -12,7 +12,7 @@ class EditorWidget(QFrame, Editor_Ui): def __init__(self, context, signals): - super(EditorWidget, self).__init__() + super().__init__() self.signals = signals self.context = context self.setupUi(self) diff --git a/jet_tracking/gui/widgets/editorWidgetUi.py b/jet_tracking/gui/widgets/editorWidgetUi.py index 3449431..55ce0ec 100644 --- a/jet_tracking/gui/widgets/editorWidgetUi.py +++ b/jet_tracking/gui/widgets/editorWidgetUi.py @@ -4,7 +4,7 @@ QSlider, QVBoxLayout, QButtonGroup, QTextEdit) -class Editor_Ui(object): +class Editor_Ui: def setupUi(self, obj): """ diff --git a/jet_tracking/gui/widgets/graphWidget.py b/jet_tracking/gui/widgets/graphWidget.py index 1829b77..aecc42e 100644 --- a/jet_tracking/gui/widgets/graphWidget.py +++ b/jet_tracking/gui/widgets/graphWidget.py @@ -15,7 +15,7 @@ class GraphsWidget(QFrame, GraphsUi): def __init__(self, context, signals): - super(GraphsWidget, self).__init__() + super().__init__() self.signals = signals self.context = context self.setupUi(self) diff --git a/jet_tracking/gui/widgets/graphWidgetUi.py b/jet_tracking/gui/widgets/graphWidgetUi.py index 5209278..e9b57ea 100644 --- a/jet_tracking/gui/widgets/graphWidgetUi.py +++ b/jet_tracking/gui/widgets/graphWidgetUi.py @@ -3,7 +3,7 @@ from PyQt5.QtWidgets import QVBoxLayout -class GraphsUi(object): +class GraphsUi: def setupUi(self, obj): """ used to setup the layout and initialize graphs diff --git a/jet_tracking/gui/widgets/jetImageWidget.py b/jet_tracking/gui/widgets/jetImageWidget.py index 190d1ef..8d0d7ec 100644 --- a/jet_tracking/gui/widgets/jetImageWidget.py +++ b/jet_tracking/gui/widgets/jetImageWidget.py @@ -13,7 +13,7 @@ class JetImageWidget(QGraphicsView): def __init__(self, context, signals): - super(JetImageWidget, self).__init__() + super().__init__() log.debug("Supplying Thread information from init of jetImageWidget") self.signals = signals self.context = context @@ -125,4 +125,4 @@ def resizeEvent(self, event): self.fitInView(self.line_item_vert_left, Qt.KeepAspectRatio) self.fitInView(self.line_item_hor_bot, Qt.KeepAspectRatio) self.fitInView(self.line_item_vert_right, Qt.KeepAspectRatio) - super(JetImageWidget, self).resizeEvent(event) + super().resizeEvent(event) diff --git a/jet_tracking/gui/widgets/simControlWidget.py b/jet_tracking/gui/widgets/simControlWidget.py index ed8c7df..51749af 100644 --- a/jet_tracking/gui/widgets/simControlWidget.py +++ b/jet_tracking/gui/widgets/simControlWidget.py @@ -9,7 +9,7 @@ class SimWidget(QFrame, SimUi): def __init__(self, context, signals): - super(SimWidget, self).__init__() + super().__init__() self.signals = signals self.context = context self.setupUi(self) diff --git a/jet_tracking/gui/widgets/simControlWidgetUi.py b/jet_tracking/gui/widgets/simControlWidgetUi.py index ad7c34b..521b294 100644 --- a/jet_tracking/gui/widgets/simControlWidgetUi.py +++ b/jet_tracking/gui/widgets/simControlWidgetUi.py @@ -3,7 +3,7 @@ QVBoxLayout) -class SimUi(object): +class SimUi: def setupUi(self, obj): """ diff --git a/jet_tracking/gui/windows/mainWindow.py b/jet_tracking/gui/windows/mainWindow.py index ac0a886..3a83e90 100644 --- a/jet_tracking/gui/windows/mainWindow.py +++ b/jet_tracking/gui/windows/mainWindow.py @@ -44,7 +44,7 @@ def __init__(self): jetTrackerView (class): connects the first tab view to the main window jetImageView (class): connects the second tab view to the main window """ - super(MainWindow, self).__init__() + super().__init__() log.debug("Supplying Thread information from init of MainWindow.") self.setAttribute(Qt.WA_AlwaysStackOnTop) self.setMinimumSize(QSize(700, 300)) diff --git a/jet_tracking/gui/windows/mainWindowUi.py b/jet_tracking/gui/windows/mainWindowUi.py index ea3ee8e..2afbc99 100644 --- a/jet_tracking/gui/windows/mainWindowUi.py +++ b/jet_tracking/gui/windows/mainWindowUi.py @@ -1,7 +1,7 @@ from PyQt5.QtWidgets import QMenuBar -class Ui_MainWindow(object): +class Ui_MainWindow: """This class represents the user interface (UI) definition for the main window of the application.""" def setupUi(self, obj): """ diff --git a/jet_tracking/gui/windows/simWindowUi.py b/jet_tracking/gui/windows/simWindowUi.py index 97c2a27..0b06b5f 100644 --- a/jet_tracking/gui/windows/simWindowUi.py +++ b/jet_tracking/gui/windows/simWindowUi.py @@ -1,7 +1,7 @@ from PyQt5.QtCore import QSize -class SimWindow_Ui(object): +class SimWindow_Ui: def setupUi(self, obj): obj.setMinimumSize(self.minimumSizeHint()) obj.setObjectName("Simulation Tools") diff --git a/jet_tracking/gui/windows/simulationWindow.py b/jet_tracking/gui/windows/simulationWindow.py index fe30280..7038c7e 100644 --- a/jet_tracking/gui/windows/simulationWindow.py +++ b/jet_tracking/gui/windows/simulationWindow.py @@ -18,7 +18,7 @@ def __init__(self, context, signals): signals: the signals class """ - super(SimWindow, self).__init__() + super().__init__() self.signals = signals self.context = context self.setupUi(self) diff --git a/jet_tracking/jetGraphing.py b/jet_tracking/jetGraphing.py index 2754aa9..e0be8fc 100644 --- a/jet_tracking/jetGraphing.py +++ b/jet_tracking/jetGraphing.py @@ -27,7 +27,7 @@ def add_calibration_graph(graph): class ScrollingTimeWidget(pg.PlotWidget): def __init__(self, context, signals, parent=None): - super(ScrollingTimeWidget, self).__init__(parent) + super().__init__(parent) self.context = context self.signals = signals self.setMouseEnabled(x=False, y=False) diff --git a/jet_tracking/jet_tracking_cal/jt_cal.py b/jet_tracking/jet_tracking_cal/jt_cal.py index 4befd73..23173bb 100644 --- a/jet_tracking/jet_tracking_cal/jt_cal.py +++ b/jet_tracking/jet_tracking_cal/jt_cal.py @@ -249,8 +249,8 @@ def peak_fig(signal, hist, edges, med, low, high): """General histogram plotter with peak location and left/right limits plotted""" fig = figure( - title='Used Intensity Distribution for {0}. \ - Low/Hi: {1}/{2}'.format(signal, low, high), + title='Used Intensity Distribution for {}. \ + Low/Hi: {}/{}'.format(signal, low, high), x_axis_label='Intensity Values', y_axis_label='Counts' ) @@ -364,14 +364,14 @@ def intensity_vs_peak_fig(intensity, peak_vals, x, y, slope, intercept, sigma): if ffb: ds_name += ':dir='+FFB_LOC+f'{hutch}/{exp}/xtc' try: - print('Make datasource with {}'.format(ds_name)) + print(f'Make datasource with {ds_name}') ds = psana.MPIDataSource(ds_name) except Exception as e: - logger.warning('Could not use MPI Data Source: {}'.format(e)) + logger.warning(f'Could not use MPI Data Source: {e}') sys.exit() # Setup smd saver - jt_file = 'run{}_jt_cal.h5'.format(run) + jt_file = f'run{run}_jt_cal.h5' if ffb: jt_file_path = ''.join([FFB_LOC, hutch, '/', exp, '/scratch/', jt_file]) @@ -379,7 +379,7 @@ def intensity_vs_peak_fig(intensity, peak_vals, x, y, slope, intercept, sigma): jt_file_path = ''.join([SD_LOC, hutch, '/', exp, '/scratch/', jt_file]) if rank == 0: - logger.info('Will save small data to {}'.format(jt_file_path)) + logger.info(f'Will save small data to {jt_file_path}') smd = ds.small_data(jt_file_path, gather_interval=100) # Get the detectors from the config @@ -394,18 +394,18 @@ def intensity_vs_peak_fig(intensity, peak_vals, x, y, slope, intercept, sigma): evr = psana.Detector(evr_name) masks = get_r_masks(det_map['shape'], cal_params['azav_bins']) except Exception as e: - logger.warning('Unable to create psana detectors: {}'.format(e)) + logger.warning(f'Unable to create psana detectors: {e}') sys.exit() if rank == 0: logger.info(f"Gathering small data for exp: {exp}, run: {run}, events:" f" {cal_params['events']}") - logger.info('Detectors Available: {}'.format(psana.DetNames())) + logger.info(f'Detectors Available: {psana.DetNames()}') # Iterate through and pull out small data for evt_idx, evt in enumerate(ds.events()): if evt_idx % 10 == 0: - print('Event: {}'.format(evt_idx)) + print(f'Event: {evt_idx}') try: if event_code not in evr.eventCodes(evt): continue @@ -439,7 +439,7 @@ def intensity_vs_peak_fig(intensity, peak_vals, x, y, slope, intercept, sigma): smd.event(azav=azav, i0=i0_data, jet_peak=max_jet_val, jet_loc=max_jet_idx) except Exception as e: - logger.info('Unable to process event {}: {}'.format(evt_idx, e)) + logger.info(f'Unable to process event {evt_idx}: {e}') if evt_idx > num_events: break @@ -528,7 +528,7 @@ def intensity_vs_peak_fig(intensity, peak_vals, x, y, slope, intercept, sigma): 'jet_peak_std': jet_peak_std } - logger.info('Results: {}'.format(results)) + logger.info(f'Results: {results}') # Set report directory results_dir = ''.join([SD_LOC, hutch, '/', exp, @@ -538,11 +538,11 @@ def intensity_vs_peak_fig(intensity, peak_vals, x, y, slope, intercept, sigma): calib_dir = ''.join([SD_LOC, hutch, '/', exp, '/calib/jt_results/']) if not os.path.isdir(results_dir): - logger.info('Creating Path {}'.format(results_dir)) + logger.info(f'Creating Path {results_dir}') os.makedirs(results_dir) if not os.path.isdir(calib_dir): - logger.info('Creating Path {}'.format(calib_dir)) + logger.info(f'Creating Path {calib_dir}') os.makedirs(calib_dir) # Write metadata to file @@ -562,21 +562,21 @@ def intensity_vs_peak_fig(intensity, peak_vals, x, y, slope, intercept, sigma): with open(res_file, 'w') as f: results = {k: str(v) for k, v in results.items()} json.dump(results, f) - logger.info('Saved calibration to {}'.format(res_file)) + logger.info(f'Saved calibration to {res_file}') except Exception as e: logger.warning(f'Unable to write to {hutch}opr experiment ' f'directory: {e}') # Accumulate plots and write report gspec = pn.GridSpec(sizing_mode='stretch_both', - name='JT Cal Results: Run {}'.format(run)) + name=f'JT Cal Results: Run {run}') gspec[0:3, 0:3] = p gspec[4:6, 0:3] = p1 gspec[7:12, 0:3] = p2 tabs = pn.Tabs(gspec) report_file = ''.join([results_dir, '/report.html']) - logger.info('Saving report to {}'.format(report_file)) + logger.info(f'Saving report to {report_file}') tabs.save(report_file) logger.info('finished with jet tracking calibration') diff --git a/jet_tracking/main.py b/jet_tracking/main.py index 4ebc821..ec8ec0e 100644 --- a/jet_tracking/main.py +++ b/jet_tracking/main.py @@ -41,7 +41,7 @@ def __init__(self, sys_argv): sys_argv(list): Command - line arguments passed to the application. """ - super(App, self).__init__(sys_argv) + super().__init__(sys_argv) log.debug("Supplying Thread information from init of QApplication") self.setAttribute(Qt.AA_EnableHighDpiScaling) self.setStyle("Fusion") diff --git a/jet_tracking/motorMoving.py b/jet_tracking/motorMoving.py index 8118479..43e7712 100644 --- a/jet_tracking/motorMoving.py +++ b/jet_tracking/motorMoving.py @@ -20,7 +20,7 @@ logger = logging.getLogger(__name__) -class MotorAction(object): +class MotorAction: def __init__(self, motor_thread, context, signals): self.context = context self.signals = signals diff --git a/jet_tracking/mpi_scripts/mpi_driver.py b/jet_tracking/mpi_scripts/mpi_driver.py index d3e913a..df4e7b8 100644 --- a/jet_tracking/mpi_scripts/mpi_driver.py +++ b/jet_tracking/mpi_scripts/mpi_driver.py @@ -59,7 +59,7 @@ if cal_files: cal_file_path = cal_files[-1] # cal_file_path = ''.join([jt_dir, cal_file]) - print('Calibration file: {}'.format(cal_file_path)) + print(f'Calibration file: {cal_file_path}') with open(cal_file_path) as f: cal_results = json.load(f) else: diff --git a/jet_tracking/mpi_scripts/mpi_master.py b/jet_tracking/mpi_scripts/mpi_master.py index 6b6b411..f34e832 100644 --- a/jet_tracking/mpi_scripts/mpi_master.py +++ b/jet_tracking/mpi_scripts/mpi_master.py @@ -13,7 +13,7 @@ logger = logging.getLogger(__name__) -class MpiMaster(object): +class MpiMaster: def __init__(self, rank, api_port, det_map, pv_map, sim=True, data_port=8123, wf_length=None): self._rank = rank @@ -131,11 +131,11 @@ def start_msg_thread(self, api_port): logger.info('aborting jet tracking data analysis process') elif cmd == 'peak_bin': self._pub_socket.send_pyobj(message) - msg_string = 'Changing peak bin to {}'.format(value) + msg_string = f'Changing peak bin to {value}' logger.info(msg_string) elif cmd == 'delta_bin': self._pub_socket.send_pyobj(message) - msg_string = 'Changing delta bin to {}'.format(value) + msg_string = f'Changing delta bin to {value}' logger.info(msg_string) else: print('Received Message with no definition ', message) diff --git a/jet_tracking/mpi_scripts/mpi_worker.py b/jet_tracking/mpi_scripts/mpi_worker.py index bdbca70..228493b 100644 --- a/jet_tracking/mpi_scripts/mpi_worker.py +++ b/jet_tracking/mpi_scripts/mpi_worker.py @@ -10,7 +10,7 @@ logger = logging.getLogger(__name__) -class MpiWorker(object): +class MpiWorker: """This worker will collect events and do whatever necessary processing, then send to master""" def __init__(self, ds, detector, ipm, jet_cam, jet_cam_axis, evr, r_mask, @@ -169,7 +169,7 @@ def start_run(self): self.comm.Isend(packet, dest=0, tag=self.rank) # else: except Exception as e: - logger.warning('Unable to Process Event: {}'.format(e)) + logger.warning(f'Unable to Process Event: {e}') continue def start_msg_thread(self, data_port=1235): diff --git a/jet_tracking/sketch/simJetImage.py b/jet_tracking/sketch/simJetImage.py index fd6aaf8..3cc0330 100644 --- a/jet_tracking/sketch/simJetImage.py +++ b/jet_tracking/sketch/simJetImage.py @@ -3,7 +3,7 @@ from tools.imGen import read_noise, jet_display -class SimulatedImage(object): +class SimulatedImage: """SimulatedImage class generates and manages a simulated image. Args: diff --git a/jet_tracking/tools/ROI.py b/jet_tracking/tools/ROI.py index 35afb18..0dc7380 100644 --- a/jet_tracking/tools/ROI.py +++ b/jet_tracking/tools/ROI.py @@ -282,7 +282,7 @@ def mouseReleaseEvent(self, event): class VLineItem(QGraphicsLineItem): def __init__(self): - super(VLineItem, self).__init__() + super().__init__() self.setPen(QPen(Qt.blue, 3)) self.setFlag(QGraphicsLineItem.ItemIsMovable) self.setCursor(Qt.OpenHandCursor) diff --git a/jet_tracking/tools/motorAlgorithm.py b/jet_tracking/tools/motorAlgorithm.py index cf0af03..4659fe2 100644 --- a/jet_tracking/tools/motorAlgorithm.py +++ b/jet_tracking/tools/motorAlgorithm.py @@ -19,7 +19,7 @@ logger = logging.getLogger(__name__) -class LinearTernary(object): +class LinearTernary: def __init__(self, motor_thread, context, signals): self.motor_thread = motor_thread self.context = context @@ -45,7 +45,7 @@ def search(self): self.done = True -class DynamicLinear(object): +class DynamicLinear: def __init__(self, motor_thread, context, signals): self.motor_thread = motor_thread self.context = context @@ -144,7 +144,7 @@ def scan(self): self.step = 1 -class BasicScan(object): +class BasicScan: def __init__(self, motor_thread, context, signals): self.motor_thread = motor_thread self.context = context @@ -262,7 +262,7 @@ def scan(self): self.step = 1 -class TernarySearch(object): +class TernarySearch: def __init__(self, motor_thread, context, signals): self.motor_thread = motor_thread self.signals = signals diff --git a/jet_tracking/tools/numGen.py b/jet_tracking/tools/numGen.py index 1bd44be..5fb2e28 100644 --- a/jet_tracking/tools/numGen.py +++ b/jet_tracking/tools/numGen.py @@ -2,7 +2,7 @@ import random -class SimulationGenerator(object): +class SimulationGenerator: def __init__(self, context, signals): # initial values from the control widget diff --git a/jet_tracking/tools/simMotorMoving.py b/jet_tracking/tools/simMotorMoving.py index 2aa2469..f767795 100644 --- a/jet_tracking/tools/simMotorMoving.py +++ b/jet_tracking/tools/simMotorMoving.py @@ -4,7 +4,7 @@ log = logging.getLogger(__name__) -class SimulatedMotor(object): +class SimulatedMotor: def __init__(self, context, signals): # initial values from the control widget From 2631b972f62802395be3bc2f49a126646a500ade Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:24:32 -0700 Subject: [PATCH 12/30] BLD: migrate to pyproject.toml Performed by pcds-migration-tools PyprojectTomlMigration --- pyproject.toml | 47 ++++++++++++++++++++++++++++++++++ setup.cfg | 11 -------- setup.py | 69 -------------------------------------------------- 3 files changed, 47 insertions(+), 80 deletions(-) create mode 100644 pyproject.toml delete mode 100644 setup.cfg delete mode 100644 setup.py diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..75c7ee3 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,47 @@ +[build-system] +build-backend = "setuptools.build_meta" +requires = [ "setuptools>=45", "setuptools_scm[toml]>=6.2",] + +[project] +classifiers = [ "Development Status :: 2 - Pre-Alpha", "Natural Language :: English", "Programming Language :: Python :: 3",] +description = "CXI liquid jet positioning feedback and tracking" +dynamic = [ "version", "readme", "dependencies", "optional-dependencies", "optional-dependencies",] +keywords = [] +name = "jet_tracking" +requires-python = ">=3.9" +[[project.authors]] +name = "SLAC National Accelerator Laboratory" + +[options] +zip_safe = false +include_package_data = true + +[project.license] +file = "LICENSE.md" + +[tool.setuptools_scm] +write_to = "jet_tracking/_version.py" + +[tool.flake8] +exclude = "versioneer.py, jet_tracking/_version.py, docs/*" + +[tool.isort] +known_first_party = "jet_tracking, pcdsdevices" +default_section = "THIRDPARTY" + +[tool.setuptools.packages.find] +where = [ ".",] +include = [ "jet_tracking*",] +namespaces = false + +[tool.setuptools.dynamic.readme] +file = "README.rst" + +[tool.setuptools.dynamic.dependencies] +file = [ "requirements.txt",] + +[tool.setuptools.dynamic.optional-dependencies.test] +file = "dev-requirements.txt" + +[tool.setuptools.dynamic.optional-dependencies.doc] +file = "docs-requirements.txt" diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 13007b5..0000000 --- a/setup.cfg +++ /dev/null @@ -1,11 +0,0 @@ -[versioneer] -VCS = git -style = pep440-post -versionfile_source = jet_tracking/_version.py -versionfile_build = jet_tracking/_version.py -tag_prefix = v -[flake8] -exclude = versioneer.py, jet_tracking/_version.py, docs/* -[isort] -known_first_party=jet_tracking, pcdsdevices -default_section=THIRDPARTY diff --git a/setup.py b/setup.py deleted file mode 100644 index 473c039..0000000 --- a/setup.py +++ /dev/null @@ -1,69 +0,0 @@ -import sys -from os import path - -from setuptools import find_packages, setup - -import versioneer - -# NOTE: This file must remain Python 2 compatible for the foreseeable future, -# to ensure that we error out properly for people with outdated setuptools -# and/or pip. -min_version = (3, 6) -if sys.version_info < min_version: - error = """ - jet_tracking does not support Python {0}.{1}. - Python {2}.{3} or above is required. Check your Python version like so: - - python3 --version - - This may be due to an out-of-date pip. Make sure you have pip >= 9.0.1. - Upgrade pip like so: - - pip install --upgrade pip - """.format(*(sys.version_info[:2] + min_version)) - sys.exit(error) - -here = path.abspath(path.dirname(__file__)) - -with open(path.join(here, 'README.rst'), encoding='utf-8') as readme_file: - readme = readme_file.read() - - -with open(path.join(here, 'requirements.txt')) as requirements_file: - # Parse requirements.txt, ignoring any commented-out lines. - requirements = [line - for line in requirements_file.read().splitlines() - if not line.startswith('#') and not line.startswith('-e ')] - - -setup( - name='jet_tracking', - version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), - description="CXI liquid jet positioning feedback and tracking", - long_description=readme, - author="SLAC National Accelerator Laboratory", - author_email='', - url='https://github.com/pcdshub/jet_tracking', - packages=find_packages(exclude=['docs', 'tests']), - entry_points={ - 'console_scripts': [ - # 'some.module:some_function', - ], - }, - include_package_data=True, - package_data={ - 'jet_tracking': [ - # When adding files here, remember to update MANIFEST.in as well, - # or else they will not be included in the distribution on PyPI! - # 'path/to/data_file', - ] - }, - install_requires=requirements, - license="SLAC Open License", - classifiers=[ - 'Development Status :: 2 - Pre-Alpha', - 'Natural Language :: English', - 'Programming Language :: Python :: 3', - ], -) From 32a2450cb9f55c123f202d50d5a26d000ea62d51 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:24:32 -0700 Subject: [PATCH 13/30] BLD: migrate to setuptools-scm Performed by pcds-migration-tools SetuptoolsScmMigration --- jet_tracking/__init__.py | 4 +- jet_tracking/_version.py | 623 ------------ jet_tracking/version.py | 59 ++ versioneer.py | 2065 -------------------------------------- 4 files changed, 60 insertions(+), 2691 deletions(-) delete mode 100644 jet_tracking/_version.py create mode 100644 jet_tracking/version.py delete mode 100644 versioneer.py diff --git a/jet_tracking/__init__.py b/jet_tracking/__init__.py index cada410..5c0cf28 100644 --- a/jet_tracking/__init__.py +++ b/jet_tracking/__init__.py @@ -1,3 +1 @@ -from . import _version - -__version__ = _version.get_versions()['version'] +from .version import __version__ # noqa: F401 diff --git a/jet_tracking/_version.py b/jet_tracking/_version.py deleted file mode 100644 index dfcf192..0000000 --- a/jet_tracking/_version.py +++ /dev/null @@ -1,623 +0,0 @@ - -# 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.20 (https://github.com/python-versioneer/python-versioneer) - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys - - -def get_keywords(): - """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 - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "$Format:%d$" - git_full = "$Format:%H$" - git_date = "$Format:%ci$" - keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} - return keywords - - -class VersioneerConfig: # pylint: disable=too-few-public-methods - """Container for Versioneer configuration parameters.""" - - -def get_config(): - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "pep440-post" - cfg.tag_prefix = "v" - cfg.parentdir_prefix = "None" - cfg.versionfile_source = "jet_tracking/_version.py" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -# pylint:disable=too-many-arguments,consider-using-with # noqa -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - for command in commands: - try: - dispcmd = str([command] + args) - # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None, None - 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, process.returncode - return stdout, process.returncode - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - 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} - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """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 = {} - try: - 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 EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - 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 - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - 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 = {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 - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # 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 = {r for r in refs if re.search(r'\d', r)} - if verbose: - print("discarding '%s', no digits" % ",".join(refs - tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # 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, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # 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 = runner(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%s*" % tag_prefix], - 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 = 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["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 - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - 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): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces): - """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[.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 render_pep440_pre(pieces): - """TAG[.post0.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post0.dev%d" % pieces["distance"] - else: - # exception #1 - rendered = "0.post0.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_post_branch(pieces): - """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): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - 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": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -def get_versions(): - """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 - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # 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 _ in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} diff --git a/jet_tracking/version.py b/jet_tracking/version.py new file mode 100644 index 0000000..da8a5d5 --- /dev/null +++ b/jet_tracking/version.py @@ -0,0 +1,59 @@ +from collections import UserString +from pathlib import Path +from typing import Optional + + +class VersionProxy(UserString): + """ + Version handling helper that pairs with setuptools-scm. + + This allows for pkg.__version__ to be dynamically retrieved on request by + way of setuptools-scm. + + This deferred evaluation of the version until it is checked saves time on + package import. + + This supports the following scenarios: + + 1. A git checkout (.git exists) + 2. A git archive / a tarball release from GitHub that includes version + information in .git_archival.txt. + 3. An existing _version.py generated by setuptools_scm + 4. A fallback in case none of the above match - resulting in a version of + 0.0.unknown + """ + def __init__(self): + self._version = None + + def _get_version(self) -> Optional[str]: + # Checking for directory is faster than failing out of get_version + repo_root = Path(__file__).resolve().parent.parent + if (repo_root / ".git").exists() or (repo_root / ".git_archival.txt").exists(): + try: + # Git checkout + from setuptools_scm import get_version + return get_version(root="..", relative_to=__file__) + except (ImportError, LookupError): + ... + + # Check this second because it can exist in a git repo if we've + # done a build at least once. + try: + from ._version import version # noqa: F401 + return version + except ImportError: + ... + + return None + + @property + def data(self) -> str: + # This is accessed by UserString to allow us to lazily fill in the + # information + if self._version is None: + self._version = self._get_version() or '0.0.unknown' + + return self._version + + +__version__ = version = VersionProxy() diff --git a/versioneer.py b/versioneer.py deleted file mode 100644 index a6efdb6..0000000 --- a/versioneer.py +++ /dev/null @@ -1,2065 +0,0 @@ - -# Version: 0.20 - -"""The Versioneer - like a rocketeer, but for versions. - -The Versioneer -============== - -* like a rocketeer, but for versions! -* https://github.com/python-versioneer/python-versioneer -* Brian Warner -* License: Public Domain -* Compatible with: Python 3.6, 3.7, 3.8, 3.9 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 distutils-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 -system, and maybe making new tarballs. - - -## Quick Install - -* `pip install versioneer` to somewhere in your $PATH -* add a `[versioneer]` section to your setup.cfg (see [Install](INSTALL.md)) -* run `versioneer install` in your source tree, commit the results -* Verify version information with `python setup.py version` - -## Version Identifiers - -Source trees come from a variety of places: - -* a version-control system checkout (mostly used by developers) -* a nightly tarball, produced by build automation -* a snapshot tarball, produced by a web-based VCS browser, like github's - "tarball from tag" feature -* a release tarball, produced by "setup.py sdist", distributed through PyPI - -Within each source tree, the version identifier (either a string or a number, -this tool is format-agnostic) can come from a variety of places: - -* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows - about recent "tags" and an absolute revision-id -* the name of the directory into which the tarball was unpacked -* an expanded VCS keyword ($Id$, etc) -* a `_version.py` created by some earlier build step - -For released software, the version identifier is closely related to a VCS -tag. Some projects use tag names that include more than just the version -string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool -needs to strip the tag prefix to extract the version identifier. For -unreleased software (between tags), the version identifier should provide -enough information to help developers recreate the same tree, while also -giving them an idea of roughly how old the tree is (after version 1.2, before -version 1.3). Many VCS systems can report a description that captures this, -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). - -The version identifier is used for multiple purposes: - -* to allow the module to self-identify its version: `myproject.__version__` -* to choose a name and prefix for a 'setup.py sdist' tarball - -## Theory of Operation - -Versioneer works by adding a special `_version.py` file into your source -tree, where your `__init__.py` can import it. This `_version.py` knows how to -dynamically ask the VCS tool for version information at import time. - -`_version.py` also contains `$Revision$` markers, and the installation -process marks `_version.py` to have this marker rewritten with a tag name -during the `git archive` command. As a result, generated tarballs will -contain enough information to get the proper version. - -To allow `setup.py` to compute a version too, a `versioneer.py` is added to -the top level of your source tree, next to `setup.py` and the `setup.cfg` -that configures it. This overrides several distutils/setuptools commands to -compute the version when invoked, and changes `setup.py build` and `setup.py -sdist` to replace `_version.py` with a small static file that contains just -the generated version data. - -## Installation - -See [INSTALL.md](./INSTALL.md) for detailed installation instructions. - -## Version-String Flavors - -Code which uses Versioneer can learn about its version string at runtime by -importing `_version` from your main `__init__.py` file and running the -`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can -import the top-level `versioneer.py` and run `get_versions()`. - -Both functions return a dictionary with different flavors of version -information: - -* `['version']`: A condensed version string, rendered using the selected - style. This is the most commonly used value for the project's version - string. The default "pep440" style yields strings like `0.11`, - `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section - below for alternative styles. - -* `['full-revisionid']`: detailed revision identifier. For Git, this is the - full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". - -* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the - commit date in ISO 8601 format. This will be None if the date is not - available. - -* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that - this is only accurate if run in a VCS checkout, otherwise it is likely to - be False or None - -* `['error']`: if the version string could not be computed, this will be set - to a string describing the problem, otherwise it will be None. It may be - useful to throw an exception in setup.py if this is set, to avoid e.g. - creating tarballs with a version string of "unknown". - -Some variants are more useful than others. Including `full-revisionid` in a -bug report should allow developers to reconstruct the exact code being tested -(or indicate the presence of local changes that should be shared with the -developers). `version` is suitable for display in an "about" box or a CLI -`--version` output: it can be easily compared against release notes and lists -of bugs fixed in various releases. - -The installer adds the following text to your `__init__.py` to place a basic -version in `YOURPROJECT.__version__`: - - from ._version import get_versions - __version__ = get_versions()['version'] - del get_versions - -## Styles - -The setup.cfg `style=` configuration controls how the VCS information is -rendered into a version string. - -The default style, "pep440", produces a PEP440-compliant string, equal to the -un-prefixed tag name for actual releases, and containing an additional "local -version" section with more detail for in-between builds. For Git, this is -TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags ---dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the -tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and -that this commit is two revisions ("+2") beyond the "0.11" tag. For released -software (exactly equal to a known tag), the identifier will only contain the -stripped tag, e.g. "0.11". - -Other styles are available. See [details.md](details.md) in the Versioneer -source tree for descriptions. - -## Debugging - -Versioneer tries to avoid fatal errors: if something goes wrong, it will tend -to return a version of "0+unknown". To investigate the problem, run `setup.py -version`, which will run the version-lookup code in a verbose mode, and will -display the full contents of `get_versions()` (including the `error` string, -which may help identify what went wrong). - -## Known Limitations - -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/python-versioneer/python-versioneer/issues). - -### Subprojects - -Versioneer has limited support for source trees in which `setup.py` is not in -the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are -two common reasons why `setup.py` might not be in the root: - -* Source trees which contain multiple subprojects, such as - [Buildbot](https://github.com/buildbot/buildbot), which contains both - "master" and "slave" subprojects, each with their own `setup.py`, - `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 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 -and implementation details which frequently cause `pip install .` from a -subproject directory to fail to find a correct version string (so it usually -defaults to `0+unknown`). - -`pip install --editable .` should work correctly. `setup.py install` might -work too. - -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/python-versioneer/python-versioneer/issues/38) is tracking -this issue. The discussion in -[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 -pip to let Versioneer work correctly. - -Versioneer-0.16 and earlier only looked for a `.git` directory next to the -`setup.cfg`, so subprojects were completely unsupported with those releases. - -### Editable installs with setuptools <= 18.5 - -`setup.py develop` and `pip install --editable .` allow you to install a -project into a virtualenv once, then continue editing the source code (and -test) without re-installing after every change. - -"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a -convenient way to specify executable scripts that should be installed along -with the python package. - -These both work as expected when using modern setuptools. When using -setuptools-18.5 or earlier, however, certain operations will cause -`pkg_resources.DistributionNotFound` errors when running the entrypoint -script, which must be resolved by re-installing the package. This happens -when the install happens with one version, then the egg_info data is -regenerated while a different version is checked out. Many setup.py commands -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/python-versioneer/python-versioneer/issues/83) describes -this one, but upgrading to a newer version of setuptools should probably -resolve it. - - -## 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 - `SRC/_version.py` -* commit any changed files - -## Future Directions - -This tool is designed to make it easily extended to other version-control -systems: all VCS-specific components are in separate directories like -src/git/ . The top-level `versioneer.py` script is assembled from these -components by running make-versioneer.py . In the future, make-versioneer.py -will take a VCS name as an argument, and will construct a version of -`versioneer.py` that is specific to the given VCS. It might also take the -configuration arguments that are currently provided manually during -installation by editing setup.py . Alternatively, it might go the other -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/ . - -[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 - -""" - -import configparser -import errno -import json -import os -import re -import subprocess -import sys - - -class VersioneerConfig: # pylint: disable=too-few-public-methods # noqa - """Container for Versioneer configuration parameters.""" - - -def get_root(): - """Get the project root directory. - - We require that all commands are run from the project root, i.e. the - directory that contains setup.py, setup.cfg, and versioneer.py . - """ - root = os.path.realpath(os.path.abspath(os.getcwd())) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) 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") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) 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'), " - "or in a way that lets it use sys.argv[0] to find the root " - "(like 'python path/to/setup.py COMMAND').") - raise VersioneerBadRootError(err) - try: - # Certain runtime workflows (setup.py install/develop in a setuptools - # tree) execute all dependencies in a single python process, so - # "versioneer" may be imported multiple times, and python's shared - # 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. - 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: - print("Warning: build in %s is using versioneer.py from %s" - % (os.path.dirname(my_path), versioneer_py)) - except NameError: - pass - return root - - -def get_config_from_root(root): - """Read the project setup.cfg file to determine Versioneer config.""" - # This might raise EnvironmentError (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() - with open(setup_cfg, "r") as cfg_file: - parser.read_file(cfg_file) - VCS = parser.get("versioneer", "VCS") # mandatory - - # Dict-like interface for non-mandatory entries - section = parser["versioneer"] - - # pylint:disable=attribute-defined-outside-init # noqa - cfg = VersioneerConfig() - cfg.VCS = VCS - cfg.style = section.get("style", "") - cfg.versionfile_source = section.get("versionfile_source") - cfg.versionfile_build = section.get("versionfile_build") - cfg.tag_prefix = section.get("tag_prefix") - if cfg.tag_prefix in ("''", '""'): - cfg.tag_prefix = "" - cfg.parentdir_prefix = section.get("parentdir_prefix") - cfg.verbose = section.get("verbose") - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -# these dictionaries contain VCS-specific tools -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - HANDLERS.setdefault(vcs, {})[method] = f - return f - return decorate - - -# pylint:disable=too-many-arguments,consider-using-with # noqa -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - for command in commands: - try: - dispcmd = str([command] + args) - # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None, None - 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, process.returncode - return stdout, process.returncode - - -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.20 (https://github.com/python-versioneer/python-versioneer) - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys - - -def get_keywords(): - """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 - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" - git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" - git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" - keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} - return keywords - - -class VersioneerConfig: # pylint: disable=too-few-public-methods - """Container for Versioneer configuration parameters.""" - - -def get_config(): - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "%(STYLE)s" - cfg.tag_prefix = "%(TAG_PREFIX)s" - cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" - cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY = {} -HANDLERS = {} - - -def register_vcs_handler(vcs, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -# pylint:disable=too-many-arguments,consider-using-with # noqa -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - for command in commands: - try: - dispcmd = str([command] + args) - # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) - break - except EnvironmentError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %%s" %% dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %%s" %% (commands,)) - return None, None - 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, process.returncode - return stdout, process.returncode - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - 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} - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %%s but none started with prefix %%s" %% - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """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 = {} - try: - 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 EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - 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 - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - 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 = {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 - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # 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 = {r for r in refs if re.search(r'\d', r)} - if verbose: - print("discarding '%%s', no digits" %% ",".join(refs - tags)) - if verbose: - print("likely tags: %%s" %% ",".join(sorted(tags))) - for ref in sorted(tags): - # 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, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) - if rc != 0: - if verbose: - print("Directory %%s not under git control" %% root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # 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 = runner(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%%s*" %% tag_prefix], - 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 = 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["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 - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%%s'" - %% describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%%s' doesn't start with prefix '%%s'" - print(fmt %% (full_tag, tag_prefix)) - pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" - %% (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - 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): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces): - """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[.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 render_pep440_pre(pieces): - """TAG[.post0.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post0.dev%%d" %% pieces["distance"] - else: - # exception #1 - rendered = "0.post0.dev%%d" %% pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%%s" %% pieces["short"] - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%%s" %% pieces["short"] - return rendered - - -def render_pep440_post_branch(pieces): - """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): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - 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": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%%s'" %% style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -def get_versions(): - """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 - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # 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 _ in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} -''' - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """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 = {} - try: - 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 EnvironmentError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - 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 - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - 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 = {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 - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # 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 = {r for r in refs if re.search(r'\d', r)} - if verbose: - print("discarding '%s', no digits" % ",".join(refs - tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # 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, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # 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 = runner(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%s*" % tag_prefix], - 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 = 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["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 - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) - pieces["distance"] = int(count_out) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - 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): - """Git-specific installation logic for Versioneer. - - For Git, this means creating/changing .gitattributes to mark _version.py - for export-subst keyword substitution. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - files = [manifest_in, versionfile_source] - if ipy: - files.append(ipy) - try: - my_path = __file__ - if my_path.endswith(".pyc") or my_path.endswith(".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: - 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 EnvironmentError: - pass - if not present: - 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): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - 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} - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -SHORT_VERSION_PY = """ -# This file was generated by 'versioneer.py' (0.20) 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. - -import json - -version_json = ''' -%s -''' # END VERSION_JSON - - -def get_versions(): - return json.loads(version_json) -""" - - -def versions_from_file(filename): - """Try to determine the version from _version.py if present.""" - try: - with open(filename) as f: - contents = f.read() - except EnvironmentError: - raise NotThisMethod("unable to read _version.py") - mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - raise NotThisMethod("no version_json in _version.py") - return json.loads(mo.group(1)) - - -def write_to_version_file(filename, versions): - """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: - f.write(SHORT_VERSION_PY % contents) - - print("set %s to '%s'" % (filename, versions["version"])) - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces): - """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[.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 render_pep440_pre(pieces): - """TAG[.post0.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += ".post0.dev%d" % pieces["distance"] - else: - # exception #1 - rendered = "0.post0.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_post_branch(pieces): - """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): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - 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": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -class VersioneerBadRootError(Exception): - """The project root directory is unknown or missing key files.""" - - -def get_versions(verbose=False): - """Get the project version from whatever source is available. - - Returns dict with two keys: 'version' and 'full'. - """ - if "versioneer" in sys.modules: - # see the discussion in cmdclass.py:get_cmdclass() - del sys.modules["versioneer"] - - root = get_root() - cfg = get_config_from_root(root) - - 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 - assert cfg.versionfile_source is not None, \ - "please set versioneer.versionfile_source" - assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" - - versionfile_abs = os.path.join(root, cfg.versionfile_source) - - # extract version from first of: _version.py, VCS command (e.g. 'git - # describe'), parentdir. This is meant to work for developers using a - # source checkout, for users of a tarball created by 'setup.py sdist', - # and for users of a tarball/zipball created by 'git archive' or github's - # download-from-tag feature or the equivalent in other VCSes. - - get_keywords_f = handlers.get("get_keywords") - from_keywords_f = handlers.get("keywords") - if get_keywords_f and from_keywords_f: - try: - keywords = get_keywords_f(versionfile_abs) - ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) - if verbose: - print("got version from expanded keyword %s" % ver) - return ver - except NotThisMethod: - pass - - try: - ver = versions_from_file(versionfile_abs) - if verbose: - print("got version from file %s %s" % (versionfile_abs, ver)) - return ver - except NotThisMethod: - pass - - from_vcs_f = handlers.get("pieces_from_vcs") - if from_vcs_f: - try: - pieces = from_vcs_f(cfg.tag_prefix, root, verbose) - ver = render(pieces, cfg.style) - if verbose: - print("got version from VCS %s" % ver) - return ver - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - if verbose: - print("got version from parentdir %s" % ver) - return ver - except NotThisMethod: - pass - - if verbose: - print("unable to compute version") - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, "error": "unable to compute version", - "date": None} - - -def get_version(): - """Get the short version string for this project.""" - return get_versions()["version"] - - -def get_cmdclass(cmdclass=None): - """Get the custom setuptools/distutils 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 - # 'easy_install .'), in which subdependencies of the main project are - # built (using setup.py bdist_egg) in the same python process. Assume - # a main project A and a dependency B, which use different versions - # of Versioneer. A's setup.py imports A's Versioneer, leaving it in - # sys.modules by the time B's setup.py is executed, causing B to run - # with the wrong versioneer. Setuptools wraps the sub-dep builds in a - # sandbox that restores sys.modules to it's pre-build state, so the - # 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/python-versioneer/python-versioneer/issues/52 - - cmds = {} if cmdclass is None else cmdclass.copy() - - # we add "version" to both distutils and setuptools - from distutils.core import Command - - class cmd_version(Command): - description = "report generated version string" - user_options = [] - boolean_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - vers = get_versions(verbose=True) - print("Version: %s" % vers["version"]) - print(" full-revisionid: %s" % vers.get("full-revisionid")) - print(" dirty: %s" % vers.get("dirty")) - print(" date: %s" % vers.get("date")) - if vers["error"]: - print(" error: %s" % vers["error"]) - cmds["version"] = cmd_version - - # we override "build_py" in both distutils and setuptools - # - # most invocation pathways end up running build_py: - # distutils/build -> build_py - # distutils/install -> distutils/build ->.. - # setuptools/bdist_wheel -> distutils/install ->.. - # setuptools/bdist_egg -> distutils/install_lib -> build_py - # setuptools/install -> bdist_egg ->.. - # setuptools/develop -> ? - # pip install: - # copies source tree to a tempdir before running egg_info/etc - # if .git isn't copied too, 'git describe' will fail - # then does setup.py bdist_wheel, or sometimes setup.py install - # setup.py egg_info -> ? - - # we override different "build_py" commands for both environments - if 'build_py' in cmds: - _build_py = cmds['build_py'] - elif "setuptools" in sys.modules: - from setuptools.command.build_py import build_py as _build_py - else: - from distutils.command.build_py import build_py as _build_py - - class cmd_build_py(_build_py): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_py.run(self) - # now locate _version.py in the new build/ directory and replace - # it with an updated value - if cfg.versionfile_build: - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - cmds["build_py"] = cmd_build_py - - if 'build_ext' in cmds: - _build_ext = cmds['build_ext'] - elif "setuptools" in sys.modules: - from setuptools.command.build_ext import build_ext as _build_ext - else: - from distutils.command.build_ext import build_ext as _build_ext - - class cmd_build_ext(_build_ext): - def run(self): - 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 - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) - 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 - - # nczeczulin reports that py2exe won't like the pep440-style string - # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. - # setup(console=[{ - # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION - # "product_version": versioneer.get_version(), - # ... - - class cmd_build_exe(_build_exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _build_exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["build_exe"] = cmd_build_exe - del cmds["build_py"] - - if 'py2exe' in sys.modules: # py2exe enabled? - from py2exe.distutils_buildexe import py2exe as _py2exe - - class cmd_py2exe(_py2exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _py2exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["py2exe"] = cmd_py2exe - - # we override different "sdist" commands for both environments - if 'sdist' in cmds: - _sdist = cmds['sdist'] - elif "setuptools" in sys.modules: - from setuptools.command.sdist import sdist as _sdist - else: - from distutils.command.sdist import sdist as _sdist - - class cmd_sdist(_sdist): - def run(self): - versions = get_versions() - # pylint:disable=attribute-defined-outside-init # noqa - self._versioneer_generated_versions = versions - # unless we update this, the command will keep using the old - # version - self.distribution.metadata.version = versions["version"] - return _sdist.run(self) - - def make_release_tree(self, base_dir, files): - root = get_root() - cfg = get_config_from_root(root) - _sdist.make_release_tree(self, base_dir, files) - # now locate _version.py in the new base_dir directory - # (remembering that it may be a hardlink) and replace it with an - # updated value - target_versionfile = os.path.join(base_dir, cfg.versionfile_source) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, - self._versioneer_generated_versions) - cmds["sdist"] = cmd_sdist - - return cmds - - -CONFIG_ERROR = """ -setup.cfg is missing the necessary Versioneer configuration. You need -a section like: - - [versioneer] - VCS = git - style = pep440 - versionfile_source = src/myproject/_version.py - versionfile_build = myproject/_version.py - tag_prefix = - parentdir_prefix = myproject- - -You will also need to edit your setup.py to use the results: - - import versioneer - setup(version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), ...) - -Please read the docstring in ./versioneer.py for configuration instructions, -edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. -""" - -SAMPLE_CONFIG = """ -# See the docstring in versioneer.py for instructions. Note that you must -# re-run 'versioneer.py setup' after changing this section, and commit the -# resulting files. - -[versioneer] -#VCS = git -#style = pep440 -#versionfile_source = -#versionfile_build = -#tag_prefix = -#parentdir_prefix = - -""" - -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(): - """Do main VCS-independent setup function for installing Versioneer.""" - root = get_root() - try: - cfg = get_config_from_root(root) - except (EnvironmentError, configparser.NoSectionError, - configparser.NoOptionError) as e: - if isinstance(e, (EnvironmentError, configparser.NoSectionError)): - print("Adding sample versioneer config to setup.cfg", - file=sys.stderr) - with open(os.path.join(root, "setup.cfg"), "a") as f: - f.write(SAMPLE_CONFIG) - print(CONFIG_ERROR, file=sys.stderr) - return 1 - - print(" creating %s" % cfg.versionfile_source) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - - ipy = os.path.join(os.path.dirname(cfg.versionfile_source), - "__init__.py") - if os.path.exists(ipy): - try: - with open(ipy, "r") as f: - old = f.read() - except EnvironmentError: - 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(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") - - # 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) - return 0 - - -def scan_setup_py(): - """Validate the contents of setup.py against Versioneer's expectations.""" - found = set() - setters = False - errors = 0 - with open("setup.py", "r") as f: - for line in f.readlines(): - if "import versioneer" in line: - found.add("import") - if "versioneer.get_cmdclass()" in line: - found.add("cmdclass") - if "versioneer.get_version()" in line: - found.add("get_version") - if "versioneer.VCS" in line: - setters = True - if "versioneer.versionfile_source" in line: - setters = True - if len(found) != 3: - print("") - print("Your setup.py appears to be missing some important items") - print("(but I might be wrong). Please make sure it has something") - print("roughly like the following:") - print("") - print(" import versioneer") - print(" setup( version=versioneer.get_version(),") - print(" cmdclass=versioneer.get_cmdclass(), ...)") - print("") - errors += 1 - if setters: - print("You should remove lines like 'versioneer.VCS = ' and") - print("'versioneer.versionfile_source = ' . This configuration") - print("now lives in setup.cfg, and should be removed from setup.py") - print("") - errors += 1 - return errors - - -if __name__ == "__main__": - cmd = sys.argv[1] - if cmd == "setup": - errors = do_setup() - errors += scan_setup_py() - if errors: - sys.exit(1) From 46c73058f26e139c101055448098ff1862ee1954 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:24:32 -0700 Subject: [PATCH 14/30] BLD: update conda-recipe Performed by pcds-migration-tools UpdateCondaRecipe --- conda-recipe/build.sh | 1 - conda-recipe/meta.yaml | 46 +++++++++++++++++++++++++----------------- 2 files changed, 28 insertions(+), 19 deletions(-) delete mode 100755 conda-recipe/build.sh diff --git a/conda-recipe/build.sh b/conda-recipe/build.sh deleted file mode 100755 index a660906..0000000 --- a/conda-recipe/build.sh +++ /dev/null @@ -1 +0,0 @@ -$PYTHON setup.py install --single-version-externally-managed --record=record.txt diff --git a/conda-recipe/meta.yaml b/conda-recipe/meta.yaml index 429a588..a8b018b 100644 --- a/conda-recipe/meta.yaml +++ b/conda-recipe/meta.yaml @@ -1,35 +1,45 @@ -{% set data = load_setup_py_data() %} +{% set package_name = "jet_tracking" %} +{% set import_name = "jet_tracking" %} +{% set version = load_file_regex(load_file=os.path.join(import_name, "_version.py"), regex_pattern=".*version = '(\S+)'").group(1) %} package: - name: jet_tracking - version : {{ data.get('version') }} + name: {{ package_name }} + version: {{ version }} source: path: .. build: - number: 1 + number: 0 + noarch: python + script: {{ PYTHON }} -m pip install . -vv + + requirements: build: - - python {{PY_VER}}*,>=3.6 - - setuptools - + - python {{PY_VER}}*,>=3.6 + - setuptools_scm + - pip run: - - python {{PY_VER}}*,>=3.6 - - pcdsdevices >=2.6.0 - - matplotlib - - numpy - - ophyd >=1.5.0 - - bluesky >=1.6.0 - - opencv - - pandas - - scikit-image - - scipy + - python {{PY_VER}}*,>=3.6 + - pcdsdevices >=2.6.0 + - matplotlib + - numpy + - ophyd >=1.5.0 + - bluesky >=1.6.0 + - opencv + - pandas + - scikit-image + - scipy + + test: imports: - - jet_tracking + - jet_tracking + + about: home: https://github.com/pcdshub/jet_tracking From 759c548a086a786d560a8b16907c3f9ccc23ef53 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:25:47 -0700 Subject: [PATCH 15/30] MNT: cleaning code with pycln Performed by pcds-migration-tools RunPycln --- docs/source/conf.py | 1 - jet_tracking/gui/widgets/editorWidget.py | 3 +-- jet_tracking/gui/widgets/graphWidgetUi.py | 1 - jet_tracking/gui/widgets/jetImageWidget.py | 4 ++-- jet_tracking/gui/widgets/simControlWidget.py | 1 - jet_tracking/gui/widgets/simControlWidgetUi.py | 3 +-- jet_tracking/main.py | 1 - jet_tracking/sketch/simJetImage.py | 3 +-- 8 files changed, 5 insertions(+), 12 deletions(-) diff --git a/docs/source/conf.py b/docs/source/conf.py index 32cea09..08459e7 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -16,7 +16,6 @@ import os import sys -import sphinx_rtd_theme import jet_tracking diff --git a/jet_tracking/gui/widgets/editorWidget.py b/jet_tracking/gui/widgets/editorWidget.py index 7f775e7..a0865f4 100644 --- a/jet_tracking/gui/widgets/editorWidget.py +++ b/jet_tracking/gui/widgets/editorWidget.py @@ -1,9 +1,8 @@ import logging from collections import deque -import cv2 from datastream import JetImageFeed from gui.widgets.editorWidgetUi import Editor_Ui -from PyQt5.QtWidgets import QFrame, QFileDialog +from PyQt5.QtWidgets import QFrame from PyQt5.QtCore import QThread log = logging.getLogger(__name__) diff --git a/jet_tracking/gui/widgets/graphWidgetUi.py b/jet_tracking/gui/widgets/graphWidgetUi.py index e9b57ea..de2a6e0 100644 --- a/jet_tracking/gui/widgets/graphWidgetUi.py +++ b/jet_tracking/gui/widgets/graphWidgetUi.py @@ -1,5 +1,4 @@ import pyqtgraph as pg -from jetGraphing import ScrollingTimeWidget, graph_setup, add_calibration_graph from PyQt5.QtWidgets import QVBoxLayout diff --git a/jet_tracking/gui/widgets/jetImageWidget.py b/jet_tracking/gui/widgets/jetImageWidget.py index 8d0d7ec..acf4521 100644 --- a/jet_tracking/gui/widgets/jetImageWidget.py +++ b/jet_tracking/gui/widgets/jetImageWidget.py @@ -1,8 +1,8 @@ import logging -from PyQt5.QtWidgets import QGraphicsPixmapItem, QGraphicsView, QGraphicsEllipseItem +from PyQt5.QtWidgets import QGraphicsPixmapItem, QGraphicsView from tools.ROI import HLineItem, VLineItem, GraphicsScene, GraphicsRectItem from PyQt5.QtCore import Qt -from PyQt5.QtGui import QPixmap, QImage, QPen +from PyQt5.QtGui import QPixmap, QImage import numpy as np from qimage2ndarray import array2qimage import cv2 diff --git a/jet_tracking/gui/widgets/simControlWidget.py b/jet_tracking/gui/widgets/simControlWidget.py index 51749af..edca45d 100644 --- a/jet_tracking/gui/widgets/simControlWidget.py +++ b/jet_tracking/gui/widgets/simControlWidget.py @@ -1,6 +1,5 @@ from PyQt5.QtWidgets import QFrame from gui.widgets.simControlWidgetUi import SimUi -from datastream import StatusThread, MotorThread import logging log = logging.getLogger(__name__) diff --git a/jet_tracking/gui/widgets/simControlWidgetUi.py b/jet_tracking/gui/widgets/simControlWidgetUi.py index 521b294..0a0f4aa 100644 --- a/jet_tracking/gui/widgets/simControlWidgetUi.py +++ b/jet_tracking/gui/widgets/simControlWidgetUi.py @@ -1,6 +1,5 @@ from gui.widgets.basicWidgets import LineEdit -from PyQt5.QtWidgets import (QHBoxLayout, QLabel, QPushButton, QSizePolicy, - QVBoxLayout) +from PyQt5.QtWidgets import (QHBoxLayout, QLabel, QVBoxLayout) class SimUi: diff --git a/jet_tracking/main.py b/jet_tracking/main.py index ec8ec0e..e4f96b9 100644 --- a/jet_tracking/main.py +++ b/jet_tracking/main.py @@ -2,7 +2,6 @@ import logging import os import sys -import pathlib from gui.windows.mainWindow import MainWindow from PyQt5.Qt import Qt diff --git a/jet_tracking/sketch/simJetImage.py b/jet_tracking/sketch/simJetImage.py index 3cc0330..8b34e82 100644 --- a/jet_tracking/sketch/simJetImage.py +++ b/jet_tracking/sketch/simJetImage.py @@ -1,6 +1,5 @@ import numpy as np -import cv2 -from tools.imGen import read_noise, jet_display +from tools.imGen import jet_display class SimulatedImage: From 498e469c1f849fbf77e782a1c5348225b57c7f2b Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:25:56 -0700 Subject: [PATCH 16/30] DEV: 'pre-commit autoupdate' Performed by pcds-migration-tools PrecommitAutoupdate --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 712f148..96e5255 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -28,6 +28,6 @@ repos: - id: flake8 - repo: https://github.com/timothycrosley/isort - rev: 5.11.4 + rev: 5.12.0 hooks: - id: isort From 0517120ebe1ee41acb9c2de79d92c729bb6e53aa Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:30:02 -0700 Subject: [PATCH 17/30] MNT: 'pre-commit run' Performed by pcds-migration-tools RunPrecommit --- docs/source/conf.py | 12 ++++-- jet_tracking/context.py | 2 +- jet_tracking/datastream.py | 37 ++++++++++--------- jet_tracking/gui/views/jetTrackerView.py | 2 +- jet_tracking/gui/views/simultationView.py | 2 +- jet_tracking/gui/widgets/controlWidgetUi.py | 9 ++--- jet_tracking/gui/widgets/editorWidget.py | 15 ++++---- jet_tracking/gui/widgets/editorWidgetUi.py | 8 ++-- jet_tracking/gui/widgets/graphWidget.py | 11 +++--- jet_tracking/gui/widgets/jetImageWidget.py | 31 ++++++++-------- jet_tracking/gui/widgets/simControlWidget.py | 5 ++- .../gui/widgets/simControlWidgetUi.py | 2 +- jet_tracking/gui/windows/mainWindow.py | 2 + jet_tracking/jt_configs/Geoo.qss | 30 +++++++-------- jet_tracking/jt_configs/License.txt | 2 +- jet_tracking/motorMoving.py | 5 ++- jet_tracking/signals.py | 9 +---- jet_tracking/sketch/simJetImage.py | 3 -- jet_tracking/tools/ROI.py | 7 ++-- jet_tracking/tools/imGen.py | 3 +- jet_tracking/tools/motorAlgorithm.py | 2 +- jet_tracking/tools/simMotorMoving.py | 2 +- 22 files changed, 103 insertions(+), 98 deletions(-) diff --git a/docs/source/conf.py b/docs/source/conf.py index 08459e7..3377bc0 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -16,8 +16,7 @@ import os import sys - -import jet_tracking +import sphinx_rtd_theme # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the @@ -26,6 +25,8 @@ module_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../") sys.path.insert(0, module_path) +import jet_tracking # isort: skip # noqa: E402 + # -- General configuration ------------------------------------------------ @@ -37,7 +38,6 @@ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - "sphinxcontrib.jquery", "sphinx.ext.autodoc", "sphinx.ext.todo", "sphinx.ext.napoleon", @@ -47,6 +47,10 @@ "sphinx.ext.viewcode", "sphinx.ext.githubpages", "sphinx.ext.intersphinx", + # jquery removed in sphinx 6.0 and used in docs_versions_menu. + # See: https://www.sphinx-doc.org/en/master/changes.html + "sphinxcontrib.jquery", + "docs_versions_menu", ] # Add any paths that contain templates here, relative to this directory. @@ -81,6 +85,8 @@ # The full version, including alpha/beta/rc tags. release = str(jet_tracking.__version__) +rtd_version = getattr(sphinx_rtd_theme, "__version__", "unknown") +print(f"Version: {version} using sphinx_rtd_theme version: {rtd_version}") # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # diff --git a/jet_tracking/context.py b/jet_tracking/context.py index 3070000..470a24d 100644 --- a/jet_tracking/context.py +++ b/jet_tracking/context.py @@ -534,7 +534,7 @@ def image_calibration_position(self, line_best_fit): """ g = [self.read_motor_position, line_best_fit] self.image_calibration_positions.append(g) - + def run_image_search(self): """ Run the image search algorithm. diff --git a/jet_tracking/datastream.py b/jet_tracking/datastream.py index 1e642d7..ea280f4 100644 --- a/jet_tracking/datastream.py +++ b/jet_tracking/datastream.py @@ -1,20 +1,21 @@ import logging +import threading import time +from collections import deque from statistics import StatisticsError, mean, stdev + +import cv2 import numpy as np -from ophyd import EpicsSignal from epics import caget -from PyQt5.QtCore import QThread, QObject, QCoreApplication, QEventLoop -from pcdsdevices.epics_motor import Motor -from collections import deque -import cv2 -import threading -from scipy import stats from motorMoving import MotorAction +from ophyd import EpicsSignal +from PyQt5.QtCore import QCoreApplication, QEventLoop, QObject, QThread +from scipy import stats +from sketch.simJetImage import SimulatedImage from tools.numGen import SimulationGenerator from tools.simMotorMoving import SimulatedMotor -from sketch.simJetImage import SimulatedImage +from pcdsdevices.epics_motor import Motor ologging = logging.getLogger('ophyd') ologging.setLevel('DEBUG') @@ -469,7 +470,7 @@ def set_calibration_source(self, c): The new calibration source value. """ self.calibration_source = c - + def set_num_cali(self, n): """ Set the number of calibration. @@ -990,7 +991,7 @@ def connect_signals(self): self.signals.stopImageThread.connect(self.stop_it) self.signals.comDetection.connect(self.set_com_on) self.signals.linesInfo.connect(self.set_line_positions) - + def set_line_positions(self, ul, lr): """ Set the upper left and lower right line positions. @@ -1007,7 +1008,7 @@ def set_com_on(self): Set the find_com_bool flag. """ self.find_com_bool = self.context.find_com_bool - + def start_comm(self): """ Start the communication process for image feed processing. @@ -1016,7 +1017,7 @@ def start_comm(self): QCoreApplication.processEvents(QEventLoop.AllEvents, int(self.refresh_rate*1000)) self.run_image_thread() - + def start_it(self): """ Start the image processing thread. @@ -1036,7 +1037,7 @@ def stop_it(self, abort): self.thread().requestInterruption() else: pass - + def start_algorithm(self): """ Start the image processing algorithm. @@ -1162,7 +1163,7 @@ def editor(self, im): ret, im = cv2.threshold(im, self.left_threshold, self.right_threshold, cv2.THRESH_BINARY) return im - + def find_center(self, im): """ Find the center of a jet in the given image. @@ -1170,13 +1171,13 @@ def find_center(self, im): Args: im: The input image. """ - self.locate_jet(im, int(self.upper_left[0]), int(self.lower_right[0]), + self.locate_jet(im, int(self.upper_left[0]), int(self.lower_right[0]), int(self.upper_left[1]), int(self.lower_right[1])) if self.counter != 20: self.counter += 1 elif self.counter == 20: self.counter = 0 - success = self.form_line(self.context.com, int(self.upper_left[1]), + success = self.form_line(self.context.com, int(self.upper_left[1]), int(self.lower_right[1])) self.context.com = [] if success and self.request_for_calibration: @@ -1200,8 +1201,8 @@ def locate_jet(self, im, x_start, x_end, y_start, y_end): crop = im[y_start:y_end, x_start:x_end] crop = cv2.convertScaleAbs(crop) self.context.contours, hierarchy = cv2.findContours(crop, cv2.RETR_EXTERNAL, - cv2.CHAIN_APPROX_SIMPLE, - offset=(x_start, y_start)) + cv2.CHAIN_APPROX_SIMPLE, + offset=(x_start, y_start)) if len(self.context.contours) == 0: self.signals.message.emit("Was not able to find any contours. \n" "Try changing the ROI or image editing " diff --git a/jet_tracking/gui/views/jetTrackerView.py b/jet_tracking/gui/views/jetTrackerView.py index c9163c5..0b4744d 100644 --- a/jet_tracking/gui/views/jetTrackerView.py +++ b/jet_tracking/gui/views/jetTrackerView.py @@ -66,4 +66,4 @@ def create_dock_widgets(self): self.controlsWidget = ControlsWidget(self.context, self.signals) self.controlsDock.setWidget(self.controlsWidget) self.controlsDock.setSizePolicy(QSizePolicy.Preferred, - QSizePolicy.Preferred) \ No newline at end of file + QSizePolicy.Preferred) diff --git a/jet_tracking/gui/views/simultationView.py b/jet_tracking/gui/views/simultationView.py index 2fe202f..c4832eb 100644 --- a/jet_tracking/gui/views/simultationView.py +++ b/jet_tracking/gui/views/simultationView.py @@ -16,4 +16,4 @@ def __init__(self, context, signals, parent=None): self.setLayout(self.mainLayout) def create_editor_widget(self): - self.simControlWidget = SimWidget(self.context, self.signals) \ No newline at end of file + self.simControlWidget = SimWidget(self.context, self.signals) diff --git a/jet_tracking/gui/widgets/controlWidgetUi.py b/jet_tracking/gui/widgets/controlWidgetUi.py index e06c95a..167e54d 100644 --- a/jet_tracking/gui/widgets/controlWidgetUi.py +++ b/jet_tracking/gui/widgets/controlWidgetUi.py @@ -1,8 +1,7 @@ -from gui.widgets.basicWidgets import (CollapsibleBox, Label, - LineEdit, QHLine) -from PyQt5.QtWidgets import (QButtonGroup, QFrame, QGridLayout, QHBoxLayout, - QLCDNumber, QPushButton, QRadioButton, - QSizePolicy, QTextEdit, QVBoxLayout, QComboBox) +from gui.widgets.basicWidgets import CollapsibleBox, Label, LineEdit, QHLine +from PyQt5.QtWidgets import (QButtonGroup, QComboBox, QFrame, QGridLayout, + QHBoxLayout, QLCDNumber, QPushButton, + QRadioButton, QSizePolicy, QTextEdit, QVBoxLayout) class Controls_Ui: diff --git a/jet_tracking/gui/widgets/editorWidget.py b/jet_tracking/gui/widgets/editorWidget.py index a0865f4..f16409f 100644 --- a/jet_tracking/gui/widgets/editorWidget.py +++ b/jet_tracking/gui/widgets/editorWidget.py @@ -1,9 +1,10 @@ import logging from collections import deque + from datastream import JetImageFeed from gui.widgets.editorWidgetUi import Editor_Ui -from PyQt5.QtWidgets import QFrame from PyQt5.QtCore import QThread +from PyQt5.QtWidgets import QFrame log = logging.getLogger(__name__) @@ -82,13 +83,13 @@ def calibrate(self): if self.worker_image.connected and not self.worker_image.paused: self.context.calibrate_image() else: - self.signals.message.emit("The image feed is not live or the" - "application is stopped try to connect" + self.signals.message.emit("The image feed is not live or the" + "application is stopped try to connect" "camera") - + def search(self): self.context.run_image_search() - + def reset_all(self): self.sliders = {'dilate': deque([None], 5), 'erode': deque([None], 5), @@ -100,7 +101,7 @@ def reset_all(self): 'left threshold': deque([110], 5), 'right threshold': deque([255], 5)} self.signals.imageProcessing.emit(self.sliders) - + def display_message(self, message): pt = self.text_area.toPlainText() if pt.split('\n')[-1] == message.split('\n')[-1]: @@ -179,7 +180,7 @@ def close_off_on(self, enabled): self.slider_open.setEnabled(not enabled) self.sliders['open'].append(None) self.signals.imageProcessing.emit(self.sliders) - + def terminate_all(self): self.signals.stopImageThread.emit(True) self.thread1.quit() diff --git a/jet_tracking/gui/widgets/editorWidgetUi.py b/jet_tracking/gui/widgets/editorWidgetUi.py index 55ce0ec..db05ec6 100644 --- a/jet_tracking/gui/widgets/editorWidgetUi.py +++ b/jet_tracking/gui/widgets/editorWidgetUi.py @@ -1,7 +1,7 @@ from gui.widgets.basicWidgets import QHLine, QRangeSlider from PyQt5.Qt import Qt -from PyQt5.QtWidgets import (QHBoxLayout, QLabel, QPushButton, QRadioButton, - QSlider, QVBoxLayout, QButtonGroup, QTextEdit) +from PyQt5.QtWidgets import (QButtonGroup, QHBoxLayout, QLabel, QPushButton, + QRadioButton, QSlider, QTextEdit, QVBoxLayout) class Editor_Ui: @@ -89,7 +89,7 @@ def setupUi(self, obj): obj.bttn_search = QPushButton("Search for Jet") obj.bttn_reset_all = QPushButton("Reset All Image Morphologies") - + obj.text_area = QTextEdit("~~~read only information for user~~~") obj.text_area.setReadOnly(True) @@ -145,7 +145,7 @@ def setupUi(self, obj): obj.layout.addWidget(obj.bttn_cam_calibrate) obj.layout.addLayout(obj.layout_com) - + obj.hline0 = QHLine() obj.layout.addWidget(obj.hline0) obj.layout.addWidget(obj.lbl_dilate) diff --git a/jet_tracking/gui/widgets/graphWidget.py b/jet_tracking/gui/widgets/graphWidget.py index aecc42e..c3eb2d3 100644 --- a/jet_tracking/gui/widgets/graphWidget.py +++ b/jet_tracking/gui/widgets/graphWidget.py @@ -1,12 +1,13 @@ import logging +import warnings +from collections import deque -from gui.widgets.graphWidgetUi import GraphsUi -from PyQt5.QtWidgets import QFrame -from PyQt5.QtCore import Qt import numpy as np -from collections import deque import pyqtgraph as pg -import warnings +from gui.widgets.graphWidgetUi import GraphsUi +from PyQt5.QtCore import Qt +from PyQt5.QtWidgets import QFrame + warnings.filterwarnings('ignore') log = logging.getLogger(__name__) diff --git a/jet_tracking/gui/widgets/jetImageWidget.py b/jet_tracking/gui/widgets/jetImageWidget.py index acf4521..a7e04d2 100644 --- a/jet_tracking/gui/widgets/jetImageWidget.py +++ b/jet_tracking/gui/widgets/jetImageWidget.py @@ -1,11 +1,12 @@ import logging -from PyQt5.QtWidgets import QGraphicsPixmapItem, QGraphicsView -from tools.ROI import HLineItem, VLineItem, GraphicsScene, GraphicsRectItem -from PyQt5.QtCore import Qt -from PyQt5.QtGui import QPixmap, QImage + +import cv2 import numpy as np +from PyQt5.QtCore import Qt +from PyQt5.QtGui import QImage, QPixmap +from PyQt5.QtWidgets import QGraphicsPixmapItem, QGraphicsView from qimage2ndarray import array2qimage -import cv2 +from tools.ROI import GraphicsRectItem, GraphicsScene, HLineItem, VLineItem log = logging.getLogger("jet_tracker") @@ -47,7 +48,7 @@ def connect_scene(self): self.scene.addItem(self.line_item_hor_bot) self.scene.addItem(self.line_item_hor_top) self.scene.addItem(self.rect) - + def make_connections(self): self.signals.camImager.connect(self.update_image) self.scene.sceneRectChanged.connect(self.capture_scene_change) @@ -61,9 +62,9 @@ def rect_pos(self): self.beam_location = (pixmap_coord.x(), pixmap_coord.y()) def send_line_pos(self): - upper_left = (self.line_item_vert_left.pos().x(), + upper_left = (self.line_item_vert_left.pos().x(), self.line_item_hor_top.pos().y()) - lower_right = (self.line_item_vert_right.pos().x(), + lower_right = (self.line_item_vert_right.pos().x(), self.line_item_hor_bot.pos().y()) self.signals.linesInfo.emit(upper_left, lower_right) @@ -81,24 +82,24 @@ def update_image(self, im): self.context.contours, -1, (0, 255, 0), 3) if self.find_com_bool: for point in self.context.com: - self.color_image = cv2.circle(self.color_image, + self.color_image = cv2.circle(self.color_image, tuple(point), 1, (0, 255, 255)) if len(self.context.best_fit_line): - self.color_image = cv2.line(self.color_image, + self.color_image = cv2.line(self.color_image, tuple(self.context.best_fit_line[1]), - tuple(self.context.best_fit_line[0]), + tuple(self.context.best_fit_line[0]), (0, 255, 255), 2) if len(self.context.best_fit_line_plus): - self.color_image = cv2.line(self.color_image, + self.color_image = cv2.line(self.color_image, tuple(self.context.best_fit_line_plus[1]), - tuple(self.context.best_fit_line_plus[0]), + tuple(self.context.best_fit_line_plus[0]), (220, 20, 60), 1) if len(self.context.best_fit_line_minus): self.color_image = cv2.line(self.color_image, tuple(self.context.best_fit_line_minus[1]), - tuple(self.context.best_fit_line_minus[0]), + tuple(self.context.best_fit_line_minus[0]), (220, 20, 60), 1) self.qimage = array2qimage(self.color_image) - pixmap = QPixmap.fromImage(self.qimage) + pixmap = QPixmap.fromImage(self.qimage) self.pixmap_item.setPixmap(pixmap) if not self.image_displayed: self.image_displayed = True diff --git a/jet_tracking/gui/widgets/simControlWidget.py b/jet_tracking/gui/widgets/simControlWidget.py index edca45d..cf4278d 100644 --- a/jet_tracking/gui/widgets/simControlWidget.py +++ b/jet_tracking/gui/widgets/simControlWidget.py @@ -1,7 +1,8 @@ -from PyQt5.QtWidgets import QFrame -from gui.widgets.simControlWidgetUi import SimUi import logging +from gui.widgets.simControlWidgetUi import SimUi +from PyQt5.QtWidgets import QFrame + log = logging.getLogger(__name__) diff --git a/jet_tracking/gui/widgets/simControlWidgetUi.py b/jet_tracking/gui/widgets/simControlWidgetUi.py index 0a0f4aa..cf35854 100644 --- a/jet_tracking/gui/widgets/simControlWidgetUi.py +++ b/jet_tracking/gui/widgets/simControlWidgetUi.py @@ -1,5 +1,5 @@ from gui.widgets.basicWidgets import LineEdit -from PyQt5.QtWidgets import (QHBoxLayout, QLabel, QVBoxLayout) +from PyQt5.QtWidgets import QHBoxLayout, QLabel, QVBoxLayout class SimUi: diff --git a/jet_tracking/gui/windows/mainWindow.py b/jet_tracking/gui/windows/mainWindow.py index 3a83e90..6e31bf9 100644 --- a/jet_tracking/gui/windows/mainWindow.py +++ b/jet_tracking/gui/windows/mainWindow.py @@ -1,5 +1,6 @@ import logging import sys + from context import Context from gui.views.jetImageView import JetImageView from gui.views.jetTrackerView import JetTrackerView @@ -10,6 +11,7 @@ from PyQt5.QtWidgets import (QAction, QLabel, QMainWindow, QSizePolicy, QTabWidget) from signals import Signals + sys.path.append('/cds/group/pcds/epics-dev/ajshack/jet_tracking/jet_tracking/pyqt-stylesheets/') import pyqtcss diff --git a/jet_tracking/jt_configs/Geoo.qss b/jet_tracking/jt_configs/Geoo.qss index dbc5e38..36eef9e 100644 --- a/jet_tracking/jt_configs/Geoo.qss +++ b/jet_tracking/jt_configs/Geoo.qss @@ -40,7 +40,7 @@ QLabel /*-----QMenuBar-----*/ -QMenuBar +QMenuBar { background-color: #323232; font-size:20px; @@ -160,7 +160,7 @@ QLineEdit{ /*-----QTreeView-----*/ -QTreeView +QTreeView { background-color: #434343; border: 0.5px solid rgba(108,108,108,75); @@ -169,8 +169,8 @@ QTreeView } -QTreeView::item, -QTreeView::branch +QTreeView::item, +QTreeView::branch { background: transparent; color: #DDD; @@ -178,8 +178,8 @@ QTreeView::branch } -QTreeView::item:hover, -QTreeView::branch:hover +QTreeView::item:hover, +QTreeView::branch:hover { background-color: #55aaff; color: #DDD; @@ -187,8 +187,8 @@ QTreeView::branch:hover } -QTreeView::item:selected, -QTreeView::branch:selected +QTreeView::item:selected, +QTreeView::branch:selected { background-color: #55aaff; color: #fff; @@ -197,7 +197,7 @@ QTreeView::branch:selected /*-----QScrollBar-----*/ -QScrollBar:horizontal +QScrollBar:horizontal { background-color: #333; height: 8px; @@ -208,7 +208,7 @@ QScrollBar:horizontal } -QScrollBar::handle:horizontal +QScrollBar::handle:horizontal { border: 1px solid #111; background-color: #535353; @@ -217,7 +217,7 @@ QScrollBar::handle:horizontal QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal, -QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal +QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal { width: 0px; background-color: transparent; @@ -225,7 +225,7 @@ QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal } -QScrollBar:vertical +QScrollBar:vertical { background-color: #333; width: 8px; @@ -234,7 +234,7 @@ QScrollBar:vertical } -QScrollBar::handle:vertical +QScrollBar::handle:vertical { border: 1px solid #111; background-color: #535353; @@ -243,7 +243,7 @@ QScrollBar::handle:vertical QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical, -QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical +QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { height: 0px; background-color: transparent; @@ -266,4 +266,4 @@ QRadioButton::indicator { width: 15px; height: 15px; border-radius: 5px; -} \ No newline at end of file +} diff --git a/jet_tracking/jt_configs/License.txt b/jet_tracking/jt_configs/License.txt index 287e9a8..0aaf2f8 100644 --- a/jet_tracking/jt_configs/License.txt +++ b/jet_tracking/jt_configs/License.txt @@ -17,4 +17,4 @@ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/jet_tracking/motorMoving.py b/jet_tracking/motorMoving.py index 43e7712..1c448da 100644 --- a/jet_tracking/motorMoving.py +++ b/jet_tracking/motorMoving.py @@ -16,7 +16,10 @@ """ import logging -from tools.motorAlgorithm import TernarySearch, BasicScan, LinearTernary, DynamicLinear + +from tools.motorAlgorithm import (BasicScan, DynamicLinear, LinearTernary, + TernarySearch) + logger = logging.getLogger(__name__) diff --git a/jet_tracking/signals.py b/jet_tracking/signals.py index e204e4a..c573423 100644 --- a/jet_tracking/signals.py +++ b/jet_tracking/signals.py @@ -125,7 +125,7 @@ class Signals(QtCore.QObject): Args: float: the motor position of max value. - float: The max value + float: The max value list: List of X-coordinates for the motor moves. list: List of Y-coordinates for the motor moves. """ @@ -385,10 +385,3 @@ class Signals(QtCore.QObject): Args: float: The new background intensity value. """ - - - - - - - diff --git a/jet_tracking/sketch/simJetImage.py b/jet_tracking/sketch/simJetImage.py index 8b34e82..226ef6d 100644 --- a/jet_tracking/sketch/simJetImage.py +++ b/jet_tracking/sketch/simJetImage.py @@ -61,6 +61,3 @@ def gen_image(self): self.jet_im = np.full((self.y_size, self.x_size), 0, dtype=np.uint8) self.jet_im = jet_display(self.jet_im, self.motor_position, self.context.jet_center, self.pix_per_mm, self.x_size) - - - diff --git a/jet_tracking/tools/ROI.py b/jet_tracking/tools/ROI.py index 0dc7380..60b0d99 100644 --- a/jet_tracking/tools/ROI.py +++ b/jet_tracking/tools/ROI.py @@ -1,6 +1,7 @@ -from PyQt5.QtWidgets import QGraphicsLineItem, QGraphicsScene, QGraphicsItem, QGraphicsRectItem -from PyQt5.QtCore import QPointF, Qt, pyqtSignal, QRectF -from PyQt5.QtGui import QPen, QBrush, QColor, QPainter, QPainterPath +from PyQt5.QtCore import QPointF, QRectF, Qt, pyqtSignal +from PyQt5.QtGui import QBrush, QColor, QPainter, QPainterPath, QPen +from PyQt5.QtWidgets import (QGraphicsItem, QGraphicsLineItem, + QGraphicsRectItem, QGraphicsScene) class GraphicsScene(QGraphicsScene): diff --git a/jet_tracking/tools/imGen.py b/jet_tracking/tools/imGen.py index 8e380de..37b144f 100644 --- a/jet_tracking/tools/imGen.py +++ b/jet_tracking/tools/imGen.py @@ -1,5 +1,5 @@ -import numpy as np import cv2 +import numpy as np def read_noise(image, amount, gain=1): @@ -38,4 +38,3 @@ def jet_display(img, mp, jet_center, pix_per_mm, x_size): final_image = img + blackhat + erode #final_image = img return final_image - diff --git a/jet_tracking/tools/motorAlgorithm.py b/jet_tracking/tools/motorAlgorithm.py index 4659fe2..2694a36 100644 --- a/jet_tracking/tools/motorAlgorithm.py +++ b/jet_tracking/tools/motorAlgorithm.py @@ -16,6 +16,7 @@ """ import logging + logger = logging.getLogger(__name__) @@ -369,4 +370,3 @@ def compare_and_move(self): self.low = self.mid1 self.high = self.high self.max_value = i2 - diff --git a/jet_tracking/tools/simMotorMoving.py b/jet_tracking/tools/simMotorMoving.py index f767795..437d06f 100644 --- a/jet_tracking/tools/simMotorMoving.py +++ b/jet_tracking/tools/simMotorMoving.py @@ -1,5 +1,5 @@ -import time import logging +import time log = logging.getLogger(__name__) From 41b4442147ff70245aa3a308cf43f54804c48c6f Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:52:26 -0700 Subject: [PATCH 18/30] STY: manually fix up style issues --- jet_tracking/context.py | 50 ++++---- jet_tracking/datastream.py | 134 ++++++++++++-------- jet_tracking/gui/widgets/basicWidgets.py | 4 +- jet_tracking/gui/widgets/controlWidget.py | 12 +- jet_tracking/gui/widgets/controlWidgetUi.py | 26 ++-- jet_tracking/gui/widgets/graphWidget.py | 25 ++-- jet_tracking/gui/widgets/graphWidgetUi.py | 28 ++-- jet_tracking/gui/windows/mainWindow.py | 5 +- jet_tracking/main.py | 10 +- jet_tracking/motorMoving.py | 25 ++-- jet_tracking/tools/imGen.py | 2 +- jet_tracking/tools/numGen.py | 9 +- 12 files changed, 186 insertions(+), 144 deletions(-) diff --git a/jet_tracking/context.py b/jet_tracking/context.py index 470a24d..aca8220 100644 --- a/jet_tracking/context.py +++ b/jet_tracking/context.py @@ -96,7 +96,7 @@ def __init__(self, signals): 'dropped': 'CXI:JTRK:REQ:DROPPED', 'camera': 'XCS:GIGE:LJ2', 'motor': 'XCS:LJH:JET:Y'} - #self.CFG_FILE = 'jt_configs/cxi_config.yml' + # self.CFG_FILE = 'jt_configs/cxi_config.yml' self.HUTCH = 'cxi' self.EXPERIMENT = 'cxix53419' # end of defaults @@ -111,30 +111,30 @@ def __init__(self, signals): 'jet_tracking/jt_configs/') self.JT_CFG = ''.join([self.JT_LOC, self.args.cfg]) - #with open(self.JT_CFG) as f: - # yml_dict = yaml.load(f, Loader=yaml.FullLoader) - # self.ipm_name = yml_dict['ipm']['name'] - # self.motor = yml_dict['motor']['name'] - # self.jet_cam_name = yml_dict['jet_cam']['name'] - # self.jet_cam_axis = yml_dict['jet_cam']['axis'] - # self.HUTCH = yml_dict['hutch'] - # self.EXPERIMENT = os.environ.get('EXPERIMENT', - # yml_dict['experiment']) - # self.pv_map = yml_dict['pv_map'] - - #if self.jet_cam_name == 'None' or self.jet_cam_name == 'none': - # self.jet_came_name = None - - #if self.motor == 'None' or self.motor == 'none': - # print('Please provide a motor PV in the config file') - - #self.pv_map['diff'] = self.pv_map.pop(1) - #self.pv_map['i0'] = self.pv_map.pop(2) - #self.pv_map['ratio'] = self.pv_map.pop(3) - #self.pv_map['dropped'] = self.pv_map.pop(4) - #self.pv_map['camera'] = self.jet_cam_name - #self.pv_map['motor'] = self.motor - #self.PV_DICT = self.pv_map + # with open(self.JT_CFG) as f: + # yml_dict = yaml.load(f, Loader=yaml.FullLoader) + # self.ipm_name = yml_dict['ipm']['name'] + # self.motor = yml_dict['motor']['name'] + # self.jet_cam_name = yml_dict['jet_cam']['name'] + # self.jet_cam_axis = yml_dict['jet_cam']['axis'] + # self.HUTCH = yml_dict['hutch'] + # self.EXPERIMENT = os.environ.get('EXPERIMENT', + # yml_dict['experiment']) + # self.pv_map = yml_dict['pv_map'] + + # if self.jet_cam_name == 'None' or self.jet_cam_name == 'none': + # self.jet_came_name = None + + # if self.motor == 'None' or self.motor == 'none': + # print('Please provide a motor PV in the config file') + + # self.pv_map['diff'] = self.pv_map.pop(1) + # self.pv_map['i0'] = self.pv_map.pop(2) + # self.pv_map['ratio'] = self.pv_map.pop(3) + # self.pv_map['dropped'] = self.pv_map.pop(4) + # self.pv_map['camera'] = self.jet_cam_name + # self.pv_map['motor'] = self.motor + # self.PV_DICT = self.pv_map self.live_data = True self.calibration_source = "calibration from results" diff --git a/jet_tracking/datastream.py b/jet_tracking/datastream.py index ea280f4..ba979fa 100644 --- a/jet_tracking/datastream.py +++ b/jet_tracking/datastream.py @@ -521,12 +521,12 @@ def calculate_averages(self): avei0 = mean(list(i0)) avediff = mean(list(diff)) averatio = mean(list(ratio)) - vals = [avei0, avediff, averatio] except StatisticsError: - vals = [0, 0, 0] - self.averages['i0'].append(avei0) - self.averages['diff'].append(avediff) - self.averages['ratio'].append(averatio) + ... + else: + self.averages['i0'].append(avei0) + self.averages['diff'].append(avediff) + self.averages['ratio'].append(averatio) def update_buffer(self, vals): """ @@ -547,8 +547,7 @@ def check_status_update(self): Check the status update based on the flagged events and emit signals accordingly. """ if self.calibrated: - p = int(self.notification_tolerance + \ - (self.notification_tolerance*0.5)) # plus 10% of notification tolerance + p = int(1.5 * self.notification_tolerance) # plus 10% of notification tolerance miss = np.array(self.flagged_events['missed shot'])[-p:] drop = np.array(self.flagged_events['dropped shot'])[-p:] high = np.array(self.flagged_events['high intensity'])[-p:] @@ -557,26 +556,27 @@ def check_status_update(self): n_high = np.count_nonzero(high[~np.isnan(high)]) if n_miss > self.notification_tolerance: self.signals.changeStatus.emit("Warning, missed shots", "red") - self.processor_worker.count_flags_and_execute('missed shot', 20, - self.missed_shots) + self.processor_worker.count_flags_and_execute( + "missed shot", 20, self.missed_shots + ) elif n_drop > self.notification_tolerance: - self.signals.changeStatus.emit("Lots of dropped shots", - "yellow") - self.processor_worker.count_flags_and_execute('dropped shot', 20, - self.dropped_shots) + self.signals.changeStatus.emit("Lots of dropped shots", "yellow") + self.processor_worker.count_flags_and_execute( + "dropped shot", 20, self.dropped_shots + ) elif n_high > self.notification_tolerance: self.signals.changeStatus.emit("High Intensity", "orange") - self.processor_worker.count_flags_and_execute('high intensity', 20, - self.high_intensity) + self.processor_worker.count_flags_and_execute( + "high intensity", 20, self.high_intensity + ) else: if not self.processor_worker.isCounting: - self.signals.changeStatus.emit("Everything is good", - "green") + self.signals.changeStatus.emit("Everything is good", "green") self.everything_is_good() if self.processor_worker.isCounting: - self.processor_worker.count_flags_and_execute("everything is good", - 50, - self.everything_is_good) + self.processor_worker.count_flags_and_execute( + "everything is good", 50, self.everything_is_good + ) elif not self.calibrated: self.signals.changeStatus.emit("not calibrated", "orange") @@ -920,7 +920,7 @@ def count_flags_and_execute(self, new_flag, num_flagged, func_to_execute): if new_flag in self.flag_type.copy(): self.flag_type[new_flag] += 1 if num_flagged == self.flag_type[new_flag]: - del(self.flag_type[new_flag]) + self.flag_type.pop(new_flag) func_to_execute() else: self.flag_type[new_flag] = 1 @@ -928,7 +928,7 @@ def count_flags_and_execute(self, new_flag, num_flagged, func_to_execute): if key != new_flag: self.flag_type[key] -= 1 if self.flag_type[key] <= 0: - del(self.flag_type[key]) + self.flag_type.pop(key) def stop_count(self): """ @@ -1200,22 +1200,28 @@ def locate_jet(self, im, x_start, x_end, y_start, y_end): """ crop = im[y_start:y_end, x_start:x_end] crop = cv2.convertScaleAbs(crop) - self.context.contours, hierarchy = cv2.findContours(crop, cv2.RETR_EXTERNAL, - cv2.CHAIN_APPROX_SIMPLE, - offset=(x_start, y_start)) + self.context.contours, _ = cv2.findContours( + crop, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE, offset=(x_start, y_start) + ) if len(self.context.contours) == 0: - self.signals.message.emit("Was not able to find any contours. \n" - "Try changing the ROI or image editing " - "parameters") + self.signals.message.emit( + "Was not able to find any contours. \n" + "Try changing the ROI or image editing parameters" + ) else: - contours = [] # Did I intend to leave out the first contours detected above? + contours = ( + [] + ) # Did I intend to leave out the first contours detected above? kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) empty = False while not empty: crop = cv2.erode(crop, kernel, iterations=1) - c, h = cv2.findContours(crop, cv2.RETR_EXTERNAL, - cv2.CHAIN_APPROX_SIMPLE, - offset=(x_start, y_start)) + c, _ = cv2.findContours( + crop, + cv2.RETR_EXTERNAL, + cv2.CHAIN_APPROX_SIMPLE, + offset=(x_start, y_start), + ) for cont in c: contours.append(cont) if len(c) == 0: @@ -1257,36 +1263,52 @@ def form_line(self, com, y_min, y_max): y = np.asarray(list(xypoints[0])) x = np.asarray(list(xypoints[1])) res = stats.linregress(x, y) + if res is None: + return False + # for 95% confidence slope = res.slope intercept = res.intercept confidence_interval = 95 - pvalue = res.pvalue # if p-value is > .1 get another image and try again + # pvalue = res.pvalue # if p-value is > .1 get another image and try again slope_err = res.stderr intercept_err = res.intercept_stderr alpha = 1 - (confidence_interval / 100) - critical_prob = 1 - alpha/2 + # critical_prob = 1 - alpha/2 degrees_of_freedom = len(com) - 2 - tinv = lambda p, df: abs(stats.t.ppf(p/2., df)) + + def tinv(p, df): + return abs(stats.t.ppf(p/2., df)) + ts = tinv(alpha, degrees_of_freedom) y = np.append(y, [y_min, y_max]) - if slope: - x_model = (y - intercept)*(1/slope) - x_model_plus = (y - intercept - ts*intercept_err)*(1 / (slope + ts*slope_err)) - x_model_minus = (y - intercept + ts * intercept_err) * (1 / (slope - ts * slope_err)) - yl = list(y) - i_max = yl.index(max(yl)) - i_min = yl.index(min(yl)) - self.context.best_fit_line = [[int(yl[i_min]), int(x_model[i_min])], - [int(yl[i_max]), int(x_model[i_max])]] - self.context.best_fit_line_plus = [[int(yl[i_min]), int(x_model_plus[i_min])], - [int(yl[i_max]), int(x_model_plus[i_max])]] - self.context.best_fit_line_minus = [[int(yl[i_min]), int(x_model_minus[i_min])], - [int(yl[i_max]), int(x_model_minus[i_max])]] - return True - else: + if not slope: return False + x_model = (y - intercept) * (1 / slope) + x_model_plus = (y - intercept - ts * intercept_err) * ( + 1 / (slope + ts * slope_err) + ) + x_model_minus = (y - intercept + ts * intercept_err) * ( + 1 / (slope - ts * slope_err) + ) + yl = list(y) + i_max = yl.index(max(yl)) + i_min = yl.index(min(yl)) + self.context.best_fit_line = [ + [int(yl[i_min]), int(x_model[i_min])], + [int(yl[i_max]), int(x_model[i_max])], + ] + self.context.best_fit_line_plus = [ + [int(yl[i_min]), int(x_model_plus[i_min])], + [int(yl[i_max]), int(x_model_plus[i_max])], + ] + self.context.best_fit_line_minus = [ + [int(yl[i_min]), int(x_model_minus[i_min])], + [int(yl[i_max]), int(x_model_minus[i_max])], + ] + return True + def run_image_thread(self): """ Run the image processing thread. @@ -1301,8 +1323,10 @@ def run_image_thread(self): if self.connected: if self.context.live_data: image_array = caget(self.cam_name + ':IMAGE1:ArrayData') - image = np.reshape(image_array, (self.array_size_y_viewer, - self.array_size_x_viewer)) + image = np.reshape( + image_array, + (self.array_size_y_viewer, self.array_size_x_viewer), + ) else: self.cam_name.gen_image() image = self.cam_name.jet_im @@ -1511,7 +1535,7 @@ def change_motor_mode(self, m): if not self.connected: try: self.connect_to_motor() - except: + except Exception: self.mode = "sleep" if self.connected: if m == 'sleep' and self.mode == 'run': @@ -1574,7 +1598,7 @@ def connect_to_motor(self): """ if self.live: self.motor_name = self.context.PV_DICT.get('motor', None) - self.signals.message.emit("Trying to connect to: "+ self.motor_name) + self.signals.message.emit(f"Trying to connect to: {self.motor_name}") try: self.motor = Motor(self.motor_name, name='jet_x') time.sleep(1) @@ -1586,7 +1610,7 @@ def connect_to_motor(self): self.signals.message.emit(f"Could not connect to the PVs for the motor, {type(e).__name__}") else: self.connected = False - self.signals.message.emit(f"Could not connect to the PVs for the motor.") + self.signals.message.emit("Could not connect to the PVs for the motor.") elif not self.live: self.motor = SimulatedMotor(self.context, self.signals) self.context.update_motor_position(self.motor.position) diff --git a/jet_tracking/gui/widgets/basicWidgets.py b/jet_tracking/gui/widgets/basicWidgets.py index 73e9ead..06e25a7 100644 --- a/jet_tracking/gui/widgets/basicWidgets.py +++ b/jet_tracking/gui/widgets/basicWidgets.py @@ -123,9 +123,7 @@ def setContentLayout(self, layout): lay = self.content_area.layout() self.clear_layout(lay) self.content_area.setLayout(layout) - collapsed_height = ( - self.sizeHint().height() - self.content_area.maximumHeight() - ) + collapsed_height = self.sizeHint().height() - self.content_area.maximumHeight() content_height = layout.sizeHint().height() for i in range(self.toggle_animation.animationCount()): animation = self.toggle_animation.animationAt(i) diff --git a/jet_tracking/gui/widgets/controlWidget.py b/jet_tracking/gui/widgets/controlWidget.py index e188fc8..6a771ba 100644 --- a/jet_tracking/gui/widgets/controlWidget.py +++ b/jet_tracking/gui/widgets/controlWidget.py @@ -197,7 +197,7 @@ def _stop_motor(self): self.signals.stopMotorThread.emit(False) self.signals.message.emit("The motor was stopped" "either press start or connect motor") - #self.context.update_tracking(False) + # self.context.update_tracking(False) self.set_tracking_status('disabled', "red") else: self.signals.message.emit("The motor is not running") @@ -363,8 +363,10 @@ def show_dialog(self, go_from, go_to): go_to (str): The new data viewing option. """ self.msg.setWindowTitle("Data Viewing Changes") - self.msg.setText(f"Would you like to change the \n" - f"data from {go_from} to {go_to}?") + self.msg.setText( + f"Would you like to change the \n" + f"data from {go_from} to {go_to}?" + ) self.msg.show() def popup_clicked(self, i): @@ -377,10 +379,10 @@ def popup_clicked(self, i): if i.text() == "&Yes": self._stop() self.signals.message.emit("Must press start to run in this new mode") - if self.bttngrp1.checkedId() == 1: # live + if self.bttngrp1.checkedId() == 1: # live self.context.update_live_graphing(True) self.context.update_live_motor(True) - if self.bttngrp1.checkedId() == 0: # simulated + if self.bttngrp1.checkedId() == 0: # simulated self.context.update_live_graphing(False) self.context.update_live_motor(False) else: diff --git a/jet_tracking/gui/widgets/controlWidgetUi.py b/jet_tracking/gui/widgets/controlWidgetUi.py index 167e54d..384a8ab 100644 --- a/jet_tracking/gui/widgets/controlWidgetUi.py +++ b/jet_tracking/gui/widgets/controlWidgetUi.py @@ -299,21 +299,27 @@ def setupUi(self, obj): ##################################################################### obj.lbl_status = Label("Status") - obj.lbl_status.setStyleSheet("qproperty-alignment: AlignCenter;" - "border: 1px solid #FF17365D;" - "background-color: #FF17365D;" - "font-size: 28px;") + obj.lbl_status.setStyleSheet( + "qproperty-alignment: AlignCenter;" + "border: 1px solid #FF17365D;" + "background-color: #FF17365D;" + "font-size: 28px;" + ) obj.lbl_monitor = Label("Monitor") - obj.lbl_monitor.setStyleSheet("qproperty-alignment: AlignCenter;" - "border: 1px solid #FF17365D;" - "background-color: #FF17365D;") + obj.lbl_monitor.setStyleSheet( + "qproperty-alignment: AlignCenter;" + "border: 1px solid #FF17365D;" + "background-color: #FF17365D;" + ) obj.lbl_monitor_status = Label("Not Started") obj.lbl_tracking = Label("Tracking") - obj.lbl_tracking.setStyleSheet("qproperty-alignment: AlignCenter;" - "border: 1px solid #FF17365D;" - "background-color: #FF17365D;") + obj.lbl_tracking.setStyleSheet( + "qproperty-alignment: AlignCenter;" + "border: 1px solid #FF17365D;" + "background-color: #FF17365D;" + ) obj.lbl_tracking_status = Label("False") obj.lbl_tracking_status.setStyleSheet("background-color: red;") diff --git a/jet_tracking/gui/widgets/graphWidget.py b/jet_tracking/gui/widgets/graphWidget.py index c3eb2d3..c5160c8 100644 --- a/jet_tracking/gui/widgets/graphWidget.py +++ b/jet_tracking/gui/widgets/graphWidget.py @@ -117,18 +117,18 @@ def plot_data(self, buf, count): self.y_ratio[count] = buf['ratio'][-2] self.old_vals_ratio.append(self.y_ratio.popleft()) self.y_ratio.append(np.nan) - #self.y_ave[count] = buf['ratio'][-1] - #self.old_ave.append(self.y_ave.popleft()) - #self.y_ave.append(np.nan) + # self.y_ave[count] = buf['ratio'][-1] + # self.old_ave.append(self.y_ave.popleft()) + # self.y_ave.append(np.nan) else: self.y_diff[count] = buf['diff'] self.y_i0[count] = buf['i0'] self.y_ratio[count] = buf['ratio'][-2] - #self.y_ave[count] = buf['ratio'][-1] + # self.y_ave[count] = buf['ratio'][-1] self.line_diff.setData(self.x_axis, list(self.y_diff)) self.line_i0.setData(self.x_axis, list(self.y_i0)) self.line_ratio.setData(self.x_axis, list(self.y_ratio)) - #self.line_ave.setData(self.x_axis, list(self.y_ave)) + # self.line_ave.setData(self.x_axis, list(self.y_ave)) def plot_calibration(self): self.line_diff_low.setData(self.x_axis, self.diff_low_range) @@ -148,12 +148,15 @@ def set_display_time(self, t, rr): new_num_points = int(new_display_time * new_rr) n_nan_new = int(new_num_points * 1/4) if old_num_points < new_num_points: - new_points_diff = list(self.y_diff)[:int(new_num_points * 3/4)+1] + \ - [np.nan for _ in range(n_nan_new)] - new_points_i0 = list(self.y_i0)[:int(new_num_points * 3/4)+1] + \ - [np.nan for _ in range(n_nan_new)] - new_points_ratio = list(self.y_ratio)[:int(new_num_points * 3/4)+1] + \ - [np.nan for _ in range(n_nan_new)] + new_points_diff = list(self.y_diff)[: int(new_num_points * 3 / 4) + 1] + [ + np.nan for _ in range(n_nan_new) + ] + new_points_i0 = list(self.y_i0)[: int(new_num_points * 3 / 4) + 1] + [ + np.nan for _ in range(n_nan_new) + ] + new_points_ratio = list(self.y_ratio)[: int(new_num_points * 3 / 4) + 1] + [ + np.nan for _ in range(n_nan_new) + ] n = new_num_points - len(new_points_diff) if len(self.old_vals_diff) >= n: for i in range(n): diff --git a/jet_tracking/gui/widgets/graphWidgetUi.py b/jet_tracking/gui/widgets/graphWidgetUi.py index de2a6e0..2af7fb1 100644 --- a/jet_tracking/gui/widgets/graphWidgetUi.py +++ b/jet_tracking/gui/widgets/graphWidgetUi.py @@ -26,20 +26,20 @@ def setupUi(self, obj): obj.graph3.setLabel("bottom", "Seconds", **styles) obj.graph3.setTitle("Ratio") obj.graph3.showGrid(x=True, y=True) - #obj.ratio_graph = ScrollingTimeWidget(obj.context, obj.signals) - #obj.i0_graph = ScrollingTimeWidget(obj.context, obj.signals) - #obj.diff_graph = ScrollingTimeWidget(obj.context, obj.signals) - #graph_setup(obj.ratio_graph, "Intensity Ratio", - # "I/I\N{SUBSCRIPT ZERO}", pg.mkPen(width=5, color='r')) - #graph_setup(obj.i0_graph, "Initial Intensity", "I\N{SUBSCRIPT ZERO}", - # pg.mkPen(width=5, color='b')) - #graph_setup(obj.diff_graph, "Intensity at the Detector", - # "Diffraction Intensity", pg.mkPen(width=5, color='g')) - #add_calibration_graph(obj.ratio_graph) - #add_calibration_graph(obj.i0_graph) - #add_calibration_graph(obj.diff_graph) - #obj.i0_graph.setXLink(obj.ratio_graph) - #obj.diff_graph.setXLink(obj.ratio_graph) + # obj.ratio_graph = ScrollingTimeWidget(obj.context, obj.signals) + # obj.i0_graph = ScrollingTimeWidget(obj.context, obj.signals) + # obj.diff_graph = ScrollingTimeWidget(obj.context, obj.signals) + # graph_setup(obj.ratio_graph, "Intensity Ratio", + # "I/I\N{SUBSCRIPT ZERO}", pg.mkPen(width=5, color='r')) + # graph_setup(obj.i0_graph, "Initial Intensity", "I\N{SUBSCRIPT ZERO}", + # pg.mkPen(width=5, color='b')) + # graph_setup(obj.diff_graph, "Intensity at the Detector", + # "Diffraction Intensity", pg.mkPen(width=5, color='g')) + # add_calibration_graph(obj.ratio_graph) + # add_calibration_graph(obj.i0_graph) + # add_calibration_graph(obj.diff_graph) + # obj.i0_graph.setXLink(obj.ratio_graph) + # obj.diff_graph.setXLink(obj.ratio_graph) obj.layout.addWidget(obj.graph1) obj.layout.addWidget(obj.graph2) obj.layout.addWidget(obj.graph3) diff --git a/jet_tracking/gui/windows/mainWindow.py b/jet_tracking/gui/windows/mainWindow.py index 6e31bf9..cd00ea7 100644 --- a/jet_tracking/gui/windows/mainWindow.py +++ b/jet_tracking/gui/windows/mainWindow.py @@ -12,8 +12,11 @@ QTabWidget) from signals import Signals +# TODO: address this more completely sys.path.append('/cds/group/pcds/epics-dev/ajshack/jet_tracking/jet_tracking/pyqt-stylesheets/') -import pyqtcss + +import pyqtcss # noqa: E402 # isort: skip + log = logging.getLogger("jet_tracker") diff --git a/jet_tracking/main.py b/jet_tracking/main.py index e4f96b9..3ad296c 100644 --- a/jet_tracking/main.py +++ b/jet_tracking/main.py @@ -46,11 +46,11 @@ def __init__(self, sys_argv): self.setStyle("Fusion") self.mainWindow = MainWindow() self.mainWindow.setWindowTitle("jet-tracker") - #__location__ = os.getcwd() - #File = open(__location__ + '\jt_configs\Geoo.qss', 'r') - #with File: - # qss = File.read() - # self.setStyleSheet(qss) + # __location__ = os.getcwd() + # File = open(__location__ + '\jt_configs\Geoo.qss', 'r') + # with File: + # qss = File.read() + # self.setStyleSheet(qss) self.mainWindow.show() @staticmethod diff --git a/jet_tracking/motorMoving.py b/jet_tracking/motorMoving.py index 1c448da..1340ee3 100644 --- a/jet_tracking/motorMoving.py +++ b/jet_tracking/motorMoving.py @@ -58,8 +58,9 @@ def execute(self): self.ternary_search.search() if self.ternary_search.done: return True, self.ternary_search.max_value - else: return False, self.ternary_search.max_value - elif self.motor_thread.algorithm == "Basic Scan": + return False, self.ternary_search.max_value + + if self.motor_thread.algorithm == "Basic Scan": if self.stop_search: self.basic_scan.move_to_max() self.stop_search = False @@ -67,24 +68,26 @@ def execute(self): self.basic_scan.scan() if self.basic_scan.done: return True, self.basic_scan.max_value - else: return False, self.basic_scan.max_value - elif self.motor_thread.algorithm == "Linear + Ternary": + return False, self.basic_scan.max_value + + if self.motor_thread.algorithm == "Linear + Ternary": if self.stop_search: self.stop_search = False return True, self.linear_ternary.max_value self.linear_ternary.search() if self.linear_ternary.done: return True, self.linear_ternary.max_value - else: return False, self.linear_ternary.max_value - elif self.motor_thread.algorithm == "Dynamic Linear Scan": + return False, self.linear_ternary.max_value + + if self.motor_thread.algorithm == "Dynamic Linear Scan": if self.stop_search: self.stop_search = False return True, self.dyn_linear.max_value self.dyn_linear.scan() if self.dyn_linear.done: return True, self.dyn_linear.max_value - else: return False, self.dyn_linear.max_value - else: - self.signals.message.emit("That algorithm does not exist yet..") - self.stop_search = True - return True, self.motor_thread.motor.position + return False, self.dyn_linear.max_value + + self.signals.message.emit("That algorithm does not exist yet..") + self.stop_search = True + return True, self.motor_thread.motor.position diff --git a/jet_tracking/tools/imGen.py b/jet_tracking/tools/imGen.py index 37b144f..3e707af 100644 --- a/jet_tracking/tools/imGen.py +++ b/jet_tracking/tools/imGen.py @@ -36,5 +36,5 @@ def jet_display(img, mp, jet_center, pix_per_mm, x_size): kernel = np.ones((3, 3), np.uint8) blackhat = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel) final_image = img + blackhat + erode - #final_image = img + # final_image = img return final_image diff --git a/jet_tracking/tools/numGen.py b/jet_tracking/tools/numGen.py index 5fb2e28..fa5a922 100644 --- a/jet_tracking/tools/numGen.py +++ b/jet_tracking/tools/numGen.py @@ -92,9 +92,12 @@ def sim(self): # calculates length of chord of a circle if on jet or sets diff # to 0 (plus noise) if off jet if abs(self.motor_position - self.center) < self.radius: - val["diff"] = (self.max * ((2 * math.sqrt(self.radius ** 2 - - abs(self.motor_position - self.center) ** 2)) / - (2 * self.radius)) * (1 + self.bg * (a - 0.5))) + v0 = self.radius ** 2 - abs(self.motor_position - self.center) ** 2 + val["diff"] = ( + self.max + * ((2 * math.sqrt(v0)) / (2 * self.radius)) + * (1 + self.bg * (a - 0.5)) + ) val["dropped"] = False val["i0"] = self.peak_intensity * 1 + self.bg * (c - 0.5) From b242ef936e2cd00d49b488314189be2cb8be412b Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:52:44 -0700 Subject: [PATCH 19/30] BLD: add git requirement for pyqt-stylesheets (not on pypi?) --- requirements.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements.txt b/requirements.txt index f64ff6c..11ae6d0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -10,3 +10,4 @@ opencv-python matplotlib pyyaml cf-units +git+https://github.com/sommerc/pyqt-stylesheets@master From f67a78ab7652d3509c658e19466a02e12df061bb Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:58:21 -0700 Subject: [PATCH 20/30] BLD: fix up recipes + requirements --- conda-recipe/meta.yaml | 15 +++++++-------- dev-requirements.txt | 4 ++-- docs-requirements.txt | 5 ++--- jet_tracking/gui/windows/mainWindow.py | 11 +++++++++-- pyproject.toml | 3 +++ requirements.txt | 1 + 6 files changed, 24 insertions(+), 15 deletions(-) diff --git a/conda-recipe/meta.yaml b/conda-recipe/meta.yaml index a8b018b..30abd97 100644 --- a/conda-recipe/meta.yaml +++ b/conda-recipe/meta.yaml @@ -14,15 +14,13 @@ build: noarch: python script: {{ PYTHON }} -m pip install . -vv - - requirements: build: - - python {{PY_VER}}*,>=3.6 + - python {{PY_VER}}*,>=3.9 - setuptools_scm - pip run: - - python {{PY_VER}}*,>=3.6 + - python {{PY_VER}}*,>=3.9 - pcdsdevices >=2.6.0 - matplotlib - numpy @@ -33,13 +31,14 @@ requirements: - scikit-image - scipy - - test: imports: - jet_tracking - - + requires: + - pytest + - pytest-cov + - pytest-qt + - pyqt about: home: https://github.com/pcdshub/jet_tracking diff --git a/dev-requirements.txt b/dev-requirements.txt index 1acd06c..b21e21c 100644 --- a/dev-requirements.txt +++ b/dev-requirements.txt @@ -1,5 +1,5 @@ # These are required for developing the package (e.g. running the tests) but # not necessarily required for _using_ it. -coverage -flake8 pytest +pytest-cov +pytest-qt diff --git a/docs-requirements.txt b/docs-requirements.txt index 78a6c7a..2265734 100644 --- a/docs-requirements.txt +++ b/docs-requirements.txt @@ -4,7 +4,6 @@ ipython matplotlib numpydoc sphinx -sphinx_rtd_theme -doctr -doctr-versions-menu +sphinx_rtd_theme>=1.2.0 +docs-versions-menu sphinxcontrib-jquery diff --git a/jet_tracking/gui/windows/mainWindow.py b/jet_tracking/gui/windows/mainWindow.py index cd00ea7..fc0b1c5 100644 --- a/jet_tracking/gui/windows/mainWindow.py +++ b/jet_tracking/gui/windows/mainWindow.py @@ -15,7 +15,10 @@ # TODO: address this more completely sys.path.append('/cds/group/pcds/epics-dev/ajshack/jet_tracking/jet_tracking/pyqt-stylesheets/') -import pyqtcss # noqa: E402 # isort: skip +try: + import pyqtcss # noqa: E402 # isort: skip +except ImportError: + pyqtcss = None log = logging.getLogger("jet_tracker") @@ -54,7 +57,11 @@ def __init__(self): self.setAttribute(Qt.WA_AlwaysStackOnTop) self.setMinimumSize(QSize(700, 300)) self.resize(QSize(1800, 1100)) - self.setStyleSheet(pyqtcss.get_style("dark_orange")) + if pyqtcss is not None: + self.setStyleSheet(pyqtcss.get_style("dark_orange")) + else: + log.info("Optional dependency pyqtcss is unavailable") + self.signals = Signals() self.context = Context(self.signals) self.setupUi(self) diff --git a/pyproject.toml b/pyproject.toml index 75c7ee3..86d3da8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,6 +19,9 @@ include_package_data = true [project.license] file = "LICENSE.md" +[tool.pytest.ini_options] +addopts = "--cov=." + [tool.setuptools_scm] write_to = "jet_tracking/_version.py" diff --git a/requirements.txt b/requirements.txt index 11ae6d0..65083e9 100644 --- a/requirements.txt +++ b/requirements.txt @@ -10,4 +10,5 @@ opencv-python matplotlib pyyaml cf-units +PyQt5 git+https://github.com/sommerc/pyqt-stylesheets@master From 550d71c833c741e63af9b81b266ce9ca8076ce3a Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 13:59:01 -0700 Subject: [PATCH 21/30] TST: empty test suite --- jet_tracking/tests/conftest.py | 0 jet_tracking/tests/test_signals.py | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 jet_tracking/tests/conftest.py diff --git a/jet_tracking/tests/conftest.py b/jet_tracking/tests/conftest.py new file mode 100644 index 0000000..e69de29 diff --git a/jet_tracking/tests/test_signals.py b/jet_tracking/tests/test_signals.py index ce4107b..ae7a077 100644 --- a/jet_tracking/tests/test_signals.py +++ b/jet_tracking/tests/test_signals.py @@ -1,6 +1,6 @@ import logging -from jet_tracking.signals import Signals +from ..signals import Signals logger = logging.getLogger(__name__) From 4d21af9508d4c52b8edb2ece7b7c9c2f7efa4f1a Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 14:08:49 -0700 Subject: [PATCH 22/30] CLN: remove docs deploy key --- github_deploy_key_pcdshub_jet_tracking.enc | 1 - 1 file changed, 1 deletion(-) delete mode 100644 github_deploy_key_pcdshub_jet_tracking.enc diff --git a/github_deploy_key_pcdshub_jet_tracking.enc b/github_deploy_key_pcdshub_jet_tracking.enc deleted file mode 100644 index b613931..0000000 --- a/github_deploy_key_pcdshub_jet_tracking.enc +++ /dev/null @@ -1 +0,0 @@ -gAAAAABhe63jNtpDqbDUjRFRLOSTl837ax96FwexRfETEuUzaDuk_njGIvcJI00RR1ReQmbBotr92fpuC7dYGSBYm5bL4wC6TOAX5FVBCK08ZL1ohhKKgIw0odgeS8K_qUWDcFmynnV5wjf9SmD7mJPhh9fBCIRdYyr6A9wahnNmFS96nGUrbHsBGKXHGTQNj3zUWI0cwkxuu0tNh2CRkCu540u2mz6K72Xa2Vh_so58NmdgwbJWzvT6dS_E4N5gPpuXlKfVmz63bNC2V-gO4u1RmtMULq1Bl_PBJsnOvg5Z7UTGVNHag5igmTEkp7HpAf74bl_Potqn6HpEXz1GHCXu4RX2FH_ykLL7TxKV561fMd0Dfvv_pTVTGTSEqLwTXmRzQg4dnnILqZfBJOqZb4-x2kIUWWkoDg6xTBboRqnYG9tXkG71CbnrPLdvuWaV6q65qSocnGCkVcdDforw1qVlXX-p3hfN_tkPnUKnYMl7o8xErPNs0m83K81xKBng6BSj539HvEv48dwNfnES1Q2B7_oDMrGJ1XkE57b_AEW_KGsd7tWafQdQuNdQSKZR_RSnNXvqEIfhh8msIo_c7TofCdqBp43AVlRoRehu_oCyRTTcX47qPkqZ2cqy7idU7h6cUoR74JV4MQWbXTHrWz3CR_s1hZLqEfc4ltMeKgJSSEAXVKrzSEEXpMnSk8mDRvKGAIWCQuXTgp_iYV02HLMjb7mt6Hps0JObR_Bs15zaS79QpXFs52zcktR7KwPgDawsqqS6pWU27quds1sTMfD1L1Bjwm14C1vq4POajX9tydkSJ9B6BP_dRpdr3PHYtoFOTD3jomObzb75m9gAV9XFTyUtcUpSl57bIFcSTGKRAlT6xukRajCWHCfx5j9qp4x3Mhma7_Gc3PKROVDBw1cO4B9LMzQo6StcaQuxLlVN8OK5wzSZEQlcFdT2PFqWGx0Kt1tdppbIp53nzIqWKDSDYCPPMqJBxXc6pXP37e2h2fIBIQSKQNSyaeLjKl6J5Ficyu65SP2hCrlTCq5mUfz6Cbs0ok3MHppWpR9iTSmQOiBewZh6w-mSYJTqEU4kUY3IavnfUWPbZ28QLZGcm8-W6hx-y0r4vx6EXE_I8zZwhLyzbRKDcCMqQIMPUAwS11zjYK-7PFQ3oouO_Z1uV6S8L4Cyrc_XGbGgiLSt1wYp-kMGrGAtPnrWYeq2-EvuR6zZlnaROPL-MUlqCgsZadGanNW_PuqbzjcBr-G33g3WJezGUx1tqsxHun8jBz5DvZgU1_IkfinjRDxPwBE1ME8jLVbdlATlQnUM9IQ4thqVCLczcnu5JjkmuJlVsQAHtrC_p3BaDRVPMrIyigLlRNmSKIuh7Kmr_dBqrYzsVX7MnrSwOoBYyFpfHnXZSoEcRcDREl0BQPuSn7QVMeOZLDpHB7xvuwiL9ohzA3vwop7ymz57F6B_0OxamFUUnYtdJJ9IQio38K6PRHh3ss892wxLbVEMjiR-Dfj3k80XreXlL3n6Fq7FGKfIqr7eJjgp1P63z2r7ZtoTqkYm2pAYtEN5OXxfx0PfvCuagtvrexjQT7DCIMrJfuVV-KzzXXxMNrkrrz1ymaFkzNdGBWmnW7dUIOzgiDhF3aGcj70WRes-pFm45G8yudUy5zkZ-rVFQxo_hxb1lORMCiwHoLeqMNlIg97enjoiofKJ2CvmGcEMz7pwIR-lAvAsaz5E_XACa3VXDpXuINkZcYfoXxOdL-UwH9butJ3nY_4isPrudFrV9V4V6FfV-_c_C6Hh4fyFdCRwmnLNlvH7jEtijTQ6_s2En5vykbWJcwlO1ML48aKCWNu9hxr3-FvYMbAdR78nFN9xrLR8bkSqcaNkh_NPy5LJVuo6cy8LrBmjPBYlaslQL1YcIte7uBQp4xNQEaqONL0XrqJQKpEefrAhD_w8clvDA3Tge-eT1IXhIwAn_EKTzW9IQdanMl2tSKoFYwPZpCCZl4DnBq2gPByN--FJsl3oFqeQUTkmb1hmHZU9GDx6PkMovtu7mCDuEmVQ4oJW6KVL5R5gV489NZ2lTsiVIwwHMJym4swr0n8RsfOj0YMWUWZUVVSCBZjg4VUKWLjn54vyyTxuKW38FivUhVHvjS2cP6TN5JFH9M6SyY1o8YxM294u9y5CoRIr5fEFoGmE6XgXMuLMxOs5Ai2ZoD1lN-6lBEufZihP_Y1zu3i32rZLqt4HjpLW8CTsMkqQ-NLcAsX4WagluJgWNsJLmpNsnc89U0RWbeZjoQsgmeK3AVWIJ0-Wj-ZHuH4TeS6RnGL2WX08Xnx6KLqArf1wjGqH-0rB1TOvwhSPxmIEgAjr8ID_Bvb_5P8G_L0UlvNKBCPxPVdPAoqYBbDEtmKW02B-GFq8nKMOwkL9UDWbobE25CvuX-HBf1K7X6ybNxNsmJdKW0dOwztcWTydIutn59HxfKDq2SZmiMW5ORF3OgtryjCKbBkRUKdoyay6-qiZkDSMRotIheg0S7QCcu7n6MGu9gJyz6Rciw5NCoRFyQ_kfnqLfiVDqCCy9i1yv7Bft8UZX07WlelxBZYlRhx4Nr3lQfpHiaz4xKQ-_kTGxacCpCCt21ofjMf0m9eNPwDy9wnW08DZCQB8eypsvB6AG0gkI_Z55dMy0VWj33hzEoc5Qyi-3yzbCLGzvM8-LxNuN7L7zYUyWJ8Yi60htFgKTJGqhnWWijZ2TB7hnoE4km9NiJyS6RGfRInhihnsh3K0i9HzrZlLg5cKh2Gqny5mJZMyvx2s6wfPgLeh3m6qtHsp0cFxE9I9Lg_pSN32abBWNxAPYyoh3nSvHfgYxwW4JSjwRFDN7MVRAdzSKvwZDJ_-l6iADxyaRJ6bQKarNjQgrFMLzwldzD9FQjAM5fX4Og-INURl0UuCe6BrDg_mNCJvZkkVIvzambJ3MDqKq_O6JPp6hbK5dgrj3cM9zoTHaMZXF-aVvoP6J1T0EV1XrfB0osrdd6dAeh589VRJS3aj_o_KY99mQ1h11ld5L1PkvYRWL74QMCzNuq9twnXEf2vez64cPu5-jrn2MzrP6FnBA2UNtkSeRHZ-nwwv6dg2-UjrnGki_Q5BFxpJr1PXIM9imrZLtsXGVzAP1qibH5MNhhhvxFPRzLjrNzJR9JJBI-hhx8rMxfR6mS-Jsgy5J9d6ZlhWEzNriu_IPSGYX7Rxy3Zgqs10PLL2RqC6QuBNa4IbQlyJcKJzXdBoLlUW470YTIjKj__6K0AZs15tXvA-QC3fSlGqIY8dkxty3POzmIJ4t_YQgtHvz9EGaLh-hiRq97Xf_6LHxcvhSHCKaPuEmVrDqo5j5Und0cXXFsow9HbQRZt7GnONn90z1Ubh5LkTMvecV5_mt9GZAqYrk0H5n2r3Tn3COh5mIAWJBxLOm2WB-JdPLS3gdmnBBOzyQEzti4qu7aXTZbJhb-4rorHtORE_zEruM1mExCkp6tgNgG8N-Mqn95IpNzYJs4pkS7MnxhcZ3m3RfXw0pQJ78IORoznLN2qabCJ_Xf5hDWU1-5OKR-8aUCVcKIz6MCWEp2IveV52VmvI_g0_3Snjv_D2YO0HuDt0JykiFOTDPMI_pA7cc1RZkMaF76h49WYie9Zern2Mqre9bfXJqgxsFFvJDEbSmm9fHA53MG31jL0wjs9YKLjVpIb3k0OCO1BE84nYVNs3qQdV8-Yue9t9OgCNL0enhNdRoZOIRsAzSfKqmgrEi70xrH8__zpS1ouVdLl2heQl51NPyGiSP7QJg15ajZKoMX3u9hIIum52B2jcfjB6dsXw6CRvljHE7_Vh8qSMS-BfwzoxBYWJTq2V2t9dfnUakJV2id1ouZN6IF-3wGwrp470bRCLskH7pg1wfvg1qkqVDSTuubhTtO0LsDwUpfgMIyKg0PhAGlB1xr6TCYsyhrA1tOqAWFnSoNeTKNjp5XnIjjswjfqzmOCCclRvAZH0D8V84CqzpZX5w3hgQ-Apg-mgvK6Q7qOEBA3OQ4khp75mDhNZe1dlO8uueusCWeDYPpdmAqFo-RwZU4OZSQwBzAnpCiWR_BAtiY7y9TQ-jmJiZmXxsRW0q--Xl0wrukMLej4DINVZ8mU9eU5vZJC8fxktn3Fqy9uXV0CqQrM-MQZXT95BEmWw4Z8ke20DKoKEs47_LzWloFfUG6MJklCRgvEUqjwdVmnSNgHvvThv7Yb5KpqHPK6k0AJBA2ItEQxHQ3ZCoGHOgeiBfcX52x2uMpZDpMZyvZ9dep7-fykbgYXz7-Wrb_WfMaOpg9JSB6-azLQ6zktn1gLclhad0yehI_iLG_YoXtBwJaW5DWMIvh41ZndvLYZQ7X6jbN5VomR3Y0THYA7w2c-nrRZssl4jyZFFjgLqNX126nGvuEETXG9jIY1AKYPEaJHvmR406WNfmju3ESVtMSsG_RkveuhQQxjPYeMahNHO8Q== From 3531aae842c18186d90439358c19ed8ba6bfec9e Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 14:21:24 -0700 Subject: [PATCH 23/30] MNT: remove pyqt-stylesheets submodule for now --- jet_tracking/pyqt-stylesheets | 1 - 1 file changed, 1 deletion(-) delete mode 160000 jet_tracking/pyqt-stylesheets diff --git a/jet_tracking/pyqt-stylesheets b/jet_tracking/pyqt-stylesheets deleted file mode 160000 index 9961bc5..0000000 --- a/jet_tracking/pyqt-stylesheets +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 9961bc5b2024746a0f0b0a6445f13bb99e0ed5c3 From d8248aba5d3c90340cc16776d0ccebfd42da9ec2 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 14:30:10 -0700 Subject: [PATCH 24/30] BLD: specify commit hash for pyqt-stylesheets --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 65083e9..edcb2b5 100644 --- a/requirements.txt +++ b/requirements.txt @@ -11,4 +11,4 @@ matplotlib pyyaml cf-units PyQt5 -git+https://github.com/sommerc/pyqt-stylesheets@master +git+https://github.com/sommerc/pyqt-stylesheets/@9961bc5b2024746a0f0b0a6445f13bb99e0ed5c3 From f89323e7494d1f86c71d55a8cac8ab5a8d52b197 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 15:34:03 -0700 Subject: [PATCH 25/30] BLD: specify pyqtcss --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index edcb2b5..4151e0c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -11,4 +11,4 @@ matplotlib pyyaml cf-units PyQt5 -git+https://github.com/sommerc/pyqt-stylesheets/@9961bc5b2024746a0f0b0a6445f13bb99e0ed5c3 +pyqtcss @ git+https://github.com/sommerc/pyqt-stylesheets/@9961bc5b2024746a0f0b0a6445f13bb99e0ed5c3 From 08763a262f6e293b5dd7e535262d956605888487 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 15:49:50 -0700 Subject: [PATCH 26/30] BLD: revert to using git submodule; add qimage2ndarray --- .gitmodules | 3 +++ conda-recipe/meta.yaml | 7 ++++--- jet_tracking/__main__.py | 3 +++ jet_tracking/gui/windows/mainWindow.py | 13 +++++++------ jet_tracking/main.py | 5 +---- jet_tracking/pyqt_stylesheets | 1 + requirements.txt | 2 +- 7 files changed, 20 insertions(+), 14 deletions(-) create mode 100644 .gitmodules create mode 100644 jet_tracking/__main__.py create mode 160000 jet_tracking/pyqt_stylesheets diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..12b7362 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "jet_tracking/pyqt-stylesheets"] + path = jet_tracking/pyqt_stylesheets + url = https://github.com/sommerc/pyqt-stylesheets/ diff --git a/conda-recipe/meta.yaml b/conda-recipe/meta.yaml index 30abd97..12f5b13 100644 --- a/conda-recipe/meta.yaml +++ b/conda-recipe/meta.yaml @@ -21,13 +21,14 @@ requirements: - pip run: - python {{PY_VER}}*,>=3.9 - - pcdsdevices >=2.6.0 + - bluesky >=1.6.0 - matplotlib - numpy - - ophyd >=1.5.0 - - bluesky >=1.6.0 - opencv + - ophyd >=1.5.0 - pandas + - pcdsdevices >=2.6.0 + - qimage2ndarray - scikit-image - scipy diff --git a/jet_tracking/__main__.py b/jet_tracking/__main__.py new file mode 100644 index 0000000..5d6a810 --- /dev/null +++ b/jet_tracking/__main__.py @@ -0,0 +1,3 @@ +from .main import main + +main() diff --git a/jet_tracking/gui/windows/mainWindow.py b/jet_tracking/gui/windows/mainWindow.py index fc0b1c5..2fd4fc3 100644 --- a/jet_tracking/gui/windows/mainWindow.py +++ b/jet_tracking/gui/windows/mainWindow.py @@ -12,16 +12,17 @@ QTabWidget) from signals import Signals -# TODO: address this more completely -sys.path.append('/cds/group/pcds/epics-dev/ajshack/jet_tracking/jet_tracking/pyqt-stylesheets/') +log = logging.getLogger("jet_tracker") + try: - import pyqtcss # noqa: E402 # isort: skip + from ...pyqt_stylesheets import pyqtcss # noqa: E402 # isort: skip except ImportError: pyqtcss = None - - -log = logging.getLogger("jet_tracker") + log.exception( + "Failed to import pyqt-stylesheets. " + "Did you not clone recursively?" + ) class MainWindow(QMainWindow, Ui_MainWindow): diff --git a/jet_tracking/main.py b/jet_tracking/main.py index 3ad296c..128225d 100644 --- a/jet_tracking/main.py +++ b/jet_tracking/main.py @@ -3,13 +3,10 @@ import os import sys -from gui.windows.mainWindow import MainWindow +from .gui.windows.mainWindow import MainWindow from PyQt5.Qt import Qt from PyQt5.QtWidgets import QApplication -# Append stylesheet path -sys.path.append('/cds/group/pcds/epics-dev/ajshack/jet_tracking/jet_tracking/pyqt-stylesheets/') - # create logger log = logging.getLogger('jet_tracker') log.setLevel(logging.INFO) diff --git a/jet_tracking/pyqt_stylesheets b/jet_tracking/pyqt_stylesheets new file mode 160000 index 0000000..9961bc5 --- /dev/null +++ b/jet_tracking/pyqt_stylesheets @@ -0,0 +1 @@ +Subproject commit 9961bc5b2024746a0f0b0a6445f13bb99e0ed5c3 diff --git a/requirements.txt b/requirements.txt index 4151e0c..1bb887c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -11,4 +11,4 @@ matplotlib pyyaml cf-units PyQt5 -pyqtcss @ git+https://github.com/sommerc/pyqt-stylesheets/@9961bc5b2024746a0f0b0a6445f13bb99e0ed5c3 +qimage2ndarray From e4217548b0d0733e578528972321ec3f9a5ca530 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 15:58:30 -0700 Subject: [PATCH 27/30] ENH: jet-tracking entrypoint --- pyproject.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 86d3da8..52a6564 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,6 +19,9 @@ include_package_data = true [project.license] file = "LICENSE.md" +[project.scripts] +jet-tracking = "jet_tracking.main:main" + [tool.pytest.ini_options] addopts = "--cov=." From 4b86a3d5fa63387f9b836c388d0b46ea21fdbe9f Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 16:00:37 -0700 Subject: [PATCH 28/30] MNT: relative imports --- jet_tracking/datastream.py | 9 +++++---- jet_tracking/gui/views/jetImageView.py | 5 +++-- jet_tracking/gui/views/jetTrackerView.py | 5 +++-- jet_tracking/gui/views/simultationView.py | 3 ++- jet_tracking/gui/widgets/controlWidget.py | 5 +++-- jet_tracking/gui/widgets/controlWidgetUi.py | 3 ++- jet_tracking/gui/widgets/editorWidget.py | 5 +++-- jet_tracking/gui/widgets/editorWidgetUi.py | 3 ++- jet_tracking/gui/widgets/graphWidget.py | 3 ++- jet_tracking/gui/widgets/jetImageWidget.py | 3 ++- jet_tracking/gui/widgets/simControlWidget.py | 3 ++- jet_tracking/gui/widgets/simControlWidgetUi.py | 3 ++- jet_tracking/gui/windows/mainWindow.py | 14 +++++++------- jet_tracking/gui/windows/simulationWindow.py | 5 +++-- jet_tracking/main.py | 3 ++- jet_tracking/motorMoving.py | 4 ++-- jet_tracking/mpi_scripts/mpi_driver.py | 8 +++++--- jet_tracking/sketch/simJetImage.py | 3 ++- 18 files changed, 52 insertions(+), 35 deletions(-) diff --git a/jet_tracking/datastream.py b/jet_tracking/datastream.py index ba979fa..efb2587 100644 --- a/jet_tracking/datastream.py +++ b/jet_tracking/datastream.py @@ -7,16 +7,17 @@ import cv2 import numpy as np from epics import caget -from motorMoving import MotorAction from ophyd import EpicsSignal from PyQt5.QtCore import QCoreApplication, QEventLoop, QObject, QThread from scipy import stats -from sketch.simJetImage import SimulatedImage -from tools.numGen import SimulationGenerator -from tools.simMotorMoving import SimulatedMotor from pcdsdevices.epics_motor import Motor +from .motorMoving import MotorAction +from .sketch.simJetImage import SimulatedImage +from .tools.numGen import SimulationGenerator +from .tools.simMotorMoving import SimulatedMotor + ologging = logging.getLogger('ophyd') ologging.setLevel('DEBUG') diff --git a/jet_tracking/gui/views/jetImageView.py b/jet_tracking/gui/views/jetImageView.py index fa7e98a..19703f0 100644 --- a/jet_tracking/gui/views/jetImageView.py +++ b/jet_tracking/gui/views/jetImageView.py @@ -1,9 +1,10 @@ import logging -from gui.widgets.editorWidget import EditorWidget -from gui.widgets.jetImageWidget import JetImageWidget from PyQt5.QtWidgets import QHBoxLayout, QWidget +from ..widgets.editorWidget import EditorWidget +from ..widgets.jetImageWidget import JetImageWidget + log = logging.getLogger('pydm') log.setLevel('CRITICAL') diff --git a/jet_tracking/gui/views/jetTrackerView.py b/jet_tracking/gui/views/jetTrackerView.py index 0b4744d..c38178a 100644 --- a/jet_tracking/gui/views/jetTrackerView.py +++ b/jet_tracking/gui/views/jetTrackerView.py @@ -1,10 +1,11 @@ import logging -from gui.widgets.controlWidget import ControlsWidget -from gui.widgets.graphWidget import GraphsWidget from PyQt5.Qt import Qt from PyQt5.QtWidgets import QDockWidget, QHBoxLayout, QSizePolicy, QWidget +from ..widgets.controlWidget import ControlsWidget +from ..widgets.graphWidget import GraphsWidget + pydm_log = logging.getLogger('pydm') pydm_log.setLevel('CRITICAL') diff --git a/jet_tracking/gui/views/simultationView.py b/jet_tracking/gui/views/simultationView.py index c4832eb..1d60029 100644 --- a/jet_tracking/gui/views/simultationView.py +++ b/jet_tracking/gui/views/simultationView.py @@ -1,6 +1,7 @@ -from gui.widgets.simControlWidget import SimWidget from PyQt5.QtWidgets import QHBoxLayout, QWidget +from ..widgets.simControlWidget import SimWidget + class SimulationView(QWidget): diff --git a/jet_tracking/gui/widgets/controlWidget.py b/jet_tracking/gui/widgets/controlWidget.py index 6a771ba..0eaa45e 100644 --- a/jet_tracking/gui/widgets/controlWidget.py +++ b/jet_tracking/gui/widgets/controlWidget.py @@ -2,11 +2,12 @@ import matplotlib.pyplot as plt import numpy as np -from datastream import MotorThread, StatusThread -from gui.widgets.controlWidgetUi import Controls_Ui from PyQt5.QtCore import QThread from PyQt5.QtWidgets import QFrame, QMessageBox +from ...datastream import MotorThread, StatusThread +from ..widgets.controlWidgetUi import Controls_Ui + log = logging.getLogger('jet_tracker') diff --git a/jet_tracking/gui/widgets/controlWidgetUi.py b/jet_tracking/gui/widgets/controlWidgetUi.py index 384a8ab..6c777b0 100644 --- a/jet_tracking/gui/widgets/controlWidgetUi.py +++ b/jet_tracking/gui/widgets/controlWidgetUi.py @@ -1,8 +1,9 @@ -from gui.widgets.basicWidgets import CollapsibleBox, Label, LineEdit, QHLine from PyQt5.QtWidgets import (QButtonGroup, QComboBox, QFrame, QGridLayout, QHBoxLayout, QLCDNumber, QPushButton, QRadioButton, QSizePolicy, QTextEdit, QVBoxLayout) +from ..widgets.basicWidgets import CollapsibleBox, Label, LineEdit, QHLine + class Controls_Ui: diff --git a/jet_tracking/gui/widgets/editorWidget.py b/jet_tracking/gui/widgets/editorWidget.py index f16409f..5fbc3eb 100644 --- a/jet_tracking/gui/widgets/editorWidget.py +++ b/jet_tracking/gui/widgets/editorWidget.py @@ -1,11 +1,12 @@ import logging from collections import deque -from datastream import JetImageFeed -from gui.widgets.editorWidgetUi import Editor_Ui from PyQt5.QtCore import QThread from PyQt5.QtWidgets import QFrame +from ...datastream import JetImageFeed +from ..widgets.editorWidgetUi import Editor_Ui + log = logging.getLogger(__name__) diff --git a/jet_tracking/gui/widgets/editorWidgetUi.py b/jet_tracking/gui/widgets/editorWidgetUi.py index db05ec6..056b6db 100644 --- a/jet_tracking/gui/widgets/editorWidgetUi.py +++ b/jet_tracking/gui/widgets/editorWidgetUi.py @@ -1,8 +1,9 @@ -from gui.widgets.basicWidgets import QHLine, QRangeSlider from PyQt5.Qt import Qt from PyQt5.QtWidgets import (QButtonGroup, QHBoxLayout, QLabel, QPushButton, QRadioButton, QSlider, QTextEdit, QVBoxLayout) +from ..widgets.basicWidgets import QHLine, QRangeSlider + class Editor_Ui: diff --git a/jet_tracking/gui/widgets/graphWidget.py b/jet_tracking/gui/widgets/graphWidget.py index c5160c8..28d336b 100644 --- a/jet_tracking/gui/widgets/graphWidget.py +++ b/jet_tracking/gui/widgets/graphWidget.py @@ -4,10 +4,11 @@ import numpy as np import pyqtgraph as pg -from gui.widgets.graphWidgetUi import GraphsUi from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QFrame +from ..widgets.graphWidgetUi import GraphsUi + warnings.filterwarnings('ignore') log = logging.getLogger(__name__) diff --git a/jet_tracking/gui/widgets/jetImageWidget.py b/jet_tracking/gui/widgets/jetImageWidget.py index a7e04d2..d2c1f39 100644 --- a/jet_tracking/gui/widgets/jetImageWidget.py +++ b/jet_tracking/gui/widgets/jetImageWidget.py @@ -6,7 +6,8 @@ from PyQt5.QtGui import QImage, QPixmap from PyQt5.QtWidgets import QGraphicsPixmapItem, QGraphicsView from qimage2ndarray import array2qimage -from tools.ROI import GraphicsRectItem, GraphicsScene, HLineItem, VLineItem + +from ...tools.ROI import GraphicsRectItem, GraphicsScene, HLineItem, VLineItem log = logging.getLogger("jet_tracker") diff --git a/jet_tracking/gui/widgets/simControlWidget.py b/jet_tracking/gui/widgets/simControlWidget.py index cf4278d..7430a94 100644 --- a/jet_tracking/gui/widgets/simControlWidget.py +++ b/jet_tracking/gui/widgets/simControlWidget.py @@ -1,8 +1,9 @@ import logging -from gui.widgets.simControlWidgetUi import SimUi from PyQt5.QtWidgets import QFrame +from ..widgets.simControlWidgetUi import SimUi + log = logging.getLogger(__name__) diff --git a/jet_tracking/gui/widgets/simControlWidgetUi.py b/jet_tracking/gui/widgets/simControlWidgetUi.py index cf35854..6f291c0 100644 --- a/jet_tracking/gui/widgets/simControlWidgetUi.py +++ b/jet_tracking/gui/widgets/simControlWidgetUi.py @@ -1,6 +1,7 @@ -from gui.widgets.basicWidgets import LineEdit from PyQt5.QtWidgets import QHBoxLayout, QLabel, QVBoxLayout +from ..widgets.basicWidgets import LineEdit + class SimUi: diff --git a/jet_tracking/gui/windows/mainWindow.py b/jet_tracking/gui/windows/mainWindow.py index 2fd4fc3..dfb8723 100644 --- a/jet_tracking/gui/windows/mainWindow.py +++ b/jet_tracking/gui/windows/mainWindow.py @@ -1,16 +1,16 @@ import logging -import sys -from context import Context -from gui.views.jetImageView import JetImageView -from gui.views.jetTrackerView import JetTrackerView -from gui.windows.mainWindowUi import Ui_MainWindow -from gui.windows.simulationWindow import SimWindow from PyQt5.Qt import Qt from PyQt5.QtCore import QCoreApplication, QSize from PyQt5.QtWidgets import (QAction, QLabel, QMainWindow, QSizePolicy, QTabWidget) -from signals import Signals + +from ...context import Context +from ...signals import Signals +from ..views.jetImageView import JetImageView +from ..views.jetTrackerView import JetTrackerView +from ..windows.mainWindowUi import Ui_MainWindow +from ..windows.simulationWindow import SimWindow log = logging.getLogger("jet_tracker") diff --git a/jet_tracking/gui/windows/simulationWindow.py b/jet_tracking/gui/windows/simulationWindow.py index 7038c7e..7b0c5f4 100644 --- a/jet_tracking/gui/windows/simulationWindow.py +++ b/jet_tracking/gui/windows/simulationWindow.py @@ -1,7 +1,8 @@ -from gui.views.simultationView import SimulationView -from gui.windows.simWindowUi import SimWindow_Ui from PyQt5.QtWidgets import QMainWindow +from ..views.simultationView import SimulationView +from ..windows.simWindowUi import SimWindow_Ui + class SimWindow(QMainWindow, SimWindow_Ui): """ diff --git a/jet_tracking/main.py b/jet_tracking/main.py index 128225d..ba8dd3a 100644 --- a/jet_tracking/main.py +++ b/jet_tracking/main.py @@ -3,10 +3,11 @@ import os import sys -from .gui.windows.mainWindow import MainWindow from PyQt5.Qt import Qt from PyQt5.QtWidgets import QApplication +from .gui.windows.mainWindow import MainWindow + # create logger log = logging.getLogger('jet_tracker') log.setLevel(logging.INFO) diff --git a/jet_tracking/motorMoving.py b/jet_tracking/motorMoving.py index 1340ee3..3576757 100644 --- a/jet_tracking/motorMoving.py +++ b/jet_tracking/motorMoving.py @@ -17,8 +17,8 @@ import logging -from tools.motorAlgorithm import (BasicScan, DynamicLinear, LinearTernary, - TernarySearch) +from .tools.motorAlgorithm import (BasicScan, DynamicLinear, LinearTernary, + TernarySearch) logger = logging.getLogger(__name__) diff --git a/jet_tracking/mpi_scripts/mpi_driver.py b/jet_tracking/mpi_scripts/mpi_driver.py index df4e7b8..fa6d3a3 100644 --- a/jet_tracking/mpi_scripts/mpi_driver.py +++ b/jet_tracking/mpi_scripts/mpi_driver.py @@ -8,13 +8,15 @@ import psana import yaml from mpi4py import MPI -from mpi_master import MpiMaster -from mpi_worker import MpiWorker + +from .mpi_master import MpiMaster +from .mpi_worker import MpiWorker fpath = os.path.dirname(os.path.abspath(__file__)) fpathup = '/'.join(fpath.split('/')[:-1]) sys.path.append(fpathup) -from utils import get_evr_w_codes, get_r_masks # NOQA + +from utils import get_r_masks # noqa: E402 logger = logging.getLogger(__name__) diff --git a/jet_tracking/sketch/simJetImage.py b/jet_tracking/sketch/simJetImage.py index 226ef6d..53806df 100644 --- a/jet_tracking/sketch/simJetImage.py +++ b/jet_tracking/sketch/simJetImage.py @@ -1,5 +1,6 @@ import numpy as np -from tools.imGen import jet_display + +from ..tools.imGen import jet_display class SimulatedImage: From 3be2ecbe39d0025d92fefb281b0a90cdec87f950 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 16:05:00 -0700 Subject: [PATCH 29/30] DOC: nuke non-existing classes from ancient docs --- docs/source/control.rst | 24 ------------------------ docs/source/devices.rst | 27 --------------------------- 2 files changed, 51 deletions(-) diff --git a/docs/source/control.rst b/docs/source/control.rst index e96e366..5851a78 100644 --- a/docs/source/control.rst +++ b/docs/source/control.rst @@ -3,8 +3,6 @@ Jet Control Overview #################### -.. currentmodule:: jet_tracking.jet_control - To start IPython for CXI hutch-python3: .. code-block:: bash @@ -17,25 +15,3 @@ IPython as follows: .. code-block:: bash cxi3 - - -JetControl -========== -Jet tracking control class. - -.. autosummary:: - :nosignatures: - :toctree: generated - - JetControl - -Attributes ----------- - -.. autosummary:: - :toctree: generated/ - - JetControl.set_beam - JetControl.calibrate - JetControl.jet_calculate - JetControl.jet_move diff --git a/docs/source/devices.rst b/docs/source/devices.rst index d3e8eac..e69de29 100644 --- a/docs/source/devices.rst +++ b/docs/source/devices.rst @@ -1,27 +0,0 @@ -.. _devices: - -.. currentmodule:: jet_tracking.devices - -Jet Tracking Classes -#################### -Classes used in jet tracking and control. - -JetCamera Class ---------------- - -.. autoclass:: JetCamera - -Parameters Classes ------------------- - -.. autoclass:: InlineParams -.. autoclass:: OffaxisParams - -Misc Classes --------------- - -.. autoclass:: Control -.. autoclass:: Diffract -.. autoclass:: JTInput -.. autoclass:: JTOutput -.. autoclass:: JTFake From 00e27a5f8b3c67e39e72bba1c22ecfc6c2eb6599 Mon Sep 17 00:00:00 2001 From: Ken Lauer Date: Fri, 23 Jun 2023 16:09:06 -0700 Subject: [PATCH 30/30] DOC: fix up all warnings --- docs/source/devices.rst | 0 docs/source/index.rst | 6 ------ docs/source/shared_memory.rst | 6 ------ 3 files changed, 12 deletions(-) delete mode 100644 docs/source/devices.rst diff --git a/docs/source/devices.rst b/docs/source/devices.rst deleted file mode 100644 index e69de29..0000000 diff --git a/docs/source/index.rst b/docs/source/index.rst index c0c5aa3..d1a7f25 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -19,12 +19,6 @@ Table of Contents shared_memory.rst pvNotepad.rst -.. toctree:: - :maxdepth: 2 - :caption: Devices - - devices.rst - .. toctree:: :maxdepth: 2 :caption: Presentations and Posters diff --git a/docs/source/shared_memory.rst b/docs/source/shared_memory.rst index 6be60d1..cc6ca0c 100644 --- a/docs/source/shared_memory.rst +++ b/docs/source/shared_memory.rst @@ -58,9 +58,3 @@ run on ``daq-cxi-mon06``. API --- - -.. autosummary:: - :nosignatures: - :toctree: generated/ - - output_cspad_sum