diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 169d720..c65ceb9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,23 +21,29 @@ jobs: ci: runs-on: ubuntu-latest container: openmc/openmc:develop + env: + DISPLAY: ':99.0' steps: - - - name: Apt dependencies + - name: Apt dependencies shell: bash run: | apt update - apt install -y libglu1-mesa - - - uses: actions/checkout@v2 - - - name: Install + apt install -y libglu1-mesa libglib2.0-0 libfontconfig1 libegl-dev libxkbcommon-x11-0 xvfb libdbus-1-3 + /sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :99 -screen 0 1920x1200x24 -ac +extension GLX + + - uses: actions/checkout@v4 + + - name: Configure Git safe directory + shell: bash + run: git config --global --add safe.directory "${GITHUB_WORKSPACE}" + + - name: Install shell: bash run: | cd ${GITHUB_WORKSPACE} pip install .[test] - - - name: Test + + - name: Test shell: bash run: | cd ${GITHUB_WORKSPACE} diff --git a/.github/workflows/python-publish-testpypi.yml b/.github/workflows/python-publish-testpypi.yml deleted file mode 100644 index 9c8fb43..0000000 --- a/.github/workflows/python-publish-testpypi.yml +++ /dev/null @@ -1,34 +0,0 @@ -# This yml file will trigger a Github Actions event that builds and upload the -# Python package to TestPyPI. This makes use of Twine and is triggered when a -# push to the master branch occures. For more information see: -# https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries - -name: Upload Test Python Package - -on: - push: - branches: - - master - -jobs: - deploy: - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v2 - - name: Set up Python - uses: actions/setup-python@v2 - with: - python-version: '3.x' - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install setuptools wheel twine - - name: Build and publish - env: - TWINE_USERNAME: __token__ - TWINE_PASSWORD: ${{ secrets.TEST_PYPI_API_TOKEN }} - run: | - python setup.py sdist bdist_wheel - twine upload --repository testpypi dist/* diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml index ce90768..ba033de 100644 --- a/.github/workflows/python-publish.yml +++ b/.github/workflows/python-publish.yml @@ -1,33 +1,31 @@ -# This yml file will trigger a Github Actions event that builds and upload the -# Python package to PiPy. This makes use of Twine and is triggered when a push -# to the master branch occures. For more information see: -# https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries - name: Upload Python Package on: release: - types: [created] + types: [published] jobs: - deploy: + dist: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: hynek/build-and-inspect-python-package@v2 + + publish: + needs: [dist] + environment: pypi + permissions: + id-token: write runs-on: ubuntu-latest + if: github.event_name == 'release' && github.event.action == 'published' steps: - - uses: actions/checkout@v2 - - name: Set up Python - uses: actions/setup-python@v2 - with: - python-version: '3.x' - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install setuptools wheel twine - - name: Build and publish - env: - TWINE_USERNAME: __token__ - TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }} - run: | - python setup.py sdist bdist_wheel - twine upload dist/* + - uses: actions/download-artifact@v4 + with: + name: Packages + path: dist + + - uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/.gitignore b/.gitignore index 4dc51be..fe98fa8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ *~ __pycache__ plot_settings.pkl +*.egg-info diff --git a/README.md b/README.md index b5fcc65..7601ab1 100644 --- a/README.md +++ b/README.md @@ -4,35 +4,123 @@ ## Description -A graphical interface for visualizing and manipulating OpenMC plot slices. +A graphical interface for visualizing and navigating OpenMC models. Originally created by @landonjmitchell at the University of Chicago ([original repository](https://github.com/landonjmitchell/openmc-plotgui)). +![beavrs](./screenshots/beavrs.png) + +![beavrs_zoom](./screenshots/beavrs_zoomed.png) + ## Dependencies -OpenMC, Matplotlib, NumPy, PySide2 +OpenMC, Matplotlib, NumPy, PySide6 ## Installation -This package is most easily installed by running - +This package is available from PyPI and conda-forge. To install from PyPI run +the following command from the terminal: ```console -pip install openmc-plotter +python -m pip install openmc-plotter ``` +Alternatively, conda can be used to install the plotter (recommended option for +conda enviroments): +```console +conda install -c conda-forge openmc-plotter +``` ## Usage -From a directory containing a working OpenMC model run: +From a directory containing an OpenMC model run: ```console -openmc-plotter +$ openmc-plotter ``` +or simply run + +```console +$ openmc-plotter +``` + +from the directory containing the model. + Once the viewer has opened, press `?` to view a variety of keyboard shortcuts. -# Controls/Functionality +![shortcuts](./screenshots/shortcuts.png) + +## Batch Mode + +Plot view (`.pltvw`) files generated in interactive sessions (see [Saving and Exporting](#saving-and-exporting)) +can be used to generate images from the command line without opening the plotter GUI. + +```console +$ openmc-plotter -b view1.pltvw view1.pltvw view1.pltvw +``` +## Troubleshooting + +Updates to the plotter can result in stale references to deprecated features. For example, it's possible that something like the following may appear after an update: + +``` +AttributeError: 'MainWindow' object has no attribute 'shortcutOverlay' +``` + +To address this, the application settings can be cleared, the plotter can be started with the `--clear-config` (or `-c`) to reset the application's settings cache on startup. + +```bash +$ openmc-plotter --clear-cache +``` + +## Features + +### Tally Visualization + +The plotter also provides the ability to view tallies with spatial filters (mesh +filter, cell filter, etc.). After loading a statepoint file from the "Edit" +menu, tallies can be displayed on top of the geometry. + +![tally](./screenshots/pincell_tally.png) + +Filters, scores, and nuclides on the tally can be enabled/disabled to isolate data. + +### Color Manipulation + +Cell and material colors can be customized in the color dialog menu. Overlap +coloring can be enabled as well to debug problems in the geometry definition. + +![colors](./screenshots/color_dialog.png) + +### DAGMC Geometry Visualization + +The plotter can also present the CAD-based tesellation geometry enabled by the +[Direct Accelerated Geometry Monte Carlo](https://svalinn.github.io/DAGMC/) +(DAGMC) toolkit. Below is the cross section of a tokamake model generated using [paramak](https://paramak.readthedocs.io/en/main/): + +![dagmc](./screenshots/dagmc.png) + +As well as a DAGMC model of the Advanced Test Reactor (ATR): + +![atr](./screenshots/atr.png) + +### Saving and Exporting + + - Any image displayed in the plotter can be saved in any format supported by the +user's Matplotlib installation. + + - Tally and geometry data (material/cell IDs) can be exported to a VTK file under "File->Export" + +### Source Site Plotting + +Source locations from an externally defined source can be visualized in the plotter to verify +source definitions. These source sites are gathered as generated by the transport model. A tolerance +can be provided to filter out source sites that are too far from the slice plane, otherwise source +locations are projected onto the slice plane. + +![Source plotting](./screenshots/source-sites.png) + +# Options/Functionality ## Menu Bar: diff --git a/openmc_plotter/__init__.py b/openmc_plotter/__init__.py index e69de29..bb88f5b 100644 --- a/openmc_plotter/__init__.py +++ b/openmc_plotter/__init__.py @@ -0,0 +1,3 @@ +from importlib.metadata import version + +__version__ = version("openmc-plotter") diff --git a/openmc_plotter/__main__.py b/openmc_plotter/__main__.py index 8f0fc4a..c5facb4 100644 --- a/openmc_plotter/__main__.py +++ b/openmc_plotter/__main__.py @@ -1,18 +1,44 @@ -#!/usr/bin/env python3 - +from argparse import ArgumentParser from pathlib import Path from threading import Thread +import os import signal import sys -from PySide2 import QtCore, QtGui -from PySide2.QtWidgets import QApplication, QSplashScreen +from PySide6 import QtCore, QtGui +from PySide6.QtWidgets import QApplication, QSplashScreen +from . import __version__ from .main_window import MainWindow, _openmcReload + def main(): - path_icon = str(Path(__file__).parent / 'assets/openmc_logo.png') - path_splash = str(Path(__file__).parent / 'assets/splash.png') + ap = ArgumentParser(description='OpenMC Plotter GUI') + version_str = f'OpenMC Plotter Version: {__version__}' + ap.add_argument('-v', '--version', action='version', version=version_str, + help='Display version info.') + ap.add_argument('-e','--ignore-settings', action='store_false', + help='Ignore plot_settings.pkl file if present.') + ap.add_argument('-s', '--threads', type=int, default=None, + help='If present, number of threads used to generate plots.') + ap.add_argument('-r', '--resolution', type=int, default=None, + help='Default number of pixels in each direction') + ap.add_argument('model_path', nargs='?', default=os.curdir, + help='Location of model XML file or a directory containing ' + 'XML files (default is current dir)') + ap.add_argument('-b', '--batch-mode', nargs='+', default=False, + help='View files used to generate plots in batch mode') + ap.add_argument('-c', '--clear-config', action='store_true', default=False, + help='Clear the Qt application configuration settings') + + args = ap.parse_args() + + run_app(args) + + +def run_app(user_args): + path_icon = str(Path(__file__).parent / 'assets' / 'openmc_logo.png') + path_splash = str(Path(__file__).parent / 'assets' / 'splash.png') app = QApplication(sys.argv) app.setOrganizationName("OpenMC") @@ -21,17 +47,23 @@ def main(): app.setWindowIcon(QtGui.QIcon(path_icon)) app.setAttribute(QtCore.Qt.AA_DontShowIconsInMenus, True) + if user_args.clear_config: + settings = QtCore.QSettings() + settings.clear() + splash_pix = QtGui.QPixmap(path_splash) splash = QSplashScreen(splash_pix, QtCore.Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) - splash.show() + if not user_args.batch_mode: + splash.show() app.processEvents() splash.setMask(splash_pix.mask()) splash.showMessage("Loading Model...", QtCore.Qt.AlignHCenter | QtCore.Qt.AlignBottom) app.processEvents() # load OpenMC model on another thread - loader_thread = Thread(target=_openmcReload) + openmc_args = {'threads': user_args.threads, 'model_path': user_args.model_path} + loader_thread = Thread(target=_openmcReload, kwargs=openmc_args) loader_thread.start() # while thread is working, process app events while loader_thread.is_alive(): @@ -44,12 +76,21 @@ def main(): font_metric = QtGui.QFontMetrics(app.font()) screen_size = app.primaryScreen().size() - mainWindow = MainWindow(font_metric, screen_size) + mainWindow = MainWindow(font_metric, screen_size, user_args.model_path, + user_args.threads, user_args.resolution) # connect splashscreen to main window, close when main window opens - mainWindow.loadGui() - mainWindow.show() + mainWindow.loadGui(use_settings_pkl=user_args.ignore_settings) + splash.close() + if user_args.batch_mode: + for view_file in user_args.batch_mode: + mainWindow.saveBatchImage(view_file) + mainWindow.close() + sys.exit() + else: + mainWindow.show() + # connect interrupt signal to close call signal.signal(signal.SIGINT, lambda *args: mainWindow.close()) # create timer that interrupts the Qt event loop @@ -58,7 +99,7 @@ def main(): timer.start(500) timer.timeout.connect(lambda: None) - sys.exit(app.exec_()) + sys.exit(app.exec()) if __name__ == '__main__': main() diff --git a/openmc_plotter/custom_widgets.py b/openmc_plotter/custom_widgets.py index 2a20074..e03e056 100644 --- a/openmc_plotter/custom_widgets.py +++ b/openmc_plotter/custom_widgets.py @@ -1,8 +1,8 @@ from functools import partial import warnings -from PySide2 import QtWidgets, QtCore -from PySide2.QtWidgets import QFrame +from PySide6 import QtWidgets, QtCore +from PySide6.QtWidgets import QFrame class HorizontalLine(QFrame): diff --git a/openmc_plotter/docks.py b/openmc_plotter/docks.py index 1a4a11c..36b7ba2 100644 --- a/openmc_plotter/docks.py +++ b/openmc_plotter/docks.py @@ -2,13 +2,14 @@ from collections.abc import Iterable from collections import defaultdict -from PySide2 import QtCore -from PySide2.QtWidgets import (QWidget, QPushButton, QHBoxLayout, QVBoxLayout, +from PySide6 import QtCore +from PySide6.QtWidgets import (QWidget, QPushButton, QHBoxLayout, QVBoxLayout, QGroupBox, QFormLayout, QLabel, QLineEdit, QComboBox, QSpinBox, QDoubleSpinBox, QSizePolicy, QCheckBox, QDockWidget, QScrollArea, QListWidget, - QListWidgetItem, QTreeWidget, QTreeWidgetItem) -from matplotlib import cm as mcolormaps + QListWidgetItem, QTreeWidget, QTreeWidgetItem, + QTabWidget, QSplitter) +import matplotlib.pyplot as plt import numpy as np import openmc @@ -18,40 +19,145 @@ _REACTION_UNITS, _SPATIAL_FILTERS) -class PlotterDock(QDockWidget): +class PlotterPanel(QWidget): """ - Dock widget with common settings for the plotting application + Base panel widget with common settings for the plotting application """ - def __init__(self, model, font_metric, parent=None): + + def __init__(self, model, font_metric, main_window, parent=None): super().__init__(parent) self.model = model self.font_metric = font_metric - self.main_window = parent + self.main_window = main_window self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) -class DomainDock(PlotterDock): +class MeshPanel(PlotterPanel): + """Panel for mesh options""" + + def __init__(self, model, font_metric, main_window, parent=None): + super().__init__(model, font_metric, main_window, parent) + + self.treeLayout = QVBoxLayout() + self.meshTree = QTreeWidget() + self.meshTree.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) + self.meshTree.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) + self.treeExpander = Expander("Meshes:", layout=self.treeLayout) + self.treeExpander.expand() # start with meshes expanded + self.headerLabel = QLabel("Mesh Annotations") + + self.meshTree.setColumnCount(1) + + self.mesh_items = [] + for mesh_id in self.model.cpp_mesh_ids(): + mesh_item = QTreeWidgetItem(self.meshTree, (f'Mesh {mesh_id}',)) + mesh_item.setFlags(mesh_item.flags() | QtCore.Qt.ItemIsUserCheckable) + mesh_item.setCheckState(0, QtCore.Qt.Unchecked) + self.mesh_items.append((mesh_id, mesh_item)) + self.meshTree.addTopLevelItem(mesh_item) + + self.meshTree.setHeaderHidden(True) + + self.treeLayout.addWidget(self.meshTree) + + self.panelLayout = QVBoxLayout() + self.panelLayout.addWidget(self.headerLabel) + + self.treeSplitter = QSplitter(QtCore.Qt.Vertical) + self.treeSplitter.setChildrenCollapsible(False) + self.treeSplitter.addWidget(self.meshTree) + self.treeSplitter.addWidget(QWidget()) + self.treeSplitter.setStretchFactor(0, 1) + self.treeSplitter.setStretchFactor(1, 2) + self.panelLayout.addWidget(self.treeSplitter) + self.setLayout(self.panelLayout) + + def get_checked_meshes(self): + return [id for id, item in self.mesh_items if item.checkState(0) == QtCore.Qt.Checked] + + def update(self): + pass + + +class TabbedDock(QDockWidget): """ - Domain options dock + Dock widget containing tabbed panels for Geometry, Tallies, and Meshes """ + def __init__(self, model, font_metric, parent=None): - super().__init__(model, font_metric, parent) + super().__init__(parent) + + self.model = model + self.font_metric = font_metric + self.main_window = parent + self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) self.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea) - # Create Controls - self._createOriginBox() - self._createOptionsBox() - self._createResolutionBox() + # Create the tab widget + self.tabWidget = QTabWidget() + + # Create the three panels + self.geometryPanel = GeometryPanel(model, font_metric, parent, self) + self.tallyPanel = TallyPanel(model, font_metric, parent, self) + self.meshAnnotationPanel = MeshPanel(model, font_metric, parent, self) + + # Wrap panels in scroll areas + geometryScroll = QScrollArea() + geometryScroll.setWidget(self.geometryPanel) + geometryScroll.setWidgetResizable(True) + + tallyScroll = QScrollArea() + tallyScroll.setWidget(self.tallyPanel) + tallyScroll.setWidgetResizable(True) - # Create submit button + meshScroll = QScrollArea() + meshScroll.setWidget(self.meshAnnotationPanel) + meshScroll.setWidgetResizable(True) + + # Add panels as tabs + self.tabWidget.addTab(geometryScroll, "Geometry") + self.tabWidget.addTab(tallyScroll, "Tallies") + self.tabWidget.addTab(meshScroll, "Meshes") + + # Create Apply Changes button self.applyButton = QPushButton("Apply Changes") - # Mac bug fix self.applyButton.setMinimumHeight(self.font_metric.height() * 1.6) + self.applyButton.setStyleSheet("QPushButton { background-color: #4CAF50; color: white; }") self.applyButton.clicked.connect(self.main_window.applyChanges) + # Main layout with tabs and apply button + self.mainLayout = QVBoxLayout() + self.mainLayout.addWidget(self.tabWidget) + self.mainLayout.addWidget(HorizontalLine()) + self.mainLayout.addWidget(self.applyButton) + + # Create container widget + self.containerWidget = QWidget() + self.containerWidget.setLayout(self.mainLayout) + self.setWidget(self.containerWidget) + + def resizeEvent(self, event): + self.main_window.resizeEvent(event) + + hideEvent = showEvent = moveEvent = resizeEvent + + +class GeometryPanel(PlotterPanel): + """ + Geometry options panel + """ + + def __init__(self, model, font_metric, main_window, parent=None): + super().__init__(model, font_metric, main_window, parent) + + # Create Controls + self._createOriginBox() + self._createOptionsBox() + self._createResolutionBox() + # Create Zoom box self.zoomBox = QSpinBox() self.zoomBox.setSuffix(' %') @@ -67,22 +173,15 @@ def __init__(self, model, font_metric, parent=None): self.zoomWidget.setLayout(self.zoomLayout) # Create Layout - self.dockLayout = QVBoxLayout() - self.dockLayout.addWidget(QLabel("Geometry/Properties")) - self.dockLayout.addWidget(HorizontalLine()) - self.dockLayout.addWidget(self.originGroupBox) - self.dockLayout.addWidget(self.optionsGroupBox) - self.dockLayout.addWidget(self.resGroupBox) - self.dockLayout.addWidget(HorizontalLine()) - self.dockLayout.addWidget(self.zoomWidget) - self.dockLayout.addWidget(HorizontalLine()) - self.dockLayout.addStretch() - self.dockLayout.addWidget(self.applyButton) - self.dockLayout.addWidget(HorizontalLine()) - - self.optionsWidget = QWidget() - self.optionsWidget.setLayout(self.dockLayout) - self.setWidget(self.optionsWidget) + self.panelLayout = QVBoxLayout() + self.panelLayout.addWidget(self.originGroupBox) + self.panelLayout.addWidget(self.optionsGroupBox) + self.panelLayout.addWidget(self.resGroupBox) + self.panelLayout.addWidget(HorizontalLine()) + self.panelLayout.addWidget(self.zoomWidget) + self.panelLayout.addStretch() + + self.setLayout(self.panelLayout) def _createOriginBox(self): @@ -159,7 +258,8 @@ def _createOptionsBox(self): self.domainAlphaBox.setSingleStep(0.05) self.domainAlphaBox.setDecimals(2) self.domainAlphaBox.setRange(0.0, 1.0) - self.domainAlphaBox.valueChanged.connect(self.main_window.editPlotAlpha) + self.domainAlphaBox.valueChanged.connect( + self.main_window.editPlotAlpha) # Visibility self.visibilityBox = QCheckBox(self) @@ -167,8 +267,10 @@ def _createOptionsBox(self): self.main_window.editPlotVisibility) # Outlines - self.outlinesBox = QCheckBox(self) - self.outlinesBox.stateChanged.connect(self.main_window.toggleOutlines) + self.outlinesCellBox = QCheckBox(self) + self.outlinesCellBox.stateChanged.connect(self.main_window.toggleOutlinesCell) + self.outlinesMatBox = QCheckBox(self) + self.outlinesMatBox.stateChanged.connect(self.main_window.toggleOutlinesMat) # Basis self.basisBox = QComboBox(self) @@ -179,8 +281,10 @@ def _createOptionsBox(self): # Advanced Color Options self.colorOptionsButton = QPushButton('Color Options...') - self.colorOptionsButton.setMinimumHeight(self.font_metric.height() * 1.6) - self.colorOptionsButton.clicked.connect(self.main_window.showColorDialog) + self.colorOptionsButton.setMinimumHeight( + self.font_metric.height() * 1.6) + self.colorOptionsButton.clicked.connect( + self.main_window.showColorDialog) # Options Form Layout self.opLayout = QFormLayout() @@ -191,7 +295,8 @@ def _createOptionsBox(self): self.opLayout.addRow('Universe Level:', self.universeLevelBox) self.opLayout.addRow('Plot alpha:', self.domainAlphaBox) self.opLayout.addRow('Visible:', self.visibilityBox) - self.opLayout.addRow('Outlines:', self.outlinesBox) + self.opLayout.addRow('Cell Outlines:', self.outlinesCellBox) + self.opLayout.addRow('Material Outlines:', self.outlinesMatBox) self.opLayout.addRow(self.colorOptionsButton) self.opLayout.setLabelAlignment(QtCore.Qt.AlignLeft) self.opLayout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow) @@ -233,7 +338,7 @@ def _createResolutionBox(self): self.resGroupBox = QGroupBox("Resolution") self.resGroupBox.setLayout(self.resLayout) - def updateDock(self): + def update(self): self.updateOrigin() self.updateWidth() self.updateHeight() @@ -275,7 +380,8 @@ def updatePlotVisibility(self): self.visibilityBox.setChecked(self.model.activeView.domainVisible) def updateOutlines(self): - self.outlinesBox.setChecked(self.model.activeView.outlines) + self.outlinesCellBox.setChecked(self.model.activeView.outlinesCell) + self.outlinesMatBox.setChecked(self.model.activeView.outlinesMat) def updateBasis(self): self.basisBox.setCurrentText(self.model.activeView.basis) @@ -302,20 +408,12 @@ def revertToCurrent(self): self.widthBox.setValue(cv.width) self.heightBox.setValue(cv.height) - def resizeEvent(self, event): - self.main_window.resizeEvent(event) +class TallyPanel(PlotterPanel): - hideEvent = showEvent = moveEvent = resizeEvent + def __init__(self, model, font_metric, main_window, parent=None): + super().__init__(model, font_metric, main_window, parent) - -class TallyDock(PlotterDock): - - def __init__(self, model, font_metric, parent=None): - super().__init__(model, font_metric, parent) - - self.setAllowedAreas(QtCore.Qt.RightDockWidgetArea) - - # Dock maps for tally information + # Panel maps for tally information self.tally_map = {} self.filter_map = {} self.score_map = {} @@ -335,35 +433,21 @@ def __init__(self, model, font_metric, parent=None): self.tallyGroupBox = QGroupBox('Selected Tally') self.tallyGroupBox.setLayout(self.tallySelectorLayout) - # Create submit button - self.applyButton = QPushButton("Apply Changes") - self.applyButton.setMinimumHeight(self.font_metric.height() * 1.6) - self.applyButton.clicked.connect(self.main_window.applyChanges) - # Color options section self.tallyColorForm = ColorForm(self.model, self.main_window, 'tally') self.scoresGroupBox = Expander(title="Scores:") self.scoresListWidget = QListWidget() + self.scoresListWidget.itemChanged.connect(self.updateScores) self.nuclidesListWidget = QListWidget() # Main layout - self.dockLayout = QVBoxLayout() - self.dockLayout.addWidget(QLabel("Tallies")) - self.dockLayout.addWidget(HorizontalLine()) - self.dockLayout.addWidget(self.tallyGroupBox) - self.dockLayout.addStretch() - self.dockLayout.addWidget(HorizontalLine()) - self.dockLayout.addWidget(self.tallyColorForm) - self.dockLayout.addWidget(HorizontalLine()) - self.dockLayout.addWidget(self.applyButton) - - # Create widget for dock and apply main layout - self.scroll = QScrollArea() - self.scroll.setWidgetResizable(True) - self.widget = QWidget() - self.widget.setLayout(self.dockLayout) - self.scroll.setWidget(self.widget) - self.setWidget(self.scroll) + self.panelLayout = QVBoxLayout() + self.panelLayout.addWidget(self.tallyGroupBox) + self.panelLayout.addStretch() + self.panelLayout.addWidget(HorizontalLine()) + self.panelLayout.addWidget(self.tallyColorForm) + + self.setLayout(self.panelLayout) def _createFilterTree(self, spatial_filters): av = self.model.activeView @@ -379,9 +463,9 @@ def _createFilterTree(self, spatial_filters): header = QTreeWidgetItem(["Filters"]) self.filterTree.setHeaderItem(header) - self.filterTree.setItemHidden(header, True) + header.setHidden(True) + #self.filterTree.setItemHidden(header, True) self.filterTree.setColumnCount(1) - self.filterTree.itemChanged.connect(self.updateFilters) self.filter_map = {} self.bin_map = {} @@ -394,29 +478,42 @@ def _createFilterTree(self, spatial_filters): # make checkable if not spatial_filters: filter_item.setFlags(QtCore.Qt.ItemIsUserCheckable) - filter_item.setToolTip(0, "Only tallies with spatial filters are viewable.") + filter_item.setToolTip( + 0, "Only tallies with spatial filters are viewable.") else: - filter_item.setFlags(filter_item.flags() | QtCore.Qt.ItemIsTristate | QtCore.Qt.ItemIsUserCheckable) + filter_item.setFlags( + filter_item.flags() | QtCore.Qt.ItemIsUserCheckable | + QtCore.Qt.ItemIsAutoTristate) filter_item.setCheckState(0, QtCore.Qt.Unchecked) # all mesh bins are selected by default and not shown in the dock if isinstance(tally_filter, openmc.MeshFilter): filter_item.setCheckState(0, QtCore.Qt.Checked) filter_item.setFlags(QtCore.Qt.ItemIsUserCheckable) - filter_item.setToolTip(0, "All Mesh bins are selected automatically") + filter_item.setToolTip( + 0, "All Mesh bins are selected automatically") continue def _bin_sort_val(bin): - if isinstance(bin, Iterable) and all([isinstance(val, float) for val in bin]): - return np.sum(bin) + if isinstance(bin, Iterable): + if all([isinstance(val, float) for val in bin]): + return np.sum(bin) + else: + return tuple(bin) else: return bin - for bin in sorted(tally_filter.bins, key=_bin_sort_val): + if isinstance(tally_filter, openmc.EnergyFunctionFilter): + bins = [0] + else: + bins = tally_filter.bins + + for bin in sorted(bins, key=_bin_sort_val): item = QTreeWidgetItem(filter_item, [str(bin),]) if not spatial_filters: item.setFlags(QtCore.Qt.ItemIsUserCheckable) - item.setToolTip(0, "Only tallies with spatial filters are viewable.") + item.setToolTip( + 0, "Only tallies with spatial filters are viewable.") else: item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable) item.setCheckState(0, QtCore.Qt.Unchecked) @@ -480,24 +577,16 @@ def selectTally(self, tally_label=None): if not spatial_filters: self.valueBox.setEnabled(False) - self.valueBox.setToolTip("Only tallies with spatial filters are viewable.") + self.valueBox.setToolTip( + "Only tallies with spatial filters are viewable.") # scores self.score_map = {} - self.scoresListWidget.itemClicked.connect( - self.main_window.updateScores) - self.score_map.clear() self.scoresListWidget.clear() - sorted_scores = sorted(tally.scores) - # always put total first if present - if 'total' in sorted_scores: - idx = sorted_scores.index('total') - sorted_scores.insert(0, sorted_scores.pop(idx)) - - for score in sorted_scores: + for score in tally.scores: ql = QListWidgetItem() - ql.setText(score.capitalize()) + ql.setText(score) ql.setCheckState(QtCore.Qt.Unchecked) if not spatial_filters: ql.setFlags(QtCore.Qt.ItemIsUserCheckable) @@ -515,12 +604,12 @@ def selectTally(self, tally_label=None): self.scoresGroupBoxLayout = QVBoxLayout() self.scoresGroupBoxLayout.addWidget(self.scoresListWidget) - self.scoresGroupBox = Expander("Scores:", layout=self.scoresGroupBoxLayout) + self.scoresGroupBox = Expander( + "Scores:", layout=self.scoresGroupBoxLayout) self.tallySelectorLayout.addRow(self.scoresGroupBox) # nuclides self.nuclide_map = {} - self.nuclidesListWidget.itemClicked.connect(self.main_window.updateNuclides) self.nuclide_map.clear() self.nuclidesListWidget.clear() @@ -550,7 +639,8 @@ def selectTally(self, tally_label=None): self.nuclidesGroupBoxLayout = QVBoxLayout() self.nuclidesGroupBoxLayout.addWidget(self.nuclidesListWidget) - self.nuclidesGroupBox = Expander("Nuclides:", layout=self.nuclidesGroupBoxLayout) + self.nuclidesGroupBox = Expander( + "Nuclides:", layout=self.nuclidesGroupBoxLayout) self.tallySelectorLayout.addRow(self.nuclidesGroupBox) def updateMinMax(self): @@ -569,22 +659,40 @@ def updateSelectedTally(self): self.tallySelector.setCurrentIndex(idx) def updateFilters(self): + # if the filters header is checked, uncheck all bins and return applied_filters = defaultdict(tuple) for f, f_item in self.filter_map.items(): if type(f) == openmc.MeshFilter: continue filter_checked = f_item.checkState(0) - if filter_checked != QtCore.Qt.Unchecked: + if filter_checked == QtCore.Qt.Unchecked: + for i in range(f_item.childCount()): + bin_item = f_item.child(i) + bin_item.setCheckState(0, QtCore.Qt.Unchecked) + applied_filters[f] = tuple() + elif filter_checked == QtCore.Qt.Checked: + if isinstance(f, openmc.EnergyFunctionFilter): + applied_filters[f] = (0,) + else: + for i in range(f_item.childCount()): + bin_item = f_item.child(i) + bin_item.setCheckState(0, QtCore.Qt.Checked) + applied_filters[f] = tuple(range(f_item.childCount())) + elif filter_checked == QtCore.Qt.PartiallyChecked: selected_bins = [] - for idx, b in enumerate(f.bins): + if isinstance(f, openmc.EnergyFunctionFilter): + bins = [0] + else: + bins = f.bins + for idx, b in enumerate(bins): b = b if not isinstance(b, Iterable) else tuple(b) bin_checked = self.bin_map[(f, b)].checkState(0) if bin_checked == QtCore.Qt.Checked: selected_bins.append(idx) applied_filters[f] = tuple(selected_bins) - self.model.appliedFilters = applied_filters + self.model.appliedFilters = applied_filters def updateScores(self): applied_scores = [] @@ -593,32 +701,29 @@ def updateScores(self): applied_scores.append(score) self.model.appliedScores = tuple(applied_scores) - if not applied_scores: - # if no scores are selected, enable all scores again - for score, score_box in self.score_map.items(): - sunits = _SCORE_UNITS.get(score, _REACTION_UNITS) - empty_item = QListWidgetItem() - score_box.setFlags(empty_item.flags() | QtCore.Qt.ItemIsUserCheckable) - score_box.setFlags(empty_item.flags() & ~QtCore.Qt.ItemIsSelectable) - elif 'total' in applied_scores: - self.model.appliedScores = ('total',) - # if total is selected, disable all other scores - for score, score_box in self.score_map.items(): - if score != 'total': - score_box.setFlags(QtCore.Qt.ItemIsUserCheckable) - score_box.setToolTip("De-select 'total' to enable other scores") - else: - # get units of applied scores - selected_units = _SCORE_UNITS.get(applied_scores[0], _REACTION_UNITS) - # disable scores with incompatible units - for score, score_box in self.score_map.items(): - sunits = _SCORE_UNITS.get(score, _REACTION_UNITS) - if sunits != selected_units: - score_box.setFlags(QtCore.Qt.ItemIsUserCheckable) - score_box.setToolTip("Score is incompatible with currently selected scores") - else: - score_box.setFlags(score_box.flags() | QtCore.Qt.ItemIsUserCheckable) - score_box.setFlags(score_box.flags() & ~QtCore.Qt.ItemIsSelectable) + with QtCore.QSignalBlocker(self.scoresListWidget): + if not applied_scores: + # if no scores are selected, enable all scores again + for score, score_box in self.score_map.items(): + score_box.setFlags(QtCore.Qt.ItemIsUserCheckable | + QtCore.Qt.ItemIsEnabled | + QtCore.Qt.ItemIsSelectable) + else: + # get units of applied scores + selected_units = _SCORE_UNITS.get( + applied_scores[0], _REACTION_UNITS) + # disable scores with incompatible units + for score, score_box in self.score_map.items(): + sunits = _SCORE_UNITS.get(score, _REACTION_UNITS) + if sunits != selected_units: + score_box.setFlags(QtCore.Qt.ItemIsUserCheckable) + score_box.setToolTip( + "Score is incompatible with currently selected scores") + else: + score_box.setFlags(score_box.flags() | + QtCore.Qt.ItemIsUserCheckable) + score_box.setFlags(score_box.flags() & + ~QtCore.Qt.ItemIsSelectable) def updateNuclides(self): applied_nuclides = [] @@ -628,17 +733,25 @@ def updateNuclides(self): self.model.appliedNuclides = tuple(applied_nuclides) if 'total' in applied_nuclides: - self.model.appliedNuclides = ['total',] + self.model.appliedNuclides = ('total',) for nuclide, nuclide_box in self.nuclide_map.items(): if nuclide != 'total': nuclide_box.setFlags(QtCore.Qt.ItemIsUserCheckable) - nuclide_box.setToolTip("De-select 'total' to enable other nuclides") + nuclide_box.setToolTip( + "De-select 'total' to enable other nuclides") elif not applied_nuclides: # if no nuclides are selected, enable all nuclides again for nuclide, nuclide_box in self.nuclide_map.items(): empty_item = QListWidgetItem() - nuclide_box.setFlags(empty_item.flags() | QtCore.Qt.ItemIsUserCheckable) - nuclide_box.setFlags(empty_item.flags() & ~QtCore.Qt.ItemIsSelectable) + nuclide_box.setFlags(empty_item.flags() | + QtCore.Qt.ItemIsUserCheckable) + nuclide_box.setFlags(empty_item.flags() & + ~QtCore.Qt.ItemIsSelectable) + + def updateModel(self): + self.updateFilters() + self.updateScores() + self.updateNuclides() def update(self): @@ -651,9 +764,11 @@ def update(self): self.tallySelector.addItem("None") for idx, tally in enumerate(self.model.statepoint.tallies.values()): if tally.name == "": - self.tallySelector.addItem('Tally {}'.format(tally.id), userData=tally.id) + self.tallySelector.addItem( + f'Tally {tally.id}', userData=tally.id) else: - self.tallySelector.addItem('Tally {} "{}"'.format(tally.id, tally.name), userData=tally.id) + self.tallySelector.addItem( + f'Tally {tally.id} "{tally.name}"', userData=tally.id) self.tally_map[idx] = tally self.updateSelectedTally() self.updateMinMax() @@ -681,17 +796,12 @@ class ColorForm(QWidget): Selector for colormap dataIndicatorCheckBox : QCheckBox Inidcates whether or not the data indicator will appear on the colorbar - userMinMaxBox : QCheckBox - Indicates whether or not the user defined values in the min and max - will be used to set the bounds of the colorbar. + minMaxTypeBox : QComboBox + Dropdown to select min/max type: "Full data", "Visible data", or "Custom" maxBox : ScientificDoubleSpinBox - Max value of the colorbar. If the userMinMaxBox is checked, this will be - the user's input. If the userMinMaxBox is not checked, this box will - hold the max value of the visible data. + Max value of the colorbar. Only visible when minMaxTypeBox is set to "Custom". minBox : ScientificDoubleSpinBox - Min value of the colorbar. If the userMinMaxBox is checked, this will be - the user's input. If the userMinMaxBox is not checked, this box will - hold the max value of the visible data. + Min value of the colorbar. Only visible when minMaxTypeBox is set to "Custom". scaleBox : QCheckBox Indicates whether or not the data is displayed on a log or linear scale @@ -707,6 +817,7 @@ class ColorForm(QWidget): comma-separated set of values is entered, those values will be used as levels in the contour plot. """ + def __init__(self, model, main_window, field, colormaps=None): super().__init__() @@ -732,21 +843,32 @@ def __init__(self, model, main_window, field, colormaps=None): # Color map selector self.colormapBox = QComboBox() if colormaps is None: - colormaps = sorted(m for m in mcolormaps.datad if not m.endswith("_r")) + colormaps = sorted( + m for m in plt.colormaps() if not m.endswith("_r")) for colormap in colormaps: self.colormapBox.addItem(colormap) cmap_connector = partial(main_window.editTallyDataColormap) self.colormapBox.currentTextChanged[str].connect(cmap_connector) + # Color map reverse + self.reverseCmapBox = QCheckBox() + reverse_connector = partial(main_window.toggleReverseCmap) + self.reverseCmapBox.stateChanged.connect(reverse_connector) + # Data indicator line check box self.dataIndicatorCheckBox = QCheckBox() - data_indicator_connector = partial(main_window.toggleTallyDataIndicator) - self.dataIndicatorCheckBox.stateChanged.connect(data_indicator_connector) - - # User specified min/max check box - self.userMinMaxBox = QCheckBox() - minmax_connector = partial(main_window.toggleTallyDataUserMinMax) - self.userMinMaxBox.stateChanged.connect(minmax_connector) + data_indicator_connector = partial( + main_window.toggleTallyDataIndicator) + self.dataIndicatorCheckBox.stateChanged.connect( + data_indicator_connector) + + # Min/max type dropdown + self.minMaxTypeBox = QComboBox() + self.minMaxTypeBox.addItem("Full data") + self.minMaxTypeBox.addItem("Visible data") + self.minMaxTypeBox.addItem("Custom") + minmax_type_connector = partial(main_window.setTallyMinMaxType) + self.minMaxTypeBox.currentIndexChanged.connect(minmax_type_connector) # Data min spin box self.minBox = ScientificDoubleSpinBox() @@ -760,6 +882,10 @@ def __init__(self, model, main_window, field, colormaps=None): max_connector = partial(main_window.editTallyDataMax) self.maxBox.valueChanged.connect(max_connector) + # Labels for min/max (so we can show/hide them) + self.minLabel = QLabel("Min: ") + self.maxLabel = QLabel("Max: ") + # Linear/Log scaling check box self.scaleBox = QCheckBox() scale_connector = partial(main_window.toggleTallyLogScale) @@ -770,6 +896,11 @@ def __init__(self, model, main_window, field, colormaps=None): zero_connector = partial(main_window.toggleTallyMaskZero) self.maskZeroBox.stateChanged.connect(zero_connector) + # Volume normalization check box + self.volumeNormBox = QCheckBox() + volume_connector = partial(main_window.toggleTallyVolumeNorm) + self.volumeNormBox.stateChanged.connect(volume_connector) + # Clip data to min/max check box self.clipDataBox = QCheckBox() clip_connector = partial(main_window.toggleTallyDataClip) @@ -786,13 +917,15 @@ def __init__(self, model, main_window, field, colormaps=None): self.layout.addRow("Visible:", self.visibilityBox) self.layout.addRow("Alpha: ", self.alphaBox) self.layout.addRow("Colormap: ", self.colormapBox) + self.layout.addRow("Reverse colormap: ", self.reverseCmapBox) self.layout.addRow("Data Indicator: ", self.dataIndicatorCheckBox) - self.layout.addRow("Custom Min/Max: ", self.userMinMaxBox) - self.layout.addRow("Min: ", self.minBox) - self.layout.addRow("Max: ", self.maxBox) + self.layout.addRow("Min/max: ", self.minMaxTypeBox) + self.layout.addRow(self.minLabel, self.minBox) + self.layout.addRow(self.maxLabel, self.maxBox) self.layout.addRow("Log Scale: ", self.scaleBox) self.layout.addRow("Clip Data: ", self.clipDataBox) self.layout.addRow("Mask Zeros: ", self.maskZeroBox) + self.layout.addRow("Volume normalize: ", self.volumeNormBox) self.layout.addRow("Contours: ", self.contoursBox) self.layout.addRow("Contour Levels:", self.contourLevelsLine) self.setLayout(self.layout) @@ -806,16 +939,26 @@ def updateDataIndicator(self): cv = self.model.currentView self.dataIndicatorCheckBox.setChecked(cv.tallyDataIndicator) - def setMinMaxEnabled(self, enable): - enable = bool(enable) - self.minBox.setEnabled(enable) - self.maxBox.setEnabled(enable) + def updateMinMaxType(self): + """Update the min/max type dropdown and show/hide min/max inputs.""" + cv = self.model.currentView + type_map = {'full': 0, 'visible': 1, 'custom': 2} + idx = type_map.get(cv.tallyDataMinMaxType, 0) + self.minMaxTypeBox.blockSignals(True) + self.minMaxTypeBox.setCurrentIndex(idx) + self.minMaxTypeBox.blockSignals(False) + # Show/hide min/max inputs based on whether custom is selected + show_custom = (cv.tallyDataMinMaxType == 'custom') + self.minLabel.setVisible(show_custom) + self.minBox.setVisible(show_custom) + self.maxLabel.setVisible(show_custom) + self.maxBox.setVisible(show_custom) def updateMinMax(self): cv = self.model.currentView self.minBox.setValue(cv.tallyDataMin) self.maxBox.setValue(cv.tallyDataMax) - self.setMinMaxEnabled(cv.tallyDataUserMinMax) + self.updateMinMaxType() def updateTallyVisibility(self): cv = self.model.currentView @@ -825,6 +968,10 @@ def updateMaskZeros(self): cv = self.model.currentView self.maskZeroBox.setChecked(cv.tallyMaskZeroValues) + def updateVolumeNorm(self): + cv = self.model.currentView + self.volumeNormBox.setChecked(cv.tallyVolumeNorm) + def updateDataClip(self): cv = self.model.currentView self.clipDataBox.setChecked(cv.clipTallyData) @@ -839,11 +986,11 @@ def update(self): self.alphaBox.setValue(cv.tallyDataAlpha) self.visibilityBox.setChecked(cv.tallyDataVisible) - self.userMinMaxBox.setChecked(cv.tallyDataUserMinMax) self.scaleBox.setChecked(cv.tallyDataLogScale) self.updateMinMax() self.updateMaskZeros() + self.updateVolumeNorm() self.updateDataClip() self.updateDataIndicator() self.updateTallyContours() diff --git a/openmc_plotter/main_window.py b/openmc_plotter/main_window.py index e4579a9..73a53f4 100755 --- a/openmc_plotter/main_window.py +++ b/openmc_plotter/main_window.py @@ -1,14 +1,15 @@ import copy from functools import partial -import os +from pathlib import Path import pickle from threading import Thread -from PySide2 import QtCore, QtGui -from PySide2.QtGui import QKeyEvent -from PySide2.QtWidgets import (QApplication, QLabel, QSizePolicy, QMainWindow, - QScrollArea, QMessageBox, QAction, QFileDialog, - QColorDialog, QInputDialog, QWidget, +from PySide6 import QtCore, QtGui +from PySide6.QtGui import QKeyEvent, QAction +from PySide6.QtWidgets import (QApplication, QLabel, QSizePolicy, QMainWindow, + QScrollArea, QMessageBox, QFileDialog, + QColorDialog, QInputDialog, QWidget, QDialog, + QVBoxLayout, QPlainTextEdit, QDialogButtonBox, QGestureEvent) import openmc @@ -20,36 +21,53 @@ except ImportError: _HAVE_VTK = False -from .plotmodel import PlotModel, DomainTableModel +from .plotmodel import PlotModel, DomainTableModel, hash_model from .plotgui import PlotImage, ColorDialog -from .docks import DomainDock, TallyDock +from .docks import TabbedDock from .overlays import ShortcutsOverlay -from .tools import ExportDataDialog +from .tools import ExportDataDialog, SourceSitesDialog -_COORD_LEVELS = 0 -def _openmcReload(): +def _openmcReload(threads=None, model_path='.'): # reset OpenMC memory, instances openmc.lib.reset() openmc.lib.finalize() # initialize geometry (for volume calculation) openmc.lib.settings.output_summary = False - openmc.lib.init(["-c"]) + args = ["-c"] + if threads is not None: + args += ["-s", str(threads)] + args.append(str(model_path)) + openmc.lib.init(args) + openmc.lib.settings.verbosity = 1 + class MainWindow(QMainWindow): - def __init__(self, font=QtGui.QFontMetrics(QtGui.QFont()), screen_size=QtCore.QSize()): + def __init__(self, + font=QtGui.QFontMetrics(QtGui.QFont()), + screen_size=QtCore.QSize(), + model_path='.', + threads=None, + resolution=None): super().__init__() self.screen = screen_size self.font_metric = font self.setWindowTitle('OpenMC Plot Explorer') + self.model_path = Path(model_path) + self.threads = threads + self.default_res = resolution + self.model = None + self.plot_manager = None + self.materialPropsDialog = None + self.materialPropsText = None - def loadGui(self): + def loadGui(self, use_settings_pkl=True): self.pixmap = None self.zoom = 100 - self.loadModel() + self.loadModel(use_settings_pkl=use_settings_pkl) # Create viewing area self.frame = QScrollArea(self) @@ -64,25 +82,30 @@ def loadGui(self): # Create plot image self.plotIm = PlotImage(self.model, self.frame, self) + self.plotIm.frozen = True self.frame.setWidget(self.plotIm) - # Dock - self.dock = DomainDock(self.model, self.font_metric, self) - self.dock.setObjectName("Domain Options Dock") - self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.dock) + # Tabbed Dock (contains Geometry, Tallies, and Meshes) + self.dock = TabbedDock(self.model, self.font_metric, self) + self.dock.setObjectName("Options Dock") + self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dock) - # Tally Dock - self.tallyDock = TallyDock(self.model, self.font_metric, self) - self.tallyDock.update() - self.tallyDock.setObjectName("Tally Options Dock") - self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.tallyDock) + # Create shortcuts for accessing panels + self.geometryPanel = self.dock.geometryPanel + self.tallyPanel = self.dock.tallyPanel + self.meshAnnotationPanel = self.dock.meshAnnotationPanel - # Color DialogtallyDock + # Color Dialog self.colorDialog = ColorDialog(self.model, self.font_metric, self) self.colorDialog.hide() # Tools self.exportDataDialog = ExportDataDialog(self.model, self.font_metric, self) + self.sourceSitesDialog = SourceSitesDialog(self.model, self.font_metric, self) + + # Keyboard overlay + self.shortcutOverlay = ShortcutsOverlay(self) + self.shortcutOverlay.hide() # Restore Window Settings self.restoreWindowSettings() @@ -96,20 +119,21 @@ def loadGui(self): self.statusBar().addPermanentWidget(self.coord_label) self.coord_label.hide() - # Keyboard overlay - self.shortcutOverlay = ShortcutsOverlay(self) - self.shortcutOverlay.hide() + self.plot_manager = self.model.plot_manager + self.plot_manager.plot_started.connect(self._on_plot_started) + self.plot_manager.plot_queued.connect(self._on_plot_queued) + self.plot_manager.plot_finished.connect(self._on_plot_finished) + self.plot_manager.plot_error.connect(self._on_plot_error) + self.plot_manager.plot_idle.connect(self._on_plot_idle) # Load Plot - self.statusBar().showMessage('Generating Plot...') - self.dock.updateDock() - self.tallyDock.update() + self.geometryPanel.update() + self.tallyPanel.update() self.colorDialog.updateDialogValues() - self.statusBar().showMessage('') - # Timer allows GUI to render before plot finishes loading - QtCore.QTimer.singleShot(0, self.plotIm.generatePixmap) - QtCore.QTimer.singleShot(0, self.showCurrentView) + QtCore.QTimer.singleShot(0, self.requestPlotUpdate) + + self.plotIm.frozen = False def event(self, event): # use pinch event to update zoom @@ -148,7 +172,14 @@ def createMenuBar(self): self.saveImageAction.setShortcut("Ctrl+Shift+S") self.saveImageAction.setToolTip('Save plot image') self.saveImageAction.setStatusTip('Save plot image') - self.saveImageAction.triggered.connect(self.saveImage) + save_image_connector = partial(self.saveImage, filename=None) + self.saveImageAction.triggered.connect(save_image_connector) + + self.copyImageAction = QAction("&Copy Image", self) + self.copyImageAction.setShortcut("Ctrl+Shift+C") + self.copyImageAction.setToolTip('Copy plot image to clipboard') + self.copyImageAction.setStatusTip('Copy plot image to clipboard') + self.copyImageAction.triggered.connect(self.copyImageToClipboard) self.saveViewAction = QAction("Save &View...", self) self.saveViewAction.setShortcut(QtGui.QKeySequence.Save) @@ -177,6 +208,7 @@ def createMenuBar(self): self.fileMenu = self.mainMenu.addMenu('&File') self.fileMenu.addAction(self.reloadModelAction) + self.fileMenu.addAction(self.copyImageAction) self.fileMenu.addAction(self.saveImageAction) self.fileMenu.addAction(self.exportDataAction) self.fileMenu.addSeparator() @@ -190,8 +222,19 @@ def createMenuBar(self): self.openStatePointAction.setToolTip('Open statepoint file') self.openStatePointAction.triggered.connect(self.openStatePoint) + self.sourceSitesAction = QAction('&Sample source sites...', self) + self.sourceSitesAction.setToolTip('Add source sites to plot') + self.setStatusTip('Sample and add source sites to the plot') + self.sourceSitesAction.triggered.connect(self.plotSourceSites) + + self.importPropertiesAction = QAction("&Import properties...", self) + self.importPropertiesAction.setToolTip("Import properties") + self.importPropertiesAction.triggered.connect(self.importProperties) + self.dataMenu = self.mainMenu.addMenu('D&ata') self.dataMenu.addAction(self.openStatePointAction) + self.dataMenu.addAction(self.sourceSitesAction) + self.dataMenu.addAction(self.importPropertiesAction) self.updateDataMenu() # Edit Menu @@ -341,7 +384,7 @@ def createMenuBar(self): self.outlineAct.setToolTip('Display Cell/Material Boundaries') self.outlineAct.setStatusTip('Toggle display of domain ' 'outlines when enabled') - outline_connector = partial(self.toggleOutlines, apply=True) + outline_connector = partial(self.toggleOutlinesCell, apply=True) self.outlineAct.toggled.connect(outline_connector) self.editMenu.addAction(self.outlineAct) @@ -352,12 +395,6 @@ def createMenuBar(self): self.dockAction.setStatusTip('Toggle dock visibility') self.dockAction.triggered.connect(self.toggleDockView) - self.tallyDockAction = QAction('Tally &Dock', self) - self.tallyDockAction.setShortcut("Ctrl+T") - self.tallyDockAction.setToolTip('Toggle tally dock visibility') - self.tallyDockAction.setStatusTip('Toggle tally dock visibility') - self.tallyDockAction.triggered.connect(self.toggleTallyDockView) - self.zoomAction = QAction('&Zoom...', self) self.zoomAction.setShortcut('Alt+Shift+Z') self.zoomAction.setToolTip('Edit zoom factor') @@ -366,7 +403,6 @@ def createMenuBar(self): self.viewMenu = self.mainMenu.addMenu('&View') self.viewMenu.addAction(self.dockAction) - self.viewMenu.addAction(self.tallyDockAction) self.viewMenu.addSeparator() self.viewMenu.addAction(self.zoomAction) self.viewMenu.aboutToShow.connect(self.updateViewMenu) @@ -401,9 +437,17 @@ def updateEditMenu(self): changed = self.model.currentView != self.model.defaultView self.restoreAction.setDisabled(not changed) + toggle_actions = (self.maskingAction, self.highlightingAct, + self.outlineAct, self.overlapAct) + # Temporarily block signals to avoid triggering plot update + for action in toggle_actions: + action.blockSignals(True) self.maskingAction.setChecked(self.model.currentView.masking) self.highlightingAct.setChecked(self.model.currentView.highlighting) - self.outlineAct.setChecked(self.model.currentView.outlines) + self.outlineAct.setChecked(self.model.currentView.outlinesCell) + self.overlapAct.setChecked(self.model.currentView.color_overlaps) + for action in toggle_actions: + action.blockSignals(False) num_previous_views = len(self.model.previousViews) self.undoAction.setText('&Undo ({})'.format(num_previous_views)) @@ -432,22 +476,41 @@ def updateWindowMenu(self): self.colorDialogAction.setChecked(self.colorDialog.isActiveWindow()) self.mainWindowAction.setChecked(self.isActiveWindow()) + def saveBatchImage(self, view_file): + """ + Loads a view in the GUI and generates an image + + Parameters + ---------- + view_file : str or pathlib.Path + The path to a view file that is compatible with the loaded model. + """ + # store the + cv = self.model.currentView + # load the view from file + self.loadViewFile(view_file) + self.waitForPlotIdle() + self.plotIm.saveImage(view_file.replace('.pltvw', '')) + # Menu and shared methods - def loadModel(self, reload=False): + def loadModel(self, reload=False, use_settings_pkl=True): if reload: + if self.plot_manager is not None: + self.plot_manager.wait_for_idle() self.resetModels() else: - # create new plot model - self.model = PlotModel() - self.restoreModelSettings() + self.model = PlotModel(use_settings_pkl, self.model_path, self.default_res) + # update plot and model settings self.updateRelativeBases() self.cellsModel = DomainTableModel(self.model.activeView.cells) self.materialsModel = DomainTableModel(self.model.activeView.materials) + openmc_args = {'threads': self.threads, 'model_path': self.model_path} + if reload: - loader_thread = Thread(target=_openmcReload) + loader_thread = Thread(target=_openmcReload, kwargs=openmc_args) loader_thread.start() while loader_thread.is_alive(): self.statusBar().showMessage("Reloading model...") @@ -456,17 +519,24 @@ def loadModel(self, reload=False): self.plotIm.model = self.model self.applyChanges() - def saveImage(self): - filename, ext = QFileDialog.getSaveFileName(self, - "Save Plot Image", - "untitled", - "Images (*.png)") + def saveImage(self, filename=None): + if filename is None: + filename, ext = QFileDialog.getSaveFileName(self, + "Save Plot Image", + "untitled", + "Images (*.png)") if filename: - if "." not in filename: - filename += ".png" - self.plotIm.figure.savefig(filename, transparent=True) + self.plotIm.saveImage(filename) self.statusBar().showMessage('Plot Image Saved', 5000) + def copyImageToClipboard(self): + if self.plotIm.copyImageToClipboard(): + self.statusBar().showMessage('Plot Image Copied', 5000) + return True + + self.statusBar().showMessage('No Plot Image Available', 5000) + return False + def saveView(self): filename, ext = QFileDialog.getSaveFileName(self, "Save View Settings", @@ -481,59 +551,94 @@ def saveView(self): with open(filename, 'wb') as file: pickle.dump(saved, file) + def loadViewFile(self, filename): + try: + with open(filename, 'rb') as file: + saved = pickle.load(file) + except Exception: + message = 'Error loading plot settings' + saved = {'version': None, + 'current': None} + + if saved['version'] == self.model.version: + self.model.activeView = saved['current'] + # Handle backward compatibility for outline attributes + if not hasattr(self.model.activeView, 'outlinesCell'): + self.model.activeView.outlinesCell = False + if not hasattr(self.model.activeView, 'outlinesMat'): + self.model.activeView.outlinesMat = False + self.geometryPanel.update() + self.colorDialog.updateDialogValues() + self.applyChanges() + message = '{} loaded'.format(filename) + else: + message = 'Error loading plot settings. Incompatible model.' + self.statusBar().showMessage(message, 5000) + def openView(self): filename, ext = QFileDialog.getOpenFileName(self, "Open View Settings", ".", "*.pltvw") if filename: - try: - with open(filename, 'rb') as file: - saved = pickle.load(file) - except Exception: - message = 'Error loading plot settings' - saved = {'version': None, - 'current': None} - if saved['version'] == self.model.version: - self.model.activeView = saved['current'] - self.dock.updateDock() - self.colorDialog.updateDialogValues() - self.applyChanges() - message = '{} settings loaded'.format(filename) - else: - message = 'Error loading plot settings. Incompatible model.' - self.statusBar().showMessage(message, 5000) + self.loadViewFile(filename) def openStatePoint(self): - # check for an alread-open statepoint + # confirm replacement when a statepoint is already open if self.model.statepoint: - msg_box = QMessageBox() - msg_box.setText("Please close the current statepoint file before " - "opening a new one.") + msg_box = QMessageBox(self) + msg_box.setText("A statepoint file is currently open. Continue to " + "close it and open a new one?") msg_box.setIcon(QMessageBox.Information) - msg_box.setStandardButtons(QMessageBox.Ok) - msg_box.exec_() - return + msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel) + msg_box.setDefaultButton(QMessageBox.Cancel) + msg_box.button(QMessageBox.Yes).setText("Continue") + if msg_box.exec() != QMessageBox.Yes: + return + self.closeStatePoint() filename, ext = QFileDialog.getOpenFileName(self, "Open StatePoint", - ".", "statepoint*.h5") + ".", "*.h5") if filename: try: self.model.openStatePoint(filename) - message = 'Opened statepoint file: {}' - except (FileNotFoundError, OSError): - message = 'Error opening statepoint file: {}' + message = f'Opened statepoint file: {filename}' + except Exception as e: + message = f'Error opening statepoint file: {filename}' msg_box = QMessageBox() - msg = "Could not open statepoint file: \n\n {} \n" - msg_box.setText(msg.format(filename)) + msg = f"Could not open statepoint file:\n{filename}\n\n{e}" + msg_box.setText(msg) msg_box.setIcon(QMessageBox.Warning) msg_box.setStandardButtons(QMessageBox.Ok) - msg_box.exec_() + msg_box.exec() finally: - self.statusBar().showMessage(message.format(filename), 5000) + self.statusBar().showMessage(message, 5000) self.updateDataMenu() - self.tallyDock.update() + self.tallyPanel.update() + + def importProperties(self): + filename, ext = QFileDialog.getOpenFileName(self, "Import properties", + ".", "*.h5") + if not filename: + return + + try: + openmc.lib.import_properties(filename) + message = 'Imported properties: {}' + except (FileNotFoundError, OSError, openmc.lib.exc.OpenMCError) as e: + message = 'Error opening properties file: {}' + msg_box = QMessageBox() + msg_box.setText(f"Error opening properties file: \n\n {e} \n") + msg_box.setIcon(QMessageBox.Warning) + msg_box.setStandardButtons(QMessageBox.Ok) + msg_box.exec() + finally: + self.statusBar().showMessage(message.format(filename), 5000) + + if self.model.activeView.colorby == 'temperature': + self.applyChanges() def closeStatePoint(self): # remove the statepoint object and update the data menu filename = self.model.statepoint.filename + self.model.statepoint.close() self.model.statepoint = None self.model.currentView.selectedTally = None self.model.activeView.selectedTally = None @@ -541,8 +646,8 @@ def closeStatePoint(self): msg = "Closed statepoint file {}".format(filename) self.statusBar().showMessage(msg) self.updateDataMenu() - self.tallyDock.selectTally() - self.tallyDock.update() + self.tallyPanel.selectTally() + self.tallyPanel.update() self.plotIm.updatePixmap() def updateDataMenu(self): @@ -554,75 +659,69 @@ def updateDataMenu(self): elif hasattr(self, "closeStatePointAction"): self.dataMenu.removeAction(self.closeStatePointAction) + + def updateMeshAnnotations(self): + self.model.activeView.mesh_annotations = self.meshAnnotationPanel.get_checked_meshes() + + def plotSourceSites(self): + self.sourceSitesDialog.show() + self.sourceSitesDialog.raise_() + self.sourceSitesDialog.activateWindow() + def applyChanges(self): if self.model.activeView != self.model.currentView: - self.statusBar().showMessage('Generating Plot...') - QApplication.processEvents() + if self.model.activeView.selectedTally is not None: + self.tallyPanel.updateModel() + self.updateMeshAnnotations() self.model.storeCurrent() self.model.subsequentViews = [] - self.plotIm.generatePixmap() - self.resetModels() - self.showCurrentView() - self.statusBar().showMessage('') + self.requestPlotUpdate() else: self.statusBar().showMessage('No changes to apply.', 3000) def undo(self): - self.statusBar().showMessage('Generating Plot...') - QApplication.processEvents() - + if not self.model.previousViews: + return self.model.undo() - self.resetModels() - self.showCurrentView() - self.dock.updateDock() + self.geometryPanel.update() self.colorDialog.updateDialogValues() + self.requestPlotUpdate() if not self.model.previousViews: self.undoAction.setDisabled(True) self.redoAction.setDisabled(False) - self.statusBar().showMessage('') def redo(self): - self.statusBar().showMessage('Generating Plot...') - QApplication.processEvents() - + if not self.model.subsequentViews: + return self.model.redo() - self.resetModels() - self.showCurrentView() - self.dock.updateDock() + self.geometryPanel.update() self.colorDialog.updateDialogValues() + self.requestPlotUpdate() if not self.model.subsequentViews: self.redoAction.setDisabled(True) self.undoAction.setDisabled(False) - self.statusBar().showMessage('') def restoreDefault(self): if self.model.currentView != self.model.defaultView: - - self.statusBar().showMessage('Generating Plot...') - QApplication.processEvents() - self.model.storeCurrent() - self.model.activeView.adopt_plotbase(self.model.defaultView) - self.plotIm.generatePixmap() - self.resetModels() - self.showCurrentView() - self.dock.updateDock() + self.model.activeView.adopt_view_params(self.model.defaultView) + self.geometryPanel.update() self.colorDialog.updateDialogValues() + self.requestPlotUpdate() self.model.subsequentViews = [] - self.statusBar().showMessage('') def editBasis(self, basis, apply=False): self.model.activeView.basis = basis - self.dock.updateBasis() + self.geometryPanel.updateBasis() if apply: self.applyChanges() def editColorBy(self, domain_kind, apply=False): self.model.activeView.colorby = domain_kind - self.dock.updateColorBy() + self.geometryPanel.updateColorBy() self.colorDialog.updateColorBy() if apply: self.applyChanges() @@ -632,7 +731,7 @@ def editUniverseLevel(self, level, apply=False): self.model.activeView.level = -1 else: self.model.activeView.level = int(level) - self.dock.updateUniverseLevel() + self.geometryPanel.updateUniverseLevel() self.colorDialog.updateUniverseLevel() if apply: self.applyChanges() @@ -722,28 +821,16 @@ def toggleDockView(self): self.resizePixmap() self.showMainWindow() - def toggleTallyDockView(self): - if self.tallyDock.isVisible(): - self.tallyDock.hide() - if not self.isMaximized() and not self.tallyDock.isFloating(): - self.resize(self.width() - self.tallyDock.width(), self.height()) - else: - self.tallyDock.setVisible(True) - if not self.isMaximized() and not self.tallyDock.isFloating(): - self.resize(self.width() + self.tallyDock.width(), self.height()) - self.resizePixmap() - self.showMainWindow() - def editZoomAct(self): percent, ok = QInputDialog.getInt(self, "Edit Zoom", "Zoom Percent:", - self.dock.zoomBox.value(), 25, 2000) + self.geometryPanel.zoomBox.value(), 25, 2000) if ok: - self.dock.zoomBox.setValue(percent) + self.geometryPanel.zoomBox.setValue(percent) def editZoom(self, value): self.zoom = value self.resizePixmap() - self.dock.zoomBox.setValue(value) + self.geometryPanel.zoomBox.setValue(value) def showMainWindow(self): self.raise_() @@ -770,9 +857,16 @@ def editPlotAlpha(self, value): def editPlotVisibility(self, value): self.model.activeView.domainVisible = bool(value) - def toggleOutlines(self, value, apply=False): - self.model.activeView.outlines = bool(value) - self.dock.updateOutlines() + def toggleOutlinesCell(self, value, apply=False): + self.model.activeView.outlinesCell = bool(value) + self.geometryPanel.updateOutlines() + + if apply: + self.applyChanges() + + def toggleOutlinesMat(self, value, apply=False): + self.model.activeView.outlinesMat = bool(value) + self.geometryPanel.updateOutlines() if apply: self.applyChanges() @@ -780,26 +874,26 @@ def toggleOutlines(self, value, apply=False): def editWidth(self, value): self.model.activeView.width = value self.onRatioChange() - self.dock.updateWidth() + self.geometryPanel.updateWidth() def editHeight(self, value): self.model.activeView.height = value self.onRatioChange() - self.dock.updateHeight() + self.geometryPanel.updateHeight() def toggleAspectLock(self, state): self.model.activeView.aspectLock = bool(state) self.onRatioChange() - self.dock.updateAspectLock() + self.geometryPanel.updateAspectLock() def editVRes(self, value): self.model.activeView.v_res = value - self.dock.updateVRes() + self.geometryPanel.updateVRes() def editHRes(self, value): self.model.activeView.h_res = value self.onRatioChange() - self.dock.updateHRes() + self.geometryPanel.updateHRes() # Color dialog methods: @@ -808,7 +902,7 @@ def editMaskingColor(self): dlg = QColorDialog(self) dlg.setCurrentColor(QtGui.QColor.fromRgb(*current_color)) - if dlg.exec_(): + if dlg.exec(): new_color = dlg.currentColor().getRgb()[:3] self.model.activeView.maskBackground = new_color self.colorDialog.updateMaskingColor() @@ -818,7 +912,7 @@ def editHighlightColor(self): dlg = QColorDialog(self) dlg.setCurrentColor(QtGui.QColor.fromRgb(*current_color)) - if dlg.exec_(): + if dlg.exec(): new_color = dlg.currentColor().getRgb()[:3] self.model.activeView.highlightBackground = new_color self.colorDialog.updateHighlightColor() @@ -833,7 +927,7 @@ def editOverlapColor(self, apply=False): current_color = self.model.activeView.overlap_color dlg = QColorDialog(self) dlg.setCurrentColor(QtGui.QColor.fromRgb(*current_color)) - if dlg.exec_(): + if dlg.exec(): new_color = dlg.currentColor().getRgb()[:3] self.model.activeView.overlap_color = new_color self.colorDialog.updateOverlapColor() @@ -846,7 +940,7 @@ def editBackgroundColor(self, apply=False): dlg = QColorDialog(self) dlg.setCurrentColor(QtGui.QColor.fromRgb(*current_color)) - if dlg.exec_(): + if dlg.exec(): new_color = dlg.currentColor().getRgb()[:3] self.model.activeView.domainBackground = new_color self.colorDialog.updateBackgroundColor() @@ -868,18 +962,12 @@ def editSelectedTally(self, event): av.selectedTally = None else: av.selectedTally = int(event.split()[1]) - self.tallyDock.selectTally(event) + self.tallyPanel.selectTally(event) def editTallyValue(self, event): av = self.model.activeView av.tallyValue = event - def updateScores(self, state): - self.tallyDock.updateScores() - - def updateNuclides(self, state): - self.tallyDock.updateNuclides() - def toggleTallyVisibility(self, state, apply=False): av = self.model.activeView av.tallyDataVisible = bool(state) @@ -896,6 +984,10 @@ def toggleTallyMaskZero(self, state): av = self.model.activeView av.tallyMaskZeroValues = bool(state) + def toggleTallyVolumeNorm(self, state): + av = self.model.activeView + av.tallyVolumeNorm = bool(state) + def editTallyAlpha(self, value, apply=False): av = self.model.activeView av.tallyDataAlpha = value @@ -920,10 +1012,29 @@ def toggleTallyDataClip(self, state): av = self.model.activeView av.clipTallyData = bool(state) - def toggleTallyDataUserMinMax(self, state, apply=False): + def setTallyMinMaxType(self, index, apply=False): + """Set the min/max type for tally data. + + Parameters + ---------- + index : int + Index of the selected option: 0='full', 1='visible', 2='custom' + apply : bool + Whether to apply changes immediately + """ av = self.model.activeView - av.tallyDataUserMinMax = bool(state) - self.tallyDock.tallyColorForm.setMinMaxEnabled(bool(state)) + type_map = {0: 'full', 1: 'visible', 2: 'custom'} + new_type = type_map.get(index, 'full') + av.tallyDataMinMaxType = new_type + + # Immediately update visibility of min/max fields based on selection + show_custom = (new_type == 'custom') + form = self.tallyPanel.tallyColorForm + form.minLabel.setVisible(show_custom) + form.minBox.setVisible(show_custom) + form.maxLabel.setVisible(show_custom) + form.maxBox.setVisible(show_custom) + if apply: self.applyChanges() @@ -945,8 +1056,12 @@ def editTallyDataColormap(self, cmap, apply=False): if apply: self.applyChanges() + def toggleReverseCmap(self, state): + av = self.model.activeView + av.tallyDataReverseCmap = bool(state) + def updateTallyMinMax(self): - self.tallyDock.updateMinMax() + self.tallyPanel.updateMinMax() # Plot image methods def editPlotOrigin(self, xOr, yOr, zOr=None, apply=False): @@ -959,13 +1074,13 @@ def editPlotOrigin(self, xOr, yOr, zOr=None, apply=False): origin[self.zBasis] = self.model.activeView.origin[self.zBasis] self.model.activeView.origin = origin - self.dock.updateOrigin() + self.geometryPanel.updateOrigin() if apply: self.applyChanges() def revertDockControls(self): - self.dock.revertToCurrent() + self.geometryPanel.revertToCurrent() def editDomainColor(self, kind, id): if kind == 'Cell': @@ -981,9 +1096,9 @@ def editDomainColor(self, kind, id): elif isinstance(current_color, str): current_color = openmc.plots._SVG_COLORS[current_color] dlg.setCurrentColor(QtGui.QColor.fromRgb(*current_color)) - if dlg.exec_(): + if dlg.exec(): new_color = dlg.currentColor().getRgb()[:3] - domain[id].color = new_color + domain.set_color(id, new_color) self.applyChanges() @@ -993,7 +1108,7 @@ def toggleDomainMask(self, state, kind, id): else: domain = self.model.activeView.materials - domain[id].masked = bool(state) + domain.set_masked(id, bool(state)) self.applyChanges() def toggleDomainHighlight(self, state, kind, id): @@ -1002,7 +1117,7 @@ def toggleDomainHighlight(self, state, kind, id): else: domain = self.model.activeView.materials - domain[id].highlight = bool(state) + domain.set_highlight(id, bool(state)) self.applyChanges() # Helper methods: @@ -1011,7 +1126,7 @@ def restoreWindowSettings(self): settings = QtCore.QSettings() self.resize(settings.value("mainWindow/Size", - QtCore.QSize(800, 600))) + QtCore.QSize(1200, 800))) self.move(settings.value("mainWindow/Position", QtCore.QPoint(100, 100))) self.restoreState(settings.value("mainWindow/State")) @@ -1029,36 +1144,6 @@ def restoreWindowSettings(self): self.colorDialog.setVisible(is_visible) - def restoreModelSettings(self): - if os.path.isfile("plot_settings.pkl"): - - with open('plot_settings.pkl', 'rb') as file: - model = pickle.load(file) - - # do not replace model if the version is out of date - if model.version != self.model.version: - print("WARNING: previous plot settings are for a different " - "version of the GUI. They will be ignored.") - wrn_msg = "Existing version: {}, Current GUI version: {}" - print(wrn_msg.format(model.version, self.model.version)) - return - - try: - self.model.statepoint = model.statepoint - except OSError: - msg_box = QMessageBox() - msg = "Could not open statepoint file: \n\n {} \n" - msg_box.setText(msg.format(self.model.statepoint.filename)) - msg_box.setIcon(QMessageBox.Warning) - msg_box.setStandardButtons(QMessageBox.Ok) - msg_box.exec_() - self.model.statepoint = None - - self.model.currentView = model.currentView - self.model.activeView = copy.deepcopy(model.currentView) - self.model.previousViews = model.previousViews - self.model.subsequentViews = model.subsequentViews - def resetModels(self): self.cellsModel = DomainTableModel(self.model.activeView.cells) self.materialsModel = DomainTableModel(self.model.activeView.materials) @@ -1101,7 +1186,7 @@ def onRatioChange(self): if av.aspectLock: ratio = av.width / max(av.height, .001) av.v_res = int(av.h_res / ratio) - self.dock.updateVRes() + self.geometryPanel.updateVRes() def showCoords(self, xPlotPos, yPlotPos): cv = self.model.currentView @@ -1134,6 +1219,9 @@ def resizeEvent(self, event): self.shortcutOverlay.resize(self.width(), self.height()) def closeEvent(self, event): + if self.plot_manager is not None: + self.plot_manager.wait_for_idle(timeout_ms=250) + self.plot_manager.shutdown() settings = QtCore.QSettings() settings.setValue("mainWindow/Size", self.size()) settings.setValue("mainWindow/Position", self.pos()) @@ -1148,18 +1236,121 @@ def closeEvent(self, event): self.saveSettings() - def saveSettings(self): + def requestPlotUpdate(self, view=None): + if self.model is None: + return + if view is None: + view = self.model.activeView + view_snapshot = copy.deepcopy(view) + if self.model.can_reuse_maps(view_snapshot): + view_params = self.model.view_params_payload(view_snapshot) + self.plot_manager.set_latest_view_params(view_params) + self.plot_manager.clear_pending() + self.model.makePlot(view_snapshot, self.model.geom_data, self.model.property_data) + self.resetModels() + self.showCurrentView() + if not self.plot_manager.is_busy: + self._on_plot_idle() + return + view_params = self.model.view_params_payload(view_snapshot) + self.plot_manager.enqueue(view_snapshot, view_params) + + def waitForPlotIdle(self, timeout_ms=None): + if self.plot_manager is not None: + return self.plot_manager.wait_for_idle(timeout_ms) + return True - if len(self.model.previousViews) > 10: - self.model.previousViews = self.model.previousViews[-10:] - if len(self.model.subsequentViews) > 10: - self.model.subsequentViews = self.model.subsequentViews[-10:] + def _on_plot_started(self): + self.plotIm.showUpdatingOverlay("Generating Plot...") - with open('plot_settings.pkl', 'wb') as file: - if self.model.statepoint: - self.model.statepoint.close() - pickle.dump(self.model, file) + def _on_plot_queued(self): + self.plotIm.showUpdatingOverlay("Generating Plot... (update queued)") + + def _on_plot_finished(self, view_snapshot, view_params, geom_data, property_data): + if view_params != self.plot_manager.latest_view_params: + return + self.model.makePlot(view_snapshot, geom_data, property_data) + self.resetModels() + self.showCurrentView() + + def _on_plot_error(self, error_msg): + msg_box = QMessageBox() + msg_box.setText(f"Failed to generate plot:\n\n{error_msg}") + msg_box.setIcon(QMessageBox.Warning) + msg_box.setStandardButtons(QMessageBox.Ok) + msg_box.exec() + + def _on_plot_idle(self): + self.plotIm.hideUpdatingOverlay() + + def saveSettings(self): + if self.model.statepoint: + self.model.statepoint.close() + + # get hashes for material.xml and geometry.xml at close + mat_xml_hash, geom_xml_hash = hash_model(self.model_path) + + pickle_data = { + 'version': self.model.version, + 'currentView': self.model.currentView, + 'statepoint': self.model.statepoint, + 'mat_xml_hash': mat_xml_hash, + 'geom_xml_hash': geom_xml_hash + } + if self.model_path.is_file(): + settings_pkl = self.model_path.with_name('plot_settings.pkl') + else: + settings_pkl = self.model_path / 'plot_settings.pkl' + with settings_pkl.open('wb') as file: + pickle.dump(pickle_data, file) def exportTallyData(self): # show export tool dialog self.showExportDialog() + + def viewMaterialProps(self, id): + """Display material properties in a scrollable dialog.""" + mat = openmc.lib.materials[id] + if mat.name: + title = f"Material {id} ({mat.name}) Properties" + else: + title = f"Material {id} Properties" + + msg_str = f"{title}\n\n" + + # get density and temperature + dens_g = mat.get_density(units='g/cm3') + dens_a = mat.get_density(units='atom/b-cm') + msg_str += f"Density: {dens_g:.3f} g/cm3 ({dens_a:.3e} atom/b-cm)\n" + msg_str += f"Temperature: {mat.temperature} K\n\n" + + # get nuclides and their densities + msg_str += "Nuclide densities [atom/b-cm]:\n" + for nuc, dens in zip(mat.nuclides, mat.densities): + msg_str += f'{nuc}: {dens:5.3e}\n' + + if self.materialPropsDialog is None: + dialog = QDialog(self) + dialog.setModal(False) + dialog.setMinimumSize(560, 420) + + layout = QVBoxLayout(dialog) + text = QPlainTextEdit(dialog) + text.setReadOnly(True) + text.setLineWrapMode(QPlainTextEdit.NoWrap) + layout.addWidget(text) + + buttons = QDialogButtonBox(QDialogButtonBox.Close, parent=dialog) + buttons.rejected.connect(dialog.close) + buttons.accepted.connect(dialog.close) + layout.addWidget(buttons) + + self.materialPropsDialog = dialog + self.materialPropsText = text + + self.materialPropsDialog.setWindowTitle(title) + self.materialPropsText.setPlainText(msg_str) + self.materialPropsText.moveCursor(QtGui.QTextCursor.Start) + self.materialPropsDialog.show() + self.materialPropsDialog.raise_() + self.materialPropsDialog.activateWindow() diff --git a/openmc_plotter/overlays.py b/openmc_plotter/overlays.py index 153c439..a87b453 100644 --- a/openmc_plotter/overlays.py +++ b/openmc_plotter/overlays.py @@ -1,7 +1,7 @@ from sys import platform -from PySide2 import QtGui, QtCore -from PySide2.QtWidgets import (QWidget, QTableWidget, QSizePolicy, +from PySide6 import QtGui, QtCore +from PySide6.QtWidgets import (QWidget, QTableWidget, QSizePolicy, QPushButton, QTableWidgetItem, QVBoxLayout) c_key = "⌘" if platform == 'darwin' else "Ctrl" @@ -38,8 +38,7 @@ class ShortcutsOverlay(QWidget): ("When zoomed:", ""), ("Vertical Scroll", "Scroll"), ("Horizontal Scroll", "Alt+Scroll")], - "Menus": [("Hide/Show Geometry Dock", c_key + "+D"), - ("Hide/Show Tally Dock", c_key + "+T"), + "Menus": [("Hide/Show Dock", c_key + "+D"), ("Reload Model", "Shift+" + c_key + "+R"), ("Quit", c_key + "+Q"), ("Display Shortcuts", "?")], @@ -101,18 +100,18 @@ def set_cells(self): for menu in self.shortcuts: # set menu header header_item = self.tableWidget.item(row_idx, col_idx) - header_item.setTextColor(QtGui.QColor(150, 150, 150, 255)) + header_item.setForeground(QtGui.QColor(150, 150, 150, 255)) header_item.setText(menu) header_item.setFlags(QtCore.Qt.NoItemFlags) row_idx += 1 for shortcut in self.shortcuts[menu]: desc_item = self.tableWidget.item(row_idx, col_idx) - desc_item.setTextColor(self.textPenColor) + desc_item.setForeground(self.textPenColor) desc_item.setText(shortcut[0]) key_item = self.tableWidget.item(row_idx, col_idx + 1) - key_item.setTextColor(self.textPenColor) + key_item.setForeground(self.textPenColor) key_item.setText(shortcut[1]) row_idx += 1 # update for next menu diff --git a/openmc_plotter/plot_colors.py b/openmc_plotter/plot_colors.py index 9c973d1..a77f27b 100644 --- a/openmc_plotter/plot_colors.py +++ b/openmc_plotter/plot_colors.py @@ -1,12 +1,6 @@ - import numpy as np -# for consistent, but random, colors -def reset_seed(): - np.random.seed(10) - - def random_rgb(): return tuple(np.random.choice(range(256), size=3)) diff --git a/openmc_plotter/plotgui.py b/openmc_plotter/plotgui.py index d735880..22cce96 100644 --- a/openmc_plotter/plotgui.py +++ b/openmc_plotter/plotgui.py @@ -1,30 +1,58 @@ +import io from functools import partial -from PySide2 import QtCore, QtGui -from PySide2.QtWidgets import (QWidget, QPushButton, QHBoxLayout, QVBoxLayout, - QFormLayout, QComboBox, QSpinBox, +from PySide6 import QtCore, QtGui +from PySide6.QtWidgets import (QWidget, QPushButton, QHBoxLayout, QVBoxLayout, + QFormLayout, QComboBox, QSpinBox, QLabel, QDoubleSpinBox, QSizePolicy, QMessageBox, QCheckBox, QRubberBand, QMenu, QDialog, QTabWidget, QTableView, QHeaderView) -from matplotlib.backends.qt_compat import is_pyqt5 from matplotlib.figure import Figure from matplotlib import lines as mlines -from matplotlib import cm as mcolormaps from matplotlib.colors import SymLogNorm +from matplotlib.backends.backend_qt5agg import FigureCanvas +import matplotlib.pyplot as plt import numpy as np +import numpy.ma as ma from .plot_colors import rgb_normalize, invert_rgb -from .plotmodel import DomainDelegate +from .plotmodel import DomainDelegate, PlotModel from .plotmodel import _NOT_FOUND, _VOID_REGION, _OVERLAP, _MODEL_PROPERTIES from .scientific_spin_box import ScientificDoubleSpinBox from .custom_widgets import HorizontalLine -from matplotlib.backends.backend_qt5agg import FigureCanvas + +class PlotUpdateOverlay(QWidget): + + def __init__(self, parent=None): + super().__init__(parent) + self.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents, True) + self.setAttribute(QtCore.Qt.WA_StyledBackground, True) + self.setFocusPolicy(QtCore.Qt.NoFocus) + self.setStyleSheet("background-color: rgba(20, 20, 20, 140);") + + layout = QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 0) + layout.setAlignment(QtCore.Qt.AlignCenter) + + self.label = QLabel("Generating Plot...", self) + self.label.setAlignment(QtCore.Qt.AlignCenter) + font = self.label.font() + font.setPointSize(max(12, font.pointSize() + 6)) + self.label.setFont(font) + self.label.setStyleSheet("color: white; background-color: transparent;") + layout.addWidget(self.label) + + self.hide() + + def set_message(self, message: str): + self.label.setText(message) + class PlotImage(FigureCanvas): - def __init__(self, model, parent, main_window): + def __init__(self, model: PlotModel, parent, main_window): self.figure = Figure(dpi=main_window.logicalDpiX()) super().__init__(self.figure) @@ -38,17 +66,28 @@ def __init__(self, model, parent, main_window): self.main_window = main_window self.parent = parent + self.frozen = False + self.rubber_band = QRubberBand(QRubberBand.Rectangle, self) self.band_origin = QtCore.QPoint() self.x_plot_origin = None self.y_plot_origin = None - self.colorbar = None + self.property_colorbar = None self.data_indicator = None self.tally_data_indicator = None + self.tally_colorbar = None + self.tally_image = None self.image = None + self.ax = None + + self._property_colorbar_bg = None + self._tally_colorbar_bg = None + self._last_tally_indicator_value = None + self._last_data_indicator_value = None self.menu = QMenu(self) + self.update_overlay = PlotUpdateOverlay(self) def enterEvent(self, event): self.setCursor(QtCore.Qt.CrossCursor) @@ -70,6 +109,8 @@ def mousePressEvent(self, event): QtCore.QSize())) def getPlotCoords(self, pos): + if self.ax is None: + return (0.0, 0.0) x, y = self.mouseEventCoords(pos) # get the normalized axis coordinates from the event display units @@ -110,6 +151,90 @@ def _resize(self): self.resize(self.parent.width() * z, self.parent.height() * z) + def resizeEvent(self, event): + super().resizeEvent(event) + if self.update_overlay is not None: + self.update_overlay.setGeometry(self.rect()) + + def showUpdatingOverlay(self, message: str = "Generating Plot..."): + if self.update_overlay is None: + return + self.update_overlay.set_message(message) + self.update_overlay.setGeometry(self.rect()) + self.update_overlay.raise_() + self.update_overlay.show() + + def hideUpdatingOverlay(self): + if self.update_overlay is None: + return + self.update_overlay.hide() + + def saveImage(self, filename): + """Save an image of the current view + + Parameters + ---------- + filename : str or pathlib.Path + Name of the image to save + """ + if "." not in str(filename): + filename += ".png" + self.figure.savefig(filename, transparent=True) + + def copyImageToClipboard(self): + """Copy the current canvas image to the clipboard.""" + image = self._export_plot_image() + if image is None: + return False + + clipboard = QtGui.QGuiApplication.clipboard() + if clipboard is None: + return False + + clipboard.setImage(image) + return True + + def _export_plot_image(self): + self.draw() + width, height = self.get_width_height() + if width <= 0 or height <= 0: + return None + + buffer = io.BytesIO() + self.figure.savefig(buffer, format='png', transparent=True) + image = QtGui.QImage.fromData(buffer.getvalue(), 'PNG') + if image.isNull(): + return None + + crop_rect = self._visible_canvas_rect(image.width(), image.height()) + if crop_rect.isEmpty(): + return None + + return image.copy(crop_rect) + + def _visible_canvas_rect(self, image_width, image_height): + if self.width() <= 0 or self.height() <= 0: + return QtCore.QRect() + + if self.parent is None or not hasattr(self.parent, 'viewport'): + return QtCore.QRect(0, 0, image_width, image_height) + + viewport = self.parent.viewport() + visible_width = min(viewport.width(), self.width()) + visible_height = min(viewport.height(), self.height()) + x_offset = self.parent.horizontalScrollBar().value() + y_offset = self.parent.verticalScrollBar().value() + + scale_x = image_width / self.width() + scale_y = image_height / self.height() + + return QtCore.QRect(round(x_offset * scale_x), + round(y_offset * scale_y), + round(visible_width * scale_x), + round(visible_height * scale_y)).intersected( + QtCore.QRect(0, 0, image_width, image_height) + ) + def getDataIndices(self, event): cv = self.model.currentView @@ -183,11 +308,18 @@ def getIDinfo(self, event): # check that the position is in the axes view if 0 <= yPos < self.model.currentView.v_res \ and 0 <= xPos and xPos < self.model.currentView.h_res: - id = self.model.ids[yPos][xPos] - temp = "{:g}".format(self.model.properties[yPos][xPos][0]) - density = "{:g}".format(self.model.properties[yPos][xPos][1]) + cell_id = int(self.model.cell_ids[yPos, xPos]) + mat_id = int(self.model.mat_ids[yPos, xPos]) + if cell_id < _OVERLAP: + id = cell_id + else: + id = cell_id if self.model.currentView.colorby == 'cell' else mat_id + instance = self.model.instances[yPos, xPos] + temp = "{:g}".format(self.model.property_data[yPos, xPos, 0]) + density = "{:g}".format(self.model.property_data[yPos, xPos, 1]) else: id = _NOT_FOUND + instance = _NOT_FOUND density = str(_NOT_FOUND) temp = str(_NOT_FOUND) @@ -207,7 +339,27 @@ def getIDinfo(self, event): properties = {'density': density, 'temperature': temp} - return id, properties, domain, domain_kind + return id, instance, properties, domain, domain_kind + + def _cellLabel(self, cell_id): + try: + name = self.model.activeView.cells[cell_id].name + except KeyError: + name = None + return f"{cell_id} ({name})" if name else str(cell_id) + + def _overlapInfo(self, id): + if id == _OVERLAP: + return "OVERLAP" + + overlap_idx = int(_OVERLAP - int(id) - 1) + if not 0 <= overlap_idx < len(self.model.overlap_info): + return "OVERLAP (unknown region)" + + universe, cell1, cell2 = self.model.overlap_info[overlap_idx] + label1 = self._cellLabel(cell1) + label2 = self._cellLabel(cell2) + return f"OVERLAP: Universe {universe}, Cells {label1} and {label2}" def mouseDoubleClickEvent(self, event): xCenter, yCenter = self.getPlotCoords(event.pos()) @@ -215,17 +367,18 @@ def mouseDoubleClickEvent(self, event): def mouseMoveEvent(self, event): cv = self.model.currentView + if self.ax is None or self.model.image is None: + return # Show Cursor position relative to plot in status bar xPlotPos, yPlotPos = self.getPlotCoords(event.pos()) # Show Cell/Material ID, Name in status bar - id, properties, domain, domain_kind = self.getIDinfo(event) + id, instance, properties, domain, domain_kind = self.getIDinfo(event) domainInfo = "" tallyInfo = "" if self.parent.underMouse(): - if domain_kind.lower() in _MODEL_PROPERTIES: line_val = float(properties[domain_kind.lower()]) line_val = max(line_val, 0.0) @@ -235,21 +388,29 @@ def mouseMoveEvent(self, event): temperature = properties['temperature'] density = properties['density'] + if instance != _NOT_FOUND and domain_kind == 'Cell': + instanceInfo = f" ({instance})" + else: + instanceInfo = "" if id == _VOID_REGION: domainInfo = ("VOID") - elif id == _OVERLAP: - domainInfo = ("OVERLAP") + elif id <= _OVERLAP: + domainInfo = self._overlapInfo(id) elif id != _NOT_FOUND and domain[id].name: - domainInfo = ("{} {}: \"{}\"\t Density: {} g/cc\t" - "Temperature: {} K".format(domain_kind, - id, - domain[id].name, - density, - temperature)) + domainInfo = ("{} {}{}: \"{}\"\t Density: {} g/cc\t" + "Temperature: {} K".format( + domain_kind, + id, + instanceInfo, + domain[id].name, + density, + temperature + )) elif id != _NOT_FOUND: - domainInfo = ("{} {}\t Density: {} g/cc\t" + domainInfo = ("{} {}{}\t Density: {} g/cc\t" "Temperature: {} K".format(domain_kind, id, + instanceInfo, density, temperature)) else: @@ -257,9 +418,10 @@ def mouseMoveEvent(self, event): if self.model.tally_data is not None: tid, value = self.getTallyInfo(event) - if value is not None and value != np.nan: + if value is not None and value is not ma.masked: self.updateTallyDataIndicatorValue(value) - tallyInfo = "Tally {} {}: {:.5E}".format(tid, cv.tallyValue, value) + tallyInfo = "Tally {} {}: {:.5E}".format( + tid, cv.tallyValue, float(value)) else: self.updateTallyDataIndicatorValue(0.0) else: @@ -311,12 +473,17 @@ def mouseReleaseEvent(self, event): self.rubber_band.hide() self.main_window.applyChanges() else: + plot_manager = self.main_window.plot_manager + if plot_manager.is_busy or plot_manager.has_pending: + return + if self.main_window.model.activeView != self.main_window.model.currentView: + return self.main_window.revertDockControls() def wheelEvent(self, event): - if event.delta() and event.modifiers() == QtCore.Qt.ShiftModifier: - numDegrees = event.delta() / 8 + if event.angleDelta() and event.modifiers() == QtCore.Qt.ShiftModifier: + numDegrees = event.angleDelta() / 8 if 24 < self.main_window.zoom + numDegrees < 5001: self.main_window.editZoom(self.main_window.zoom + numDegrees) @@ -325,10 +492,12 @@ def contextMenuEvent(self, event): self.menu.clear() - self.main_window.undoAction.setText('&Undo ({})'.format(len(self.model.previousViews))) - self.main_window.redoAction.setText('&Redo ({})'.format(len(self.model.subsequentViews))) + self.main_window.undoAction.setText( + '&Undo ({})'.format(len(self.model.previousViews))) + self.main_window.redoAction.setText( + '&Redo ({})'.format(len(self.model.subsequentViews))) - id, properties, domain, domain_kind = self.getIDinfo(event) + id, instance, properties, domain, domain_kind = self.getIDinfo(event) cv = self.model.currentView @@ -338,18 +507,28 @@ def contextMenuEvent(self, event): self.menu.addAction(self.main_window.redoAction) self.menu.addSeparator() - if int(id) not in (_NOT_FOUND, _OVERLAP) and \ - cv.colorby not in _MODEL_PROPERTIES: + if (int(id) not in (_NOT_FOUND, _VOID_REGION) and + int(id) > _OVERLAP and + cv.colorby not in _MODEL_PROPERTIES): # Domain ID if domain[id].name: - domainID = self.menu.addAction("{} {}: \"{}\"".format(domain_kind, id, domain[id].name)) + domainID = self.menu.addAction( + "{} {} Info: \"{}\"".format(domain_kind, id, domain[id].name)) else: - domainID = self.menu.addAction("{} {}".format(domain_kind, id)) + domainID = self.menu.addAction( + "{} {} Info".format(domain_kind, id)) + + # add connector to a new window of info here for material props + if domain_kind == 'Material': + mat_prop_connector = partial( + self.main_window.viewMaterialProps, id) + domainID.triggered.connect(mat_prop_connector) self.menu.addSeparator() - colorAction = self.menu.addAction('Edit {} Color...'.format(domain_kind)) + colorAction = self.menu.addAction( + 'Edit {} Color...'.format(domain_kind)) colorAction.setDisabled(cv.highlighting) colorAction.setToolTip('Edit {} color'.format(domain_kind)) colorAction.setStatusTip('Edit {} color'.format(domain_kind)) @@ -369,12 +548,15 @@ def contextMenuEvent(self, event): id=id) maskAction.toggled.connect(mask_connector) - highlightAction = self.menu.addAction('Highlight {}'.format(domain_kind)) + highlightAction = self.menu.addAction( + 'Highlight {}'.format(domain_kind)) highlightAction.setCheckable(True) highlightAction.setChecked(domain[id].highlight) highlightAction.setDisabled(not cv.highlighting) - highlightAction.setToolTip('Toggle {} highlight'.format(domain_kind)) - highlightAction.setStatusTip('Toggle {} highlight'.format(domain_kind)) + highlightAction.setToolTip( + 'Toggle {} highlight'.format(domain_kind)) + highlightAction.setStatusTip( + 'Toggle {} highlight'.format(domain_kind)) highlight_connector = partial(self.main_window.toggleDomainHighlight, kind=domain_kind, id=id) @@ -387,14 +569,16 @@ def contextMenuEvent(self, event): if cv.colorby not in _MODEL_PROPERTIES: self.menu.addSeparator() if int(id) == _NOT_FOUND: - bgColorAction = self.menu.addAction('Edit Background Color...') + bgColorAction = self.menu.addAction( + 'Edit Background Color...') bgColorAction.setToolTip('Edit background color') bgColorAction.setStatusTip('Edit plot background color') connector = partial(self.main_window.editBackgroundColor, apply=True) bgColorAction.triggered.connect(connector) - elif int(id) == _OVERLAP: - olapColorAction = self.menu.addAction('Edit Overlap Color...') + elif int(id) <= _OVERLAP: + olapColorAction = self.menu.addAction( + 'Edit Overlap Color...') olapColorAction.setToolTip('Edit overlap color') olapColorAction.setStatusTip('Edit plot overlap color') connector = partial(self.main_window.editOverlapColor, @@ -402,6 +586,7 @@ def contextMenuEvent(self, event): olapColorAction.triggered.connect(connector) self.menu.addSeparator() + self.menu.addAction(self.main_window.copyImageAction) self.menu.addAction(self.main_window.saveImageAction) self.menu.addAction(self.main_window.saveViewAction) self.menu.addAction(self.main_window.openAction) @@ -425,12 +610,13 @@ def contextMenuEvent(self, event): else: self.main_window.dockAction.setText('Show &Dock') - self.menu.exec_(event.globalPos()) + self.menu.exec(event.globalPos()) def generatePixmap(self, update=False): - self.model.generatePlot() - if update: - self.updatePixmap() + if self.frozen: + return + + self.main_window.requestPlotUpdate() def updatePixmap(self): @@ -439,7 +625,7 @@ def updatePixmap(self): cv = self.model.currentView # set figure bg color to match window - window_bg = self.parent.palette().color(QtGui.QPalette.Background) + window_bg = self.parent.palette().color(QtGui.QPalette.Window) self.figure.patch.set_facecolor(rgb_normalize(window_bg.getRgb())) # set data extents for automatic reporting of pointer location @@ -449,9 +635,8 @@ def updatePixmap(self): cv.origin[self.main_window.yBasis] - cv.height/2., cv.origin[self.main_window.yBasis] + cv.height/2.] - # make sure we have a domain image to load - if not hasattr(self.model, 'image'): - self.model.generatePlot() + if not hasattr(self.model, 'image') or self.model.image is None: + return ### DRAW DOMAIN IMAGE ### @@ -472,9 +657,10 @@ def updatePixmap(self): idx = 1 cmap_label = "Density (g/cc)" - norm = SymLogNorm(1E-10) if cv.color_scale_log[cv.colorby] else None + norm = SymLogNorm( + 1E-10) if cv.color_scale_log[cv.colorby] else None - data = self.model.properties[:, :, idx] + data = self.model.property_data[:, :, idx] self.image = self.figure.subplots().imshow(data, cmap=cmap, norm=norm, @@ -482,20 +668,21 @@ def updatePixmap(self): alpha=cv.domainAlpha) # add colorbar - self.colorbar = self.figure.colorbar(self.image, - anchor=(1.0, 0.0)) - self.colorbar.set_label(cmap_label, - rotation=-90, - labelpad=15) + self.property_colorbar = self.figure.colorbar(self.image, + anchor=(1.0, 0.0)) + self.property_colorbar.set_label(cmap_label, + rotation=-90, + labelpad=15) # draw line on colorbar - dl = self.colorbar.ax.dataLim.get_points() + dl = self.property_colorbar.ax.dataLim.get_points() self.data_indicator = mlines.Line2D(dl[:][0], [0.0, 0.0], linewidth=3., color='blue', clip_on=True) - self.colorbar.ax.add_line(self.data_indicator) - self.colorbar.ax.margins(0.0 ,0.0) + self.data_indicator.set_animated(True) + self.property_colorbar.ax.add_line(self.data_indicator) + self.property_colorbar.ax.margins(0.0, 0.0) self.updateDataIndicatorVisibility() self.updateColorMinMax(cv.colorby) @@ -515,7 +702,7 @@ def updatePixmap(self): # draw tally image if image_data is not None: - if not cv.tallyDataUserMinMax: + if cv.tallyDataMinMaxType != 'custom': cv.tallyDataMin = data_min cv.tallyDataMax = data_max else: @@ -525,6 +712,9 @@ def updatePixmap(self): # always mask out negative values image_mask = image_data < 0.0 + # mask out invalid values (NaN/Inf) + image_mask |= ~np.isfinite(image_data) + if cv.clipTallyData: image_mask |= image_data < data_min image_mask |= image_data > data_max @@ -535,6 +725,21 @@ def updatePixmap(self): # mask out invalid values image_data = np.ma.masked_where(image_mask, image_data) + # auto-rescale based on displayed (imshow) data + if cv.tallyDataMinMaxType == 'visible' and not cv.tallyContours: + displayed = image_data.compressed() + if displayed.size: + visible_min = float(displayed.min()) + visible_max = float(displayed.max()) + # Fall back to full data range if visible range is invalid for log scale + if cv.tallyDataLogScale and visible_min <= 0: + pass # keep the full data range + else: + data_min = visible_min + data_max = visible_max + cv.tallyDataMin = data_min + cv.tallyDataMax = data_max + if extents is None: extents = data_bounds @@ -543,6 +748,10 @@ def updatePixmap(self): norm = SymLogNorm(1E-30) if cv.tallyDataLogScale else None + cmap = cv.tallyDataColormap + if cv.tallyDataReverseCmap: + cmap += '_r' + if cv.tallyContours: # parse the levels line levels = self.parseContoursLine(cv.tallyContourLevels) @@ -550,14 +759,15 @@ def updatePixmap(self): origin='image', levels=levels, alpha=cv.tallyDataAlpha, - cmap=cv.tallyDataColormap, + cmap=cmap, norm=norm, - extent=extents) + extent=extents, + algorithm='serial') else: self.tally_image = self.ax.imshow(image_data, alpha=cv.tallyDataAlpha, - cmap=cv.tallyDataColormap, + cmap=cmap, norm=norm, extent=extents) # add colorbar @@ -577,6 +787,7 @@ def updatePixmap(self): linewidth=3., color='blue', clip_on=True) + self.tally_data_indicator.set_animated(True) self.tally_colorbar.ax.add_line(self.tally_data_indicator) self.tally_colorbar.ax.margins(0.0, 0.0) @@ -591,6 +802,11 @@ def updatePixmap(self): # annotate outlines self.add_outlines() + self.plotSourceSites() + + # annotate mesh boundaries + for mesh_id in cv.mesh_annotations: + self.annotate_mesh(mesh_id) # always make sure the data bounds are set correctly self.ax.set_xbound(data_bounds[0], data_bounds[1]) @@ -601,24 +817,81 @@ def updatePixmap(self): self.ax.dataLim.y1 = data_bounds[3] self.draw() + self._cache_colorbar_backgrounds() + self._blit_indicator(self.data_indicator, self.property_colorbar) + self._blit_indicator(self.tally_data_indicator, self.tally_colorbar) return "Done" + def current_view_data_bounds(self): + cv = self.model.currentView + return [cv.origin[self.main_window.xBasis] - cv.width/2., + cv.origin[self.main_window.xBasis] + cv.width/2., + cv.origin[self.main_window.yBasis] - cv.height/2., + cv.origin[self.main_window.yBasis] + cv.height/2.] + + def annotate_mesh(self, mesh_id): + mesh_bins = self.model.mesh_plot_bins(mesh_id) + + data_bounds = self.current_view_data_bounds() + self.mesh_contours = self.ax.contour( + mesh_bins, + origin='upper', + colors='k', + linestyles='solid', + levels=np.unique(mesh_bins), + extent=data_bounds, + algorithm='serial' + ) + + def plotSourceSites(self): + if not self.model.sourceSitesVisible or self.model.sourceSites is None: + return + + cv = self.model.currentView + basis = cv.view_params.basis + + h_idx = 'xyz'.index(basis[0]) + v_idx = 'xyz'.index(basis[1]) + + sites = self.model.sourceSites + + slice_ax = cv.view_params.slice_axis + + if self.model.sourceSitesApplyTolerance: + sites_to_plot = sites[np.abs(sites[:, slice_ax] - cv.origin[slice_ax]) <= self.model.sourceSitesTolerance] + else: + sites_to_plot = sites + + self.ax.scatter([s[h_idx] for s in sites_to_plot], + [s[v_idx] for s in sites_to_plot], + marker='o', + color=rgb_normalize(self.model.sourceSitesColor)) + def add_outlines(self): cv = self.model.currentView # draw outlines as isocontours - if cv.outlines: + if cv.outlinesCell or cv.outlinesMat: # set data extents for automatic reporting of pointer location - data_bounds = [cv.origin[self.main_window.xBasis] - cv.width/2., - cv.origin[self.main_window.xBasis] + cv.width/2., - cv.origin[self.main_window.yBasis] - cv.height/2., - cv.origin[self.main_window.yBasis] + cv.height/2.] - levels = np.unique(self.model.ids) - self.contours = self.ax.contour(self.model.ids, - origin='upper', - colors='k', - linestyles='solid', - levels=levels, - extent=data_bounds) + data_bounds = self.current_view_data_bounds() + if cv.outlinesCell: + levels = np.unique(self.model.cell_ids) + self.ax.contour(self.model.cell_ids, + origin='upper', + colors='k', + linestyles='solid', + levels=levels, + extent=data_bounds, + algorithm='serial') + if cv.outlinesMat: + levels = np.unique(self.model.mat_ids) + self.ax.contour(self.model.mat_ids, + origin='upper', + colors='k', + linestyles='solid', + levels=levels, + extent=data_bounds, + algorithm='serial') + @staticmethod def parseContoursLine(line): @@ -632,21 +905,63 @@ def parseContoursLine(line): def updateColorbarScale(self): self.updatePixmap() + def _cache_colorbar_backgrounds(self): + """Cache colorbar backgrounds for fast indicator blitting.""" + self._property_colorbar_bg = None + self._tally_colorbar_bg = None + + if self.property_colorbar and self.data_indicator: + self._property_colorbar_bg = self.copy_from_bbox( + self.property_colorbar.ax.bbox) + + if self.tally_colorbar and self.tally_data_indicator: + self._tally_colorbar_bg = self.copy_from_bbox( + self.tally_colorbar.ax.bbox) + + def _blit_indicator(self, indicator, colorbar): + """Blit a single indicator line onto its colorbar if possible.""" + if colorbar is None or indicator is None: + return False + + if not indicator.get_visible(): + return False + + if colorbar is self.property_colorbar: + background = self._property_colorbar_bg + else: + background = self._tally_colorbar_bg + + if background is None: + return False + + self.restore_region(background) + colorbar.ax.draw_artist(indicator) + self.blit(colorbar.ax.bbox) + return True + def updateTallyDataIndicatorValue(self, y_val): cv = self.model.currentView if not cv.tallyDataVisible or not cv.tallyDataIndicator: - return + return + + if self.tally_data_indicator is not None and self.tally_image is not None: + # If indicator value hasn't changed, skip update + if self._last_tally_indicator_value == y_val: + return + self._last_tally_indicator_value = y_val - if self.tally_data_indicator is not None: data = self.tally_data_indicator.get_data() - # use norm to get axis value if log scale - if cv.tallyDataLogScale: - y_val = self.tally_image.norm(y_val) + # Colorbar axes use data coordinates; normalization is only needed + # when mapping the value through the colormap. self.tally_data_indicator.set_data([data[0], [y_val, y_val]]) - dl_color = invert_rgb(self.tally_image.get_cmap()(y_val), True) + normalized_value = self.tally_image.norm(y_val) + dl_color = invert_rgb( + self.tally_image.get_cmap()(normalized_value), True) self.tally_data_indicator.set_c(dl_color) - self.draw() + + if not self._blit_indicator(self.tally_data_indicator, self.tally_colorbar): + self.draw_idle() def updateDataIndicatorValue(self, y_val): cv = self.model.currentView @@ -655,38 +970,52 @@ def updateDataIndicatorValue(self, y_val): not cv.data_indicator_enabled[cv.colorby]: return - if self.data_indicator: + if self.data_indicator and self.image is not None: + # If indicator value hasn't changed, skip update + if self._last_data_indicator_value == y_val: + return + self._last_data_indicator_value = y_val + data = self.data_indicator.get_data() - # use norm to get axis value if log scale - if cv.color_scale_log[cv.colorby]: - y_val = self.image.norm(y_val) + # Colorbar axes use data coordinates; normalization is only needed + # when mapping the value through the colormap. self.data_indicator.set_data([data[0], [y_val, y_val]]) - dl_color = invert_rgb(self.image.get_cmap()(y_val), True) + normalized_value = self.image.norm(y_val) + dl_color = invert_rgb( + self.image.get_cmap()(normalized_value), True) self.data_indicator.set_c(dl_color) - self.draw() + + if not self._blit_indicator(self.data_indicator, self.property_colorbar): + self.draw_idle() def updateDataIndicatorVisibility(self): cv = self.model.currentView if self.data_indicator and cv.colorby in _MODEL_PROPERTIES: val = cv.data_indicator_enabled[cv.colorby] self.data_indicator.set_visible(val) - self.draw() + if not self._blit_indicator(self.data_indicator, self.property_colorbar): + self.draw_idle() def updateColorMap(self, colormap_name, property_type): - if self.colorbar and property_type == self.model.activeView.colorby: + if self.property_colorbar and property_type == self.model.activeView.colorby: self.image.set_cmap(colormap_name) - self.colorbar.draw_all() + self.figure.draw_without_rendering() self.draw() + self._cache_colorbar_backgrounds() + self._blit_indicator(self.data_indicator, self.property_colorbar) def updateColorMinMax(self, property_type): av = self.model.activeView - if self.colorbar and property_type == av.colorby: + if self.property_colorbar and property_type == av.colorby: clim = av.getColorLimits(property_type) - self.colorbar.mappable.set_clim(*clim) + self.property_colorbar.mappable.set_clim(*clim) self.data_indicator.set_data(clim[:2], (0.0, 0.0)) - self.colorbar.draw_all() + self.figure.draw_without_rendering() self.draw() + self._cache_colorbar_backgrounds() + self._blit_indicator(self.data_indicator, self.property_colorbar) + class ColorDialog(QDialog): @@ -714,7 +1043,8 @@ def createDialogLayout(self): self.tab_bar = QTabWidget() self.tab_bar.setMaximumHeight(800) - self.tab_bar.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) + self.tab_bar.setSizePolicy( + QSizePolicy.Expanding, QSizePolicy.Expanding) self.tab_bar.addTab(self.generalTab, 'General') self.tab_bar.addTab(self.tabs['cell'], 'Cells') self.tab_bar.addTab(self.tabs['material'], 'Materials') @@ -774,13 +1104,15 @@ def createGeneralTab(self): self.colorbyBox.addItem("cell") self.colorbyBox.addItem("temperature") self.colorbyBox.addItem("density") - self.colorbyBox.currentTextChanged[str].connect(main_window.editColorBy) + self.colorbyBox.currentTextChanged[str].connect( + main_window.editColorBy) self.universeLevelBox = QComboBox(self) self.universeLevelBox.addItem('all') for i in range(self.model.max_universe_levels): self.universeLevelBox.addItem(str(i)) - self.universeLevelBox.currentTextChanged[str].connect(main_window.editUniverseLevel) + self.universeLevelBox.currentTextChanged[str].connect( + main_window.editUniverseLevel) # Overlap plotting self.overlapCheck = QCheckBox('', self) @@ -879,7 +1211,8 @@ def createPropertyTab(self, property_kind): propertyTab.maxBox.valueChanged.connect(connector3) propertyTab.colormapBox = QComboBox(self) - cmaps = sorted(m for m in mcolormaps.datad if not m.endswith("_r")) + cmaps = sorted(m for m in plt.colormaps() + if not m.endswith("_r")) for cmap in cmaps: propertyTab.colormapBox.addItem(cmap) @@ -927,8 +1260,8 @@ def updateColorMaps(self): cmaps = self.model.activeView.colormaps for key, val in cmaps.items(): idx = self.tabs[key].colormapBox.findText( - val, - QtCore.Qt.MatchFixedString) + val, + QtCore.Qt.MatchFixedString) if idx >= 0: self.tabs[key].colormapBox.setCurrentIndex(idx) diff --git a/openmc_plotter/plotmodel.py b/openmc_plotter/plotmodel.py index 11e2e19..f58f768 100644 --- a/openmc_plotter/plotmodel.py +++ b/openmc_plotter/plotmodel.py @@ -1,22 +1,27 @@ +from __future__ import annotations +from ast import literal_eval from collections import defaultdict import copy +from ctypes import c_int32, c_char_p +from dataclasses import dataclass +import hashlib import itertools -import threading -from ast import literal_eval +import pickle +from typing import Literal, Tuple, Optional, Dict -from PySide2.QtWidgets import QItemDelegate, QColorDialog, QLineEdit, QMessageBox -from PySide2.QtCore import QAbstractTableModel, QModelIndex, Qt, QSize, QEvent -from PySide2.QtGui import QColor +from PySide6.QtWidgets import QItemDelegate, QColorDialog, QLineEdit, QMessageBox +from PySide6.QtCore import (QAbstractTableModel, QModelIndex, Qt, QSize, QEvent, + QObject, Signal, Slot, QThread, QEventLoop, QTimer) +from PySide6.QtGui import QColor import openmc import openmc.lib import numpy as np +from . import __version__ from .statepointmodel import StatePointModel -from .plot_colors import random_rgb, reset_seed - -ID, NAME, COLOR, COLORLABEL, MASK, HIGHLIGHT = tuple(range(0, 6)) +from .plot_colors import random_rgb -__VERSION__ = "0.2.1" +ID, NAME, COLOR, COLORLABEL, MASK, HIGHLIGHT = range(6) _VOID_REGION = -1 _NOT_FOUND = -2 @@ -25,72 +30,285 @@ _MODEL_PROPERTIES = ('temperature', 'density') _PROPERTY_INDICES = {'temperature': 0, 'density': 1} -_REACTION_UNITS = 'Reactions per Source Particle' -_FLUX_UNITS = 'Particle-cm per Source Particle' -_PRODUCTION_UNITS = 'Particles Produced per Source Particle' -_ENERGY_UNITS = 'eV per Source Particle' +_REACTION_UNITS = 'reactions/source' +_PRODUCTION_UNITS = 'particles/source' +_ENERGY_UNITS = 'eV/source' + +_REACTION_UNITS_VOL = 'reactions/cm³/source' +_PRODUCTION_UNITS_VOL = 'particles/cm³/source' +_ENERGY_UNITS_VOL = 'eV/cm³/source' + _SPATIAL_FILTERS = (openmc.UniverseFilter, openmc.MaterialFilter, openmc.CellFilter, - openmc.MeshFilter) + openmc.DistribcellFilter, + openmc.CellInstanceFilter, + openmc.MeshFilter, + openmc.MeshMaterialFilter) _PRODUCTIONS = ('delayed-nu-fission', 'prompt-nu-fission', 'nu-fission', 'nu-scatter', 'H1-production', 'H2-production', 'H3-production', 'He3-production', 'He4-production') +_ENERGY_SCORES = {'heating', 'heating-local', 'kappa-fission', + 'fission-q-prompt', 'fission-q-recoverable', + 'damage-energy'} _SCORE_UNITS = {p: _PRODUCTION_UNITS for p in _PRODUCTIONS} -_SCORE_UNITS['flux'] = 'Particle-cm/Particle' -_SCORE_UNITS['current'] = 'Particles per source Particle' -_SCORE_UNITS['events'] = 'Events per Source Particle' -_SCORE_UNITS['inverse-velocity'] = 'Particle-seconds per Source Particle' -_SCORE_UNITS['heating'] = _ENERGY_UNITS -_SCORE_UNITS['heating-local'] = _ENERGY_UNITS -_SCORE_UNITS['kappa-fission'] = _ENERGY_UNITS -_SCORE_UNITS['fission-q-prompt'] = _ENERGY_UNITS -_SCORE_UNITS['fission-q-recoverable'] = _ENERGY_UNITS -_SCORE_UNITS['decay-rate'] = 'Seconds^-1' -_SCORE_UNITS['damage-energy'] = _ENERGY_UNITS +_SCORE_UNITS['flux'] = 'particle-cm/source' +_SCORE_UNITS['current'] = 'particle/source' +_SCORE_UNITS['events'] = 'events/source' +_SCORE_UNITS['inverse-velocity'] = 'particle-s/source' +_SCORE_UNITS['decay-rate'] = 'particle/s/source' +_SCORE_UNITS.update({s: _ENERGY_UNITS for s in _ENERGY_SCORES}) + +_SCORE_UNITS_VOL = {p: _PRODUCTION_UNITS_VOL for p in _PRODUCTIONS} +_SCORE_UNITS_VOL['flux'] = 'particle/cm²/source' +_SCORE_UNITS_VOL['current'] = 'particle/cm³/source' +_SCORE_UNITS_VOL['events'] = 'events/cm³/source' +_SCORE_UNITS_VOL['inverse-velocity'] = 'particle-s/cm³/source' +_SCORE_UNITS_VOL['decay-rate'] = 'particle/s/cm³/source' +_SCORE_UNITS.update({s: _ENERGY_UNITS_VOL for s in _ENERGY_SCORES}) + _TALLY_VALUES = {'Mean': 'mean', 'Std. Dev.': 'std_dev', 'Rel. Error': 'rel_err'} -class PlotModel(): - """ Geometry and plot settings for OpenMC Plot Explorer model +TallyValueType = Literal['mean', 'std_dev', 'rel_err'] + + +def hash_file(path): + # return the md5 hash of a file + h = hashlib.md5() + with path.open('rb') as file: + chunk = 0 + while chunk != b'': + # read 32768 bytes at a time + chunk = file.read(32768) + h.update(chunk) + return h.hexdigest() + + +def hash_model(model_path): + """Get hash values for materials.xml and geometry.xml (or model.xml)""" + if model_path.is_file(): + mat_xml_hash = hash_file(model_path) + geom_xml_hash = "" + elif (model_path / 'model.xml').exists(): + mat_xml_hash = hash_file(model_path / 'model.xml') + geom_xml_hash = "" + else: + mat_xml_hash = hash_file(model_path / 'materials.xml') + geom_xml_hash = hash_file(model_path / 'geometry.xml') + return mat_xml_hash, geom_xml_hash + + +@dataclass(frozen=True) +class PlotRequest: + view_snapshot: "PlotView" + view_params: Dict[str, object] + + +@dataclass(frozen=True) +class PlotWorkItem: + view_params: Dict[str, object] + + +class PlotWorker(QObject): + finished = Signal(object, object, object) + error = Signal(str) + + @Slot(object) + def generate_maps(self, work_item: PlotWorkItem): + try: + params = work_item.view_params + + # Determine if we need filter bins for MeshMaterialFilter tally + filter_cpp = None + if params.get("filter_id") is not None: + filter_cpp = openmc.lib.filters[params["filter_id"]] + + # Get geometry and property data from OpenMC library + geom_data, property_data = openmc.lib.slice_data( + origin=params["origin"], + width=(params["width"], params["height"]), + basis=params["basis"], + pixels=(params["h_res"], params["v_res"]), + show_overlaps=params["color_overlaps"], + level=params["level"], + filter=filter_cpp, + ) + + self.finished.emit(work_item.view_params, geom_data, property_data) + except Exception as exc: + self.error.emit(str(exc)) + + +class PlotManager(QObject): + plot_started = Signal() + plot_queued = Signal() + plot_finished = Signal(object, object, object, object) + plot_error = Signal(str) + plot_idle = Signal() + work_requested = Signal(object) - Attributes - ---------- - geom : openmc.Geometry instance - OpenMC Geometry of the model - modelCells : collections.OrderedDict - Dictionary mapping cell IDs to openmc.Cell instances - modelMaterials : collections.OrderedDict - Dictionary mapping material IDs to openmc.Material instances - ids : NumPy int array (v_res, h_res, 1) - Mapping of plot coordinates to cell/material ID by pixel - image : NumPy int array (v_res, h_res, 3) - The current RGB image data - statepoint : StatePointModel - Simulation data model used to display tally results - applied_filters : tuple of ints - IDs of the applied filters for the displayed tally - previousViews : list of PlotView instances - List of previously created plot view settings used to undo - changes made in plot explorer - subsequentViews : list of PlotView instances - List of undone plot view settings used to redo changes made - in plot explorer - defaultView : PlotView instance - Default settings for given geometry - currentView : PlotView instance - Currently displayed plot settings in plot explorer - activeView : PlotView instance - Active state of settings in plot explorer, which may or may not - have unapplied changes + def __init__(self): + super().__init__() + self._thread = QThread() + self._worker = PlotWorker() + self._worker.moveToThread(self._thread) + self._thread.finished.connect(self._worker.deleteLater) + self.work_requested.connect(self._worker.generate_maps) + self._worker.finished.connect(self._on_worker_finished) + self._worker.error.connect(self._on_worker_error) + self._thread.start() + + self._pending_request = None + self._in_flight_request = None + self._latest_view_params = None + + @property + def latest_view_params(self): + return self._latest_view_params + + @property + def is_busy(self): + return self._in_flight_request is not None + + @property + def has_pending(self): + return self._pending_request is not None + + def enqueue(self, view_snapshot, view_params): + request = PlotRequest(view_snapshot, view_params) + self._latest_view_params = view_params + if self._in_flight_request is None: + self._pending_request = request + self._start_next() + return + self._pending_request = request + self.plot_queued.emit() + + def set_latest_view_params(self, view_params): + self._latest_view_params = view_params + + def clear_pending(self): + self._pending_request = None + + def wait_for_idle(self, timeout_ms: Optional[int] = None): + if not self.is_busy and not self.has_pending: + return True + loop = QEventLoop() + timer = None + if timeout_ms is not None: + timer = QTimer() + timer.setSingleShot(True) + timer.timeout.connect(loop.quit) + def on_idle(): + loop.quit() + self.plot_idle.connect(on_idle) + if timer is not None: + timer.start(timeout_ms) + loop.exec() + self.plot_idle.disconnect(on_idle) + if timer is not None: + timer.stop() + return not self.is_busy and not self.has_pending + + def shutdown(self): + self._pending_request = None + self._in_flight_request = None + if self._thread.isRunning(): + self._thread.quit() + self._thread.wait() + + def _start_next(self): + if self._pending_request is None: + return + self._in_flight_request = self._pending_request + self._pending_request = None + self.plot_started.emit() + work_item = PlotWorkItem(self._in_flight_request.view_params) + self.work_requested.emit(work_item) + + @Slot(object, object, object) + def _on_worker_finished(self, view_params, geom_data, property_data): + request = self._in_flight_request + self._in_flight_request = None + if request is not None: + self.plot_finished.emit(request.view_snapshot, + view_params, geom_data, property_data) + if self._pending_request is not None: + self._start_next() + else: + self.plot_idle.emit() + + @Slot(str) + def _on_worker_error(self, message): + self._in_flight_request = None + self.plot_error.emit(message) + if self._pending_request is not None: + self._start_next() + else: + self.plot_idle.emit() + +class PlotModel: + """Geometry and plot settings for OpenMC Plot Explorer model + + Parameters + ---------- + use_settings_pkl : bool + If True, use plot_settings.pkl file to reload settings + model_path : pathlib.Path + Path to model XML file or directory + default_res : int + Default resolution as the number of pixels in each direction + + Attributes + ---------- + geom : openmc.Geometry + OpenMC Geometry of the model + modelCells : collections.OrderedDict + Dictionary mapping cell IDs to openmc.Cell instances + modelMaterials : collections.OrderedDict + Dictionary mapping material IDs to openmc.Material instances + ids : NumPy int array (v_res, h_res, 1) + Mapping of plot coordinates to cell/material ID by pixel + geom_data : NumPy int32 array (v_res, h_res, 3) or (v_res, h_res, 4) + Geometry data with cell IDs, instances, material IDs, and optionally filter bins + property_data : Numpy float array (v_res, h_res, 2) + Property data with cell temperatures and material densities + image : NumPy int array (v_res, h_res, 3) + The current RGB image data + statepoint : StatePointModel + Simulation data model used to display tally results + applied_filters : tuple of ints + IDs of the applied filters for the displayed tally + previousViews : list of PlotView instances + List of previously created plot view settings used to undo + changes made in plot explorer + subsequentViews : list of PlotView instances + List of undone plot view settings used to redo changes made + in plot explorer + sourceSitesTolerance : float + Tolerance for source site plotting (default 0.1 cm) + sourceSitesColor : tuple of 3 int + RGB color for source site plotting (default blue) + sourceSitesVisible : bool + Whether to plot source sites (default True) + sourceSites : Source sites to plot + Set of source locations to plot + defaultView : PlotView + Default settings for given geometry + currentView : PlotView + Currently displayed plot settings in plot explorer + activeView : PlotView + Active state of settings in plot explorer, which may or may not + have unapplied changes """ - def __init__(self): + def __init__(self, use_settings_pkl, model_path, default_res): """ Initialize PlotModel class attributes """ # Retrieve OpenMC Cells/Materials @@ -101,7 +319,15 @@ def __init__(self): # Cell/Material ID by coordinates self.ids = None - self.version = __VERSION__ + # Return values from slice_data + self.geom_data = None + self.property_data = None + self.map_view_params = None + + # Map to be populated by overlap functions + self.overlap_info = None + + self.version = __version__ # default statepoint value self._statepoint = None @@ -110,15 +336,78 @@ def __init__(self): self.appliedScores = () self.appliedNuclides = () - # reset random number seed for consistent - # coloring when reloading a model - reset_seed() - self.previousViews = [] self.subsequentViews = [] - self.defaultView = self.getDefaultView() - self.currentView = copy.deepcopy(self.defaultView) - self.activeView = copy.deepcopy(self.defaultView) + + self.defaultView = self.getDefaultView(default_res) + + # Source site defaults + self.sourceSitesApplyTolerance = False + self.sourceSitesTolerance = 0.1 # cm + self.sourceSitesColor = (0, 0, 255) + self.sourceSitesVisible = True + self.sourceSites = None + + if model_path.is_file(): + settings_pkl = model_path.with_name('plot_settings.pkl') + else: + settings_pkl = model_path / 'plot_settings.pkl' + + if use_settings_pkl and settings_pkl.is_file(): + with settings_pkl.open('rb') as file: + try: + data = pickle.load(file) + except AttributeError: + msg_box = QMessageBox() + msg = "WARNING: previous plot settings are in an incompatible format. " +\ + "They will be ignored." + msg_box.setText(msg) + msg_box.setIcon(QMessageBox.Warning) + msg_box.setStandardButtons(QMessageBox.Ok) + msg_box.exec() + self.currentView = copy.deepcopy(self.defaultView) + + else: + restore_domains = False + + # check GUI version + if data['version'] != self.version: + print("WARNING: previous plot settings are for a different " + "version of the GUI. They will be ignored.") + wrn_msg = "Existing version: {}, Current GUI version: {}" + print(wrn_msg.format(data['version'], self.version)) + view = None + else: + view = data['currentView'] + + # get materials.xml and geometry.xml hashes to + # restore additional settings if possible + mat_xml_hash, geom_xml_hash = hash_model(model_path) + if mat_xml_hash == data['mat_xml_hash'] and \ + geom_xml_hash == data['geom_xml_hash']: + restore_domains = True + + # restore statepoint file + try: + self.statepoint = data['statepoint'] + except OSError: + msg_box = QMessageBox() + msg = "Could not open statepoint file: \n\n {} \n" + msg_box.setText(msg.format(self.model.statepoint.filename)) + msg_box.setIcon(QMessageBox.Warning) + msg_box.setStandardButtons(QMessageBox.Ok) + msg_box.exec() + self.statepoint = None + + self.currentView = PlotView(restore_view=view, + restore_domains=restore_domains, + default_res=default_res) + + else: + self.currentView = copy.deepcopy(self.defaultView) + + self.activeView = copy.deepcopy(self.currentView) + self.plot_manager = PlotManager() def openStatePoint(self, filename): self.statepoint = StatePointModel(filename, open_file=True) @@ -141,7 +430,7 @@ def statepoint(self, statepoint): if self._statepoint and not self._statepoint.is_open: self._statepoint.open() - def getDefaultView(self): + def getDefaultView(self, default_res): """ Generates default PlotView instance for OpenMC geometry Centers plot view origin in every dimension if possible. Defaults @@ -149,6 +438,11 @@ def getDefaultView(self): geometry. Defaults to (0, 0, 0) origin with width and heigth of 25 if geometry bounding box cannot be generated. + Parameters + ---------- + default_res : int + Default resolution as the number of pixels in each direction + Returns ------- default : PlotView instance @@ -171,7 +465,8 @@ def getDefaultView(self): else: zcenter = 0.00 - default = PlotView([xcenter, ycenter, zcenter], width, height) + default = PlotView([xcenter, ycenter, zcenter], width, height, + default_res=default_res) return default def resetColors(self): @@ -179,52 +474,106 @@ def resetColors(self): self.activeView.cells = self.defaultView.cells self.activeView.materials = self.defaultView.materials - def generatePlot(self): - """ Spawn thread from which to generate new plot image """ + def view_params_payload(self, view: "PlotView"): + vp = view.view_params + return { + "origin": tuple(vp.origin), + "width": float(vp.width), + "height": float(vp.height), + "h_res": int(vp.h_res), + "v_res": int(vp.v_res), + "basis": str(vp.basis), + "level": int(vp.level), + "color_overlaps": bool(vp.color_overlaps), + "filter_id": self.get_active_mesh_material_filter_id(view), + } + + def get_active_mesh_material_filter_id(self, view: "PlotView") -> Optional[int]: + """Return the filter ID if displaying a MeshMaterialFilter tally, else None.""" + if self._statepoint is None: + return None + if not view.tallyDataVisible or view.selectedTally is None: + return None - t = threading.Thread(target=self.makePlot) - t.start() - t.join() + tally = self._statepoint.tallies[view.selectedTally] + if tally.contains_filter(openmc.MeshMaterialFilter): + filter = tally.find_filter(openmc.MeshMaterialFilter) + return filter.id + return None - def makePlot(self): - """ Generate new plot image from active view settings + def can_reuse_maps(self, view: "PlotView"): + if self.geom_data is None or self.property_data is None: + return False + return self.map_view_params == self.view_params_payload(view) - Creates corresponding .xml files from user-chosen settings. - Runs OpenMC in plot mode to generate new plot image. - """ + def makePlot(self, view: Optional["PlotView"] = None, + geom_data=None, property_data=None): + """Generate new plot image from active view settings""" + if view is None: + view = self.activeView + # update/call maps under 2 circumstances + # 1. this is the intial plot (geom_data/property_data are None) + # 2. The active (desired) view differs from the current view parameters + if geom_data is None or property_data is None: + if (self.currentView.view_params != view.view_params) or \ + (self.geom_data is None) or (self.property_data is None): + # Determine if we need filter bins for MeshMaterialFilter tally + filter_cpp = None + filter_id = self.get_active_mesh_material_filter_id(view) + if filter_id is not None: + filter_cpp = openmc.lib.filters[filter_id] + + self.geom_data, self.property_data = openmc.lib.slice_data( + origin=view.origin, + width=(view.width, view.height), + basis=view.basis, + pixels=(view.h_res, view.v_res), + show_overlaps=view.color_overlaps, + level=view.level, + filter=filter_cpp, + ) + self.map_view_params = self.view_params_payload(view) - cv = self.currentView = copy.deepcopy(self.activeView) - ids = openmc.lib.id_map(cv) - props = openmc.lib.property_map(cv) + else: + self.geom_data = geom_data + self.property_data = property_data + self.map_view_params = self.view_params_payload(view) - self.cell_ids = ids[:, :, 0] - self.mat_ids = ids[:, :, 1] + # Get cell overlap information + self.overlap_info = openmc.lib.slice_data_overlap_info() + + # update current view + cv = self.currentView = copy.deepcopy(view) # set model ids based on domain if cv.colorby == 'cell': - self.ids = self.cell_ids + self.ids = self.cell_ids.copy() domain = cv.cells source = self.modelCells else: - self.ids = self.mat_ids + self.ids = self.mat_ids.copy() domain = cv.materials source = self.modelMaterials + # Normalizes so that domain only sees -3, but + # overlap indices are still available in cell_ids + self.ids[self.ids < _OVERLAP] = _OVERLAP # new line + # generate colors if not present for cell_id, cell in cv.cells.items(): if cell.color is None: - cell.color = random_rgb() + cv.cells.set_color(cell_id, random_rgb()) for mat_id, mat in cv.materials.items(): if mat.color is None: - mat.color = random_rgb() + cv.material.set_color(mat_id, random_rgb()) # construct image data domain[_OVERLAP] = DomainView(_OVERLAP, "Overlap", cv.overlap_color) domain[_NOT_FOUND] = DomainView(_NOT_FOUND, "Not Found", cv.domainBackground) u, inv = np.unique(self.ids, return_inverse=True) image = np.array([domain[id].color for id in u])[inv] - image.shape = (cv.v_res, cv.h_res, 3) + image = image.reshape(cv.v_res, cv.h_res, 3) if cv.masking: for id, dom in domain.items(): @@ -238,24 +587,25 @@ def makePlot(self): # set model image self.image = image - # set model properties - self.properties = props + # tally data self.tally_data = None - self.properties[self.properties < 0.0] = np.nan + self.property_data[self.property_data < 0.0] = np.nan - self.temperatures = self.properties[..., _PROPERTY_INDICES['temperature']] - self.densities = self.properties[..., _PROPERTY_INDICES['density']] + self.temperatures = self.property_data[..., _PROPERTY_INDICES['temperature']] + self.densities = self.property_data[..., _PROPERTY_INDICES['density']] minmax = {} for prop in _MODEL_PROPERTIES: idx = _PROPERTY_INDICES[prop] - prop_data = self.properties[:, :, idx] + prop_data = self.property_data[:, :, idx] minmax[prop] = (np.min(np.nan_to_num(prop_data)), np.max(np.nan_to_num(prop_data))) - self.activeView.data_minmax = minmax + cv.data_minmax = minmax + if self.activeView.view_params == cv.view_params: + self.activeView.data_minmax = minmax def undo(self): """ Revert to previous PlotView instance. Re-generate plot image """ @@ -263,7 +613,6 @@ def undo(self): if self.previousViews: self.subsequentViews.append(copy.deepcopy(self.currentView)) self.activeView = self.previousViews.pop() - self.generatePlot() def redo(self): """ Revert to subsequent PlotView instance. Re-generate plot image """ @@ -271,13 +620,34 @@ def redo(self): if self.subsequentViews: self.storeCurrent() self.activeView = self.subsequentViews.pop() - self.generatePlot() + + def getExternalSourceSites(self, n=100): + """Plot source sites from a source file + """ + if n == 0: + self.source_sites = None + return + sites = openmc.lib.sample_external_source(n) + self.sourceSites = np.array([s.r for s in sites[:n]], dtype=float) def storeCurrent(self): """ Add current view to previousViews list """ self.previousViews.append(copy.deepcopy(self.currentView)) - def create_tally_image(self, view=None): + def create_tally_image(self, view: Optional[PlotView] = None): + """ + Parameters + ---------- + view : PlotView + View used to set bounds of the tally data + + Returns + ------- + tuple + image data (numpy.ndarray), data extents (optional), + data_min_value (float), data_max_value (float), + data label (str) + """ if view is None: view = self.currentView @@ -309,33 +679,34 @@ def create_tally_image(self, view=None): msg_box.setText(msg) msg_box.setIcon(QMessageBox.Information) msg_box.setStandardButtons(QMessageBox.Ok) - msg_box.exec_() + msg_box.exec() return (None, None, None, None, None) units_out = list(units)[0] + contains_distribcell = tally.contains_filter(openmc.DistribcellFilter) + contains_cellinstance = tally.contains_filter(openmc.CellInstanceFilter) + if tally.contains_filter(openmc.MeshFilter): + # Check for volume normalization in order to change units + if view.tallyVolumeNorm: + units_out = _SCORE_UNITS_VOL.get(scores[0], _REACTION_UNITS_VOL) + if tally_value == 'rel_err': - # get both the std. dev. data and mean data - # to create the relative error data - mean_data = self._create_tally_mesh_image(tally, - 'mean', - scores, - nuclides, - view) - std_dev_data = self._create_tally_mesh_image(tally, - 'std_dev', - scores, - nuclides, - view) - image_data = 100 * np.divide(std_dev_data[0], - mean_data[0], - out=np.zeros_like(mean_data[0]), - where=mean_data != 0) - extents = mean_data[1] - data_min = np.min(image_data) - data_max = np.max(image_data) - return image_data, extents, data_min, data_max, '% error' + # Get both the std. dev. data and mean data to create the + # relative error data + mean_data = self._create_tally_mesh_image( + tally, 'mean', scores, nuclides, view)[0] + std_dev_data = self._create_tally_mesh_image( + tally, 'std_dev', scores, nuclides, view)[0] + with np.errstate(divide='ignore', invalid='ignore'): + image_data = 100.0 * std_dev_data / mean_data + if np.isnan(image_data).all(): + data_min, data_max = 0., 1. + else: + data_min = np.nanmin(image_data) + data_max = np.nanmax(image_data) + return image_data, None, data_min, data_max, '% error' else: image = self._create_tally_mesh_image(tally, @@ -344,6 +715,31 @@ def create_tally_image(self, view=None): nuclides, view) return image + (units_out,) + + elif tally.contains_filter(openmc.MeshMaterialFilter): + image = self._create_tally_filter_image( + tally, tally_value, openmc.MeshMaterialFilter, scores, nuclides, view) + return image + (units_out,) + + + elif contains_distribcell or contains_cellinstance: + if tally_value == 'rel_err': + mean_data = self._create_distribcell_image( + tally, 'mean', scores, nuclides, contains_cellinstance) + std_dev_data = self._create_distribcell_image( + tally, 'std_dev', scores, nuclides) + image_data = 100 * np.divide( + std_dev_data[0], mean_data[0], + out=np.zeros_like(mean_data[0]), + where=mean_data != 0 + ) + data_min = np.min(image_data) + data_max = np.max(image_data) + return image_data, None, data_min, data_max, '% error' + else: + image = self._create_distribcell_image( + tally, tally_value, scores, nuclides, contains_cellinstance) + return image + (units_out,) else: # same as above, get the std. dev. data # and mean date to produce the relative error data @@ -351,13 +747,11 @@ def create_tally_image(self, view=None): mean_data = self._create_tally_domain_image(tally, 'mean', scores, - nuclides, - view) + nuclides) std_dev_data = self._create_tally_domain_image(tally, 'std_dev', scores, - nuclides, - view) + nuclides) image_data = 100 * np.divide(std_dev_data[0], mean_data[0], out=np.zeros_like(mean_data[0]), @@ -375,8 +769,7 @@ def create_tally_image(self, view=None): image = self._create_tally_domain_image(tally, tally_value, scores, - nuclides, - view) + nuclides) return image + (units_out,) def _create_tally_domain_image(self, tally, tally_value, scores, nuclides, view=None): @@ -411,7 +804,7 @@ def _do_op(array, tally_value, ax=0): slc = tuple(slc) data = _do_op(data[slc], tally_value, n_spatial_filters) else: - data[:, ...] = 0.0 + data[:] = 0.0 data = _do_op(data, tally_value, n_spatial_filters) # filter by selected scores @@ -465,12 +858,72 @@ def _do_op(array, tally_value, ax=0): return image_data, None, data_min, data_max - def _create_tally_mesh_image(self, tally, tally_value, scores, nuclides, view=None): + def _create_distribcell_image(self, tally, tally_value, scores, nuclides, cellinstance=False): + # Get flattened array of tally results + data = tally.get_values(scores=scores, nuclides=nuclides, value=tally_value) + data = data.flatten() + + # Create an empty array of appropriate shape for image + image_data = np.full_like(self.ids, np.nan, dtype=float) + + # Determine mapping of cell IDs to list of (instance, tally value). + if cellinstance: + f = tally.find_filter(openmc.CellInstanceFilter) + cell_id_to_inst_value = defaultdict(list) + for value, (cell_id, instance) in zip(data, f.bins): + cell_id_to_inst_value[cell_id].append((instance, value)) + else: + f = tally.find_filter(openmc.DistribcellFilter) + cell_id_to_inst_value = {f.bins[0]: list(enumerate(data))} + + for cell_id, value_list in cell_id_to_inst_value.items(): + # Get mask for each relevant cell + cell_id_mask = (self.cell_ids == cell_id) + + # For each cell, iterate over instances and corresponding tally + # values and set any matching pixels + for instance, value in value_list: + instance_mask = (self.instances == instance) + image_data[cell_id_mask & instance_mask] = value + + data_min = np.min(data) + data_max = np.max(data) + image_data = np.ma.masked_where(image_data < 0.0, image_data) + + return image_data, None, data_min, data_max + + def cpp_mesh_ids(self): + return list(openmc.lib.meshes.keys()) + + def mesh_plot_bins(self, mesh_id, view: PlotView = None, translation: tuple[float, float, float] = None): + mesh = openmc.lib.meshes[mesh_id] + + if view is None: + view = self.currentView + + if translation is None: + origin = view.origin + else: + origin = (view.origin[0] - translation[0], + view.origin[1] - translation[1], + view.origin[2] - translation[2]) + + mesh_bins = mesh.get_plot_bins( + origin=origin, + width=(view.width, view.height), + basis=view.basis, + pixels=(view.h_res, view.v_res), + ) + return mesh_bins + + def _create_tally_mesh_image( + self, tally: openmc.Tally, tally_value: TallyValueType, + scores: Tuple[str], nuclides: Tuple[str], view: PlotView = None + ): # some variables used throughout if view is None: - cv = self.currentView + view = self.currentView - sp = self.statepoint mesh_filter = tally.find_filter(openmc.MeshFilter) mesh = mesh_filter.mesh @@ -483,61 +936,23 @@ def _do_op(array, tally_value, ax=0): # start with reshaped data data = tally.get_reshaped_data(tally_value) - # determine basis indices - if view.basis == 'xy': - h_ind = 0 - v_ind = 1 - ax = 2 - elif view.basis == 'yz': - h_ind = 1 - v_ind = 2 - ax = 0 - else: - h_ind = 0 - v_ind = 2 - ax = 1 - - # adjust corners of the mesh for a translation - # applied to the mesh filter - lower_left = mesh.lower_left - upper_right = mesh.upper_right - if hasattr(mesh_filter, 'translation') and mesh_filter.translation is not None: - lower_left += mesh_filter.translation - upper_right += mesh_filter.translation - - # reduce data to the visible slice of the mesh values - k = int((view.origin[ax] - lower_left[ax]) // mesh.width[ax]) - - # setup slice - data_slice = [None, None, None] - data_slice[h_ind] = slice(mesh.dimension[h_ind]) - data_slice[v_ind] = slice(mesh.dimension[v_ind]) - data_slice[ax] = k - - if k < 0 or k > mesh.dimension[ax]: - return (None, None, None, None) - # move mesh axes to the end of the filters filter_idx = [type(filter) for filter in tally.filters].index(openmc.MeshFilter) data = np.moveaxis(data, filter_idx, -1) - # reshape data (with zyx ordering for mesh data) - data = data.reshape(data.shape[:-1] + tuple(mesh.dimension[::-1])) - data = data[..., data_slice[2], data_slice[1], data_slice[0]] - # sum over the rest of the tally filters for tally_filter in tally.filters: if type(tally_filter) == openmc.MeshFilter: continue - if tally_filter in self.appliedFilters: - selected_bins = self.appliedFilters[tally_filter] + selected_bins = self.appliedFilters[tally_filter] + if selected_bins: # sum filter data for the selected bins data = data[np.array(selected_bins)].sum(axis=0) else: # if the filter is completely unselected, - # set all of it's data to zero and remove the axis - data[:, ...] = 0.0 + # set all of its data to zero and remove the axis + data[:] = 0.0 data = _do_op(data, tally_value) # filter by selected nuclides @@ -560,35 +975,131 @@ def _do_op(array, tally_value, ax=0): selected_scores.append(idx) data = _do_op(data[np.array(selected_scores)], tally_value) + # Get mesh bins from openmc.lib + mesh_cpp = openmc.lib.meshes[mesh.id] + mesh_bins = self.mesh_plot_bins(mesh.id, view, mesh_filter.translation) + + # Apply volume normalization + if view.tallyVolumeNorm: + data /= mesh_cpp.volumes + + # set image data + image_data = np.full_like(self.ids, np.nan, dtype=float) + mask = (mesh_bins >= 0) + image_data[mask] = data[mesh_bins[mask]] + # get dataset's min/max data_min = np.min(data) data_max = np.max(data) - # set image data, reverse y-axis - image_data = data[::-1, ...] + return image_data, None, data_min, data_max - # return data extents (in cm) for the tally - extents = [lower_left[h_ind], upper_right[h_ind], - lower_left[v_ind], upper_right[v_ind]] + def _create_tally_filter_image( + self, tally: openmc.Tally, tally_value: TallyValueType, filter_class, + scores: Tuple[str], nuclides: Tuple[str], view: PlotView = None + ): + # some variables used throughout + if view is None: + view = self.currentView - return image_data, extents, data_min, data_max + def _do_op(array, tally_value, ax=0): + if tally_value == 'mean': + return np.sum(array, axis=ax) + elif tally_value == 'std_dev': + return np.sqrt(np.sum(array**2, axis=ax)) + # start with reshaped data + data = tally.get_reshaped_data(tally_value) -class PlotView(openmc.lib.plot._PlotBase): - """ View settings for OpenMC plot. + # move mesh axes to the end of the filters + filter_idx = [type(filter) for filter in tally.filters].index(filter_class) + data = np.moveaxis(data, filter_idx, -1) + + # sum over the rest of the tally filters + for tally_filter in tally.filters: + if type(tally_filter) is filter_class: + continue + + selected_bins = self.appliedFilters[tally_filter] + if selected_bins: + # sum filter data for the selected bins + data = data[np.array(selected_bins)].sum(axis=0) + else: + # if the filter is completely unselected, + # set all of its data to zero and remove the axis + data[:] = 0.0 + data = _do_op(data, tally_value) + + # filter by selected nuclides + if not nuclides: + data = 0.0 + + selected_nuclides = [] + for idx, nuclide in enumerate(tally.nuclides): + if nuclide in nuclides: + selected_nuclides.append(idx) + data = _do_op(data[np.array(selected_nuclides)], tally_value) + + # filter by selected scores + if not scores: + data = 0.0 + + selected_scores = [] + for idx, score in enumerate(tally.scores): + if score in scores: + selected_scores.append(idx) + data = _do_op(data[np.array(selected_scores)], tally_value) + + # Extract filter bins from geom_data (computed during slice_data call) + # geom_data has shape (v_res, h_res, 4) when filter was included + if self.geom_data.shape[2] < 4: + raise RuntimeError( + "Filter bins not available. Ensure slice_data was called with " + "the appropriate filter for MeshMaterialFilter tallies." + ) + bins = self.geom_data[:, :, 3] + + # set image data + image_data = np.full_like(self.ids, np.nan, dtype=float) + mask = (bins >= 0) + image_data[mask] = data[bins[mask]] + + # get dataset's min/max + data_min = np.min(data) + data_max = np.max(data) + + return image_data, None, data_min, data_max + + @property + def cell_ids(self): + return self.geom_data[:, :, 0] + + @property + def instances(self): + return self.geom_data[:, :, 1] + + @property + def mat_ids(self): + return self.geom_data[:, :, 2] + + +class ViewParam: + """View parameters defining a 2-D geometry slice. Parameters ---------- - origin : 3-tuple of floats + origin : sequence of float Origin (center) of plot view - width: float + width : float Width of plot view in model units height : float Height of plot view in model units + default_res : int + Default resolution as the number of pixels in each direction Attributes ---------- - origin : 3-tuple of floats + origin : list of float Origin (center) of plot view width : float Width of the plot view in model units @@ -598,11 +1109,106 @@ class PlotView(openmc.lib.plot._PlotBase): Horizontal resolution of plot image v_res : int Vertical resolution of plot image + basis : {'xy', 'xz', 'yz'} + The basis directions for the plot + slice_axis : int + The axis along which the plot is sliced + color_overlaps : bool + Indicator of whether or not overlaps will be shown + level : int + The universe level for the plot (default: -1 -> all universes shown) + """ + + _VALID_BASES = ('xy', 'xz', 'yz') + + def __init__(self, origin=(0, 0, 0), width=10, height=10, default_res=1000): + self.origin = list(origin) + self.width = float(width) + self.height = float(height) + self.h_res = int(default_res) + self.v_res = int(default_res) + self.basis = 'xy' + self.level = -1 + self.color_overlaps = False + + @property + def basis(self): + return self._basis + + @basis.setter + def basis(self, basis): + if basis not in self._VALID_BASES: + raise ValueError(f"'{basis}' is not a valid plot basis. " + f"Must be one of {self._VALID_BASES}.") + self._basis = basis + + @property + def slice_axis(self): + if self._basis == 'xy': + return 2 + elif self._basis == 'yz': + return 0 + else: + return 1 + + @property + def llc(self): + if self._basis == 'xy': + x = self.origin[0] - self.width / 2.0 + y = self.origin[1] - self.height / 2.0 + z = self.origin[2] + elif self._basis == 'yz': + x = self.origin[0] + y = self.origin[1] - self.width / 2.0 + z = self.origin[2] - self.height / 2.0 + else: + x = self.origin[0] - self.width / 2.0 + y = self.origin[1] + z = self.origin[2] - self.height / 2.0 + return x, y, z + + @property + def urc(self): + if self._basis == 'xy': + x = self.origin[0] + self.width / 2.0 + y = self.origin[1] + self.height / 2.0 + z = self.origin[2] + elif self._basis == 'yz': + x = self.origin[0] + y = self.origin[1] + self.width / 2.0 + z = self.origin[2] + self.height / 2.0 + else: + x = self.origin[0] + self.width / 2.0 + y = self.origin[1] + z = self.origin[2] + self.height / 2.0 + return x, y, z + + def __repr__(self): + out_str = ["-----", + "Plot:", + "-----", + f"Origin: {self.origin}", + f"Width: {self.width}", + f"Height: {self.height}", + f"Basis: {self.basis}", + f"HRes: {self.h_res}", + f"VRes: {self.v_res}", + f"Color Overlaps: {self.color_overlaps}", + f"Level: {self.level}"] + return '\n'.join(out_str) + + def __eq__(self, other): + return repr(self) == repr(other) + + +class PlotViewIndependent: + """View settings for OpenMC plot, independent of the model. + + Attributes + ---------- aspectLock : bool Indication of whether aspect lock should be maintained to prevent image stretching/warping - basis : {'xy', 'xz', 'yz'} - The basis directions for the plot colorby : {'cell', 'material', 'temperature', 'density'} Indication of whether the plot should be colored by cell or material masking : bool @@ -620,20 +1226,16 @@ class PlotView(openmc.lib.plot._PlotBase): is active domainBackground : 3-tuple of int RGB color to apply to plot background - color_overlaps : bool - Indicator of whether or not overlaps will be shown overlap_color : 3-tuple of int RGB color to apply for cell overlap regions - cells : Dict of DomainView instances - Dictionary of cell view settings by ID - materials : Dict of DomainView instances - Dictionary of material view settings by ID domainAlpha : float between 0 and 1 Alpha value of the geometry plot plotVisibile : bool Controls visibility of geometry - outlines: bool - Controls visibility of geometry outlines + outlinesCell : bool + Controls visibility of cell outlines + outlinesMat : bool + Controls visibility of material outlines tallyDataColormap : str Name of the colormap used for tally data tallyDataVisible : bool @@ -648,6 +1250,8 @@ class PlotView(openmc.lib.plot._PlotBase): Minimum scale value for tally data tallyDataLogScale : bool Indicator of logarithmic scale for tally data + tallyDataMinMaxType : str + Type of min/max scaling for tally data: 'full', 'visible', or 'custom' tallyMaskZeroValues : bool Indicates whether or not zero values in tally data should be masked clipTallyData: bool @@ -658,26 +1262,12 @@ class PlotView(openmc.lib.plot._PlotBase): Indicates whether or not tallies are displayed as contours tallyContourLevels : str Number of contours levels or explicit level values - selectedTally : str - Label of the currently selected tally """ - def __init__(self, origin, width, height): - """ Initialize PlotView attributes """ - - super().__init__() - - # View Parameters - self.level = -1 - self.origin = origin - self.width = width - self.height = height - self.h_res = 1000 - self.v_res = 1000 - self.aspectLock = True - self.basis = 'xy' - + def __init__(self): + """Initialize PlotViewIndependent attributes""" # Geometry Plot + self.aspectLock = True self.colorby = 'material' self.masking = True self.maskBackground = (0, 0, 0) @@ -689,7 +1279,8 @@ def __init__(self, origin, width, height): self.overlap_color = (255, 0, 0) self.domainAlpha = 1.0 self.domainVisible = True - self.outlines = False + self.outlinesCell = False + self.outlinesMat = False self.colormaps = {'temperature': 'Oranges', 'density': 'Greys'} # set defaults for color dialog self.data_minmax = {prop: (0.0, 0.0) for prop in _MODEL_PROPERTIES} @@ -697,31 +1288,140 @@ def __init__(self, origin, width, height): self.use_custom_minmax = {prop: False for prop in _MODEL_PROPERTIES} self.data_indicator_enabled = {prop: False for prop in _MODEL_PROPERTIES} self.color_scale_log = {prop: False for prop in _MODEL_PROPERTIES} - # Get model domain info - self.cells = self.getDomains('cell') - self.materials = self.getDomains('material') # Tally Viz Settings - self.tallyDataColormap = 'spectral' + self.tallyDataColormap = 'Spectral' + self.tallyDataReverseCmap = False self.tallyDataVisible = True self.tallyDataAlpha = 1.0 self.tallyDataIndicator = False - self.tallyDataUserMinMax = False + self.tallyDataMinMaxType = 'full' # 'full', 'visible', or 'custom' self.tallyDataMin = 0.0 self.tallyDataMax = np.inf self.tallyDataLogScale = False self.tallyMaskZeroValues = False + self.tallyVolumeNorm = False self.clipTallyData = False self.tallyValue = "Mean" self.tallyContours = False self.tallyContourLevels = "" - self.selectedTally = None + + def __setstate__(self, state): + """Handle backward compatibility when unpickling old views""" + self.__dict__.update(state) + # Add missing attributes from older versions + if not hasattr(self, 'outlinesCell'): + self.outlinesCell = False + if not hasattr(self, 'outlinesMat'): + self.outlinesMat = False + # Migrate old boolean attributes to new tallyDataMinMaxType + if not hasattr(self, 'tallyDataMinMaxType'): + if getattr(self, 'tallyDataUserMinMax', False): + self.tallyDataMinMaxType = 'custom' + else: + self.tallyDataMinMaxType = 'full' + # Remove old attributes if present + self.__dict__.pop('tallyDataUserMinMax', None) + + def getDataLimits(self): + return self.data_minmax + + def getColorLimits(self, property): + if self.use_custom_minmax[property]: + return self.user_minmax[property] + else: + return self.data_minmax[property] + + +class PlotView: + """Setup the view of the model. + + Parameters + ---------- + origin : 3-tuple of floats + Origin (center) of plot view + width : float + Width of plot view in model units + height : float + Height of plot view in model units + restore_view : PlotView or None + view object with specified parameters to restore + restore_domains : bool (optional) + If True and restore_view is provided, then also restore domain + properties. Default False. + + Attributes + ---------- + view_ind : PlotViewIndependent instance + viewing parameters that are independent of the model + view_params : ViewParam instance + view parameters defining the 2-D geometry slice + cells : Dict of DomainView instances + Dictionary of cell view settings by ID + materials : Dict of DomainView instances + Dictionary of material view settings by ID + selectedTally : str + Label of the currently selected tally + """ + + attrs = ('view_ind', 'view_params', 'cells', 'materials', 'selectedTally', 'mesh_annotations') + view_param_attrs = ('level', 'origin', 'width', 'height', + 'h_res', 'v_res', 'basis', 'llc', 'urc', 'color_overlaps', 'slice_axis') + + def __init__(self, origin=(0, 0, 0), width=10, height=10, restore_view=None, + restore_domains=False, default_res=None): + """Initialize PlotView attributes""" + + self.mesh_annotations = [] + + if restore_view is not None: + self.view_ind = copy.copy(restore_view.view_ind) + self.view_params = copy.copy(restore_view.view_params) + if default_res is not None: + p = self.view_params + p.h_res = default_res + p.v_res = int(default_res * p.height / p.width) + else: + self.view_ind = PlotViewIndependent() + if default_res is not None: + self.view_params = ViewParam(origin, width, height, default_res) + else: + self.view_params = ViewParam(origin, width, height) + + # Get model domain info + if restore_domains and restore_view is not None: + self.cells = restore_view.cells + self.materials = restore_view.materials + self.selectedTally = restore_view.selectedTally + else: + rng = np.random.RandomState(10) + self.cells = self.getDomains('cell', rng) + self.materials = self.getDomains('material', rng) + self.selectedTally = None + + def __getattr__(self, name): + if name in self.attrs: + if name not in self.__dict__: + raise AttributeError('{} not in PlotView dict'.format(name)) + return self.__dict__[name] + elif name in self.view_param_attrs: + return getattr(self.view_params, name) + else: + return getattr(self.view_ind, name) + + def __setattr__(self, name, value): + if name in self.attrs: + super().__setattr__(name, value) + elif name in self.view_param_attrs: + setattr(self.view_params, name, value) + else: + setattr(self.view_ind, name, value) def __hash__(self): return hash(self.__dict__.__str__() + self.__str__()) @staticmethod - def getDomains(domain_type): + def getDomains(domain_type, rng) -> DomainViewDict: """ Return dictionary of domain settings. Retrieve cell or material ID numbers and names from .xml files @@ -742,68 +1442,41 @@ def getDomains(domain_type): raise ValueError("Domain type, {}, requested is neither " "'cell' nor 'material'.".format(domain_type)) - lib_domain = None + # Get number of domains, functions for ID/name, and dictionary for defaults if domain_type == 'cell': - lib_domain = openmc.lib.cells + num_domain = len(openmc.lib.cells) + get_id = openmc.lib.core._dll.openmc_cell_get_id + get_name = openmc.lib.core._dll.openmc_cell_get_name elif domain_type == 'material': - lib_domain = openmc.lib.materials - - domains = {} - for domain, domain_obj in lib_domain.items(): - name = domain_obj.name - domains[domain] = DomainView(domain, name, random_rgb()) + num_domain = len(openmc.lib.materials) + get_id = openmc.lib.core._dll.openmc_material_get_id + get_name = openmc.lib.core._dll.openmc_material_get_name + + # Sample default colors for each domain + colors = rng.randint(256, size=(num_domain, 3)) + + domain_id_c = c_int32() + name_c = c_char_p() + defaults = {} + for i, color in enumerate(colors): + # Get ID and name for each domain + get_id(i, domain_id_c) + get_name(i, name_c) + domain_id = domain_id_c.value + name = name_c.value.decode() + + # Create default domain view for this domain + defaults[domain_id] = DomainView(domain_id, name, color) # always add void to a material domain at the end if domain_type == 'material': void_id = _VOID_REGION - domains[void_id] = DomainView(void_id, "VOID", - (255, 255, 255), - False, - False) + defaults[void_id] = DomainView(void_id, "VOID", (255, 255, 255), + False, False) - return domains + return DomainViewDict(defaults) - def getDataLimits(self): - return self.data_minmax - - def getColorLimits(self, property): - if self.use_custom_minmax[property]: - return self.user_minmax[property] - else: - return self.data_minmax[property] - - @property - def llc(self): - if self.basis == 'xy': - x = self.origin[0] - self.width / 2.0 - y = self.origin[1] - self.height / 2.0 - z = self.origin[2] - elif self.basis == 'yz': - x = self.origin[0] - y = self.origin[1] - self.width / 2.0 - z = self.origin[2] - self.height / 2.0 - else: - x = self.origin[0] - self.width / 2.0 - y = self.origin[1] - z = self.origin[2] - self.height / 2.0 - return x, y, z - @property - def urc(self): - if self.basis == 'xy': - x = self.origin[0] + self.width / 2.0 - y = self.origin[1] + self.height / 2.0 - z = self.origin[2] - elif self.basis == 'yz': - x = self.origin[0] - y = self.origin[1] + self.width / 2.0 - z = self.origin[2] + self.height / 2.0 - else: - x = self.origin[0] + self.width / 2.0 - y = self.origin[1] - z = self.origin[2] + self.height / 2.0 - return x, y, z - - def adopt_plotbase(self, view): + def adopt_view_params(self, view): """ Applies only the geometric aspects of a view to the current view @@ -816,12 +1489,67 @@ def adopt_plotbase(self, view): self.origin = view.origin self.width = view.width self.height = view.height - self.h_res = self.h_res - self.v_res = self.v_res + self.h_res = view.h_res + self.v_res = view.v_res self.basis = view.basis -class DomainView(): - """ Represents view settings for OpenMC cell or material. + +class DomainViewDict(dict): + """Dictionary of domain ID to DomainView objects with shared defaults + + When the active/current view changes in the plotter, this dictionary gets + deepcopied. To avoid the dictionary being huge for models with lots of + cells/materials, defaults are stored separately and the key/value pairs in + this dictionary represent modifications to the default pairs. When an item + is looked up, if there is no locally modified version we pull the value from + the defaults dictionary. + + """ + def __init__(self, defaults: Dict[int, DomainView]): + self.defaults = defaults + + def __getitem__(self, key) -> DomainView: + if key in self: + return super().__getitem__(key) + else: + # If key is not present, pull it from the defaults + return self.defaults[key] + + def __deepcopy__(self, memo): + cls = self.__class__ + obj = cls.__new__(cls) + memo[id(self)] = obj + for key, value in self.items(): + obj[key] = copy.deepcopy(value) + # Shallow copy the defaults dictionary + obj.defaults = self.defaults + return obj + + def get_defaults(self, key: int) -> DomainView: + return self.defaults[key] + + def get_default_color(self, key: int): + return self.get_defaults(key).color + + def set_name(self, key: int, name: Optional[str]): + domain = self[key] + self[key] = DomainView(domain.id, name, domain.color, domain.masked, domain.highlight) + + def set_color(self, key: int, color): + domain = self[key] + self[key] = DomainView(domain.id, domain.name, color, domain.masked, domain.highlight) + + def set_masked(self, key: int, masked: bool): + domain = self[key] + self[key] = DomainView(domain.id, domain.name, domain.color, masked, domain.highlight) + + def set_highlight(self, key: int, highlight: bool): + domain = self[key] + self[key] = DomainView(domain.id, domain.name, domain.color, domain.masked, highlight) + + +class DomainView: + """Represents view settings for OpenMC cell or material. Parameters ---------- @@ -864,22 +1592,24 @@ def __eq__(self, other): class DomainTableModel(QAbstractTableModel): """ Abstract Table Model of cell/material view attributes """ - def __init__(self, domains): + def __init__(self, domains: DomainViewDict): super().__init__() - self.domains = [dom for dom in domains.values()] + self.domains = domains + self.keys = dict(enumerate(self.domains.defaults)) def rowCount(self, index=QModelIndex()): - return len(self.domains) + return len(self.keys) def columnCount(self, index=QModelIndex()): return 6 def data(self, index, role=Qt.DisplayRole): - if not index.isValid() or not (0 <= index.row() < len(self.domains)): + if not index.isValid() or not (0 <= index.row() < self.rowCount()): return None - domain = self.domains[index.row()] + key = self.keys[index.row()] + domain = self.domains[key] column = index.column() if role == Qt.DisplayRole: @@ -890,7 +1620,8 @@ def data(self, index, role=Qt.DisplayRole): elif column == COLOR: return '' if domain.color is not None else '+' elif column == COLORLABEL: - return str(domain.color) if domain.color is not None else '--' + return (str(tuple(int(x) for x in domain.color)) + if domain.color is not None else '--') elif column == MASK: return None elif column == HIGHLIGHT: @@ -910,13 +1641,13 @@ def data(self, index, role=Qt.DisplayRole): else: return int(Qt.AlignLeft | Qt.AlignVCenter) - elif role == Qt.BackgroundColorRole: + elif role == Qt.BackgroundRole: color = domain.color if column == COLOR: - if isinstance(color, tuple): - return QColor.fromRgb(*color) - elif isinstance(color, str): + if isinstance(color, str): return QColor.fromRgb(*openmc.plots._SVG_COLORS[color]) + else: + return QColor.fromRgb(*color) elif role == Qt.CheckStateRole: if column == MASK: @@ -960,24 +1691,25 @@ def flags(self, index): def setData(self, index, value, role=Qt.EditRole): - if not index.isValid() or not (0 <= index.row() < len(self.domains)): + if not index.isValid() or not (0 <= index.row() < self.rowCount()): return False - domain = self.domains[index.row()] + key = self.keys[index.row()] column = index.column() if column == NAME: - domain.name = value if value else None - elif column == COLOR: - domain.color = value - elif column == COLORLABEL: - domain.color = value + self.domains.set_name(key, value if value else None) + elif column == COLOR or column == COLORLABEL: + # reset the color to the default value if the coloar value is None + if value is None: + value = self.domains.get_default_color(key) + self.domains.set_color(key, value) elif column == MASK: if role == Qt.CheckStateRole: - domain.masked = True if value == Qt.Checked else False + self.domains.set_masked(key, Qt.CheckState(value) == Qt.Checked) elif column == HIGHLIGHT: if role == Qt.CheckStateRole: - domain.highlight = True if value == Qt.Checked else False + self.domains.set_highlight(key, Qt.CheckState(value) == Qt.Checked) self.dataChanged.emit(index, index) return True @@ -1016,7 +1748,7 @@ def createEditor(self, parent, option, index): def setEditorData(self, editor, index): if index.column() == COLOR: - color = index.data(Qt.BackgroundColorRole) + color = index.data(Qt.BackgroundRole) color = 'white' if color is None else color editor.setCurrentColor(color) elif index.column() in (NAME, COLORLABEL): @@ -1027,7 +1759,7 @@ def setEditorData(self, editor, index): def editorEvent(self, event, model, option, index): if index.column() in (COLOR, COLORLABEL): - if not int(index.flags() & Qt.ItemIsEditable) > 0: + if (index.flags() & Qt.ItemFlag.ItemIsEditable) == Qt.ItemFlag.NoItemFlags: return False if event.type() == QEvent.MouseButtonRelease \ and event.button() == Qt.RightButton: @@ -1043,13 +1775,13 @@ def setModelData(self, editor, model, index): column = index.column() if column == COLOR and editor is None: - model.setData(index, None, Qt.BackgroundColorRole) + model.setData(index, None, Qt.BackgroundRole) model.setData(model.index(row, column+1), None, Qt.DisplayRole) elif column == COLOR: color = editor.currentColor() if color != QColor(): color = color.getRgb()[:3] - model.setData(index, color, Qt.BackgroundColorRole) + model.setData(index, color, Qt.BackgroundRole) model.setData(model.index(row, column+1), color, Qt.DisplayRole) @@ -1057,14 +1789,14 @@ def setModelData(self, editor, model, index): if editor is None: model.setData(model.index(row, column-1), None, - Qt.BackgroundColorRole) + Qt.BackgroundRole) model.setData(index, None, Qt.DisplayRole) elif editor.text().lower() in openmc.plots._SVG_COLORS: svg = editor.text().lower() color = openmc.plots._SVG_COLORS[svg] model.setData(model.index(row, column-1), color, - Qt.BackgroundColorRole) + Qt.BackgroundRole) model.setData(index, svg, Qt.DisplayRole) else: try: @@ -1078,7 +1810,7 @@ def setModelData(self, editor, model, index): return None model.setData(model.index(row, column-1), input, - Qt.BackgroundColorRole) + Qt.BackgroundRole) model.setData(index, input, Qt.DisplayRole) else: QItemDelegate.setModelData(self, editor, model, index) diff --git a/openmc_plotter/scientific_spin_box.py b/openmc_plotter/scientific_spin_box.py index a56b993..f8b8420 100644 --- a/openmc_plotter/scientific_spin_box.py +++ b/openmc_plotter/scientific_spin_box.py @@ -1,7 +1,7 @@ import re -from PySide2 import QtGui -from PySide2.QtWidgets import QDoubleSpinBox +from PySide6 import QtGui +from PySide6.QtWidgets import QDoubleSpinBox import numpy as np # Regular expression to find floats. Match groups are the whole string, the diff --git a/openmc_plotter/tools.py b/openmc_plotter/tools.py index df431d1..b6b6024 100644 --- a/openmc_plotter/tools.py +++ b/openmc_plotter/tools.py @@ -1,13 +1,100 @@ import copy -from time import sleep import numpy as np import openmc -from PySide2 import QtCore, QtGui, QtWidgets +from PySide6 import QtCore, QtWidgets from .custom_widgets import HorizontalLine from .scientific_spin_box import ScientificDoubleSpinBox + +class SourceSitesDialog(QtWidgets.QDialog): + def __init__(self, model, font_metric, parent=None): + super().__init__(parent) + + self.setWindowTitle('Sample Source Sites') + self.model = model + self.font_metric = font_metric + self.parent = parent + + self.layout = QtWidgets.QFormLayout() + self.setLayout(self.layout) + + self.populate() + + def populate(self): + self.nSitesBox = QtWidgets.QSpinBox(self) + self.nSitesBox.setMaximum(1_000_000) + self.nSitesBox.setMinimum(0) + self.nSitesBox.setValue(1000) + self.nSitesBox.setToolTip('Number of source sites to sample from the OpenMC source') + + self.sites_visible = QtWidgets.QCheckBox(self) + self.sites_visible.setChecked(self.model.sourceSitesVisible) + self.sites_visible.setToolTip('Toggle visibility of source sites on the slice plane') + self.sites_visible.stateChanged.connect(self._toggle_source_sites) + + self.colorButton = QtWidgets.QPushButton(self) + self.colorButton.setToolTip('Select color for displaying source sites on the slice plane') + self.colorButton.setCursor(QtCore.Qt.PointingHandCursor) + self.colorButton.setFixedHeight(self.font_metric.height() * 1.5) + self.colorButton.clicked.connect(self._select_source_site_color) + rgb = self.model.sourceSitesColor + self.colorButton.setStyleSheet( + f"border-radius: 8px; background-color: rgb{rgb}") + + self.toleranceBox = ScientificDoubleSpinBox() + self.toleranceBox.setToolTip('Slice axis tolerance for displaying source sites on the slice plane') + self.toleranceBox.setValue(self.model.sourceSitesTolerance) + self.toleranceBox.valueChanged.connect(self._set_source_site_tolerance) + self.toleranceBox.setEnabled(self.model.sourceSitesApplyTolerance) + + self.toleranceToggle = QtWidgets.QCheckBox(self) + self.toleranceToggle.setChecked(self.model.sourceSitesApplyTolerance) + self.toleranceToggle.stateChanged.connect(self._toggle_tolerance) + + self.sampleButton = QtWidgets.QPushButton("Sample New Sites") + self.sampleButton.setToolTip('Sample new source sites from the OpenMC source') + self.sampleButton.clicked.connect(self._sample_sites) + + self.closeButton = QtWidgets.QPushButton("Close") + self.closeButton.clicked.connect(self.close) + + self.layout.addRow("Source Sites:", self.nSitesBox) + self.layout.addRow("Visible:", self.sites_visible) + self.layout.addRow("Color:", self.colorButton) + self.layout.addRow('Tolerance:', self.toleranceBox) + self.layout.addRow('Apply tolerance:', self.toleranceToggle) + self.layout.addRow(HorizontalLine()) + self.layout.addRow(self.sampleButton) + self.layout.addRow(self.closeButton) + + def _sample_sites(self): + self.model.getExternalSourceSites(self.nSitesBox.value()) + self.parent.applyChanges() + + def _toggle_source_sites(self): + self.model.sourceSitesVisible = self.sites_visible.isChecked() + self.parent.applyChanges() + + def _select_source_site_color(self): + color = QtWidgets.QColorDialog.getColor() + if color.isValid(): + rgb = self.model.sourceSitesColor = color.getRgb()[:3] + self.colorButton.setStyleSheet( + f"border-radius: 8px; background-color: rgb{rgb}") + self.parent.applyChanges() + + def _toggle_tolerance(self): + self.model.sourceSitesApplyTolerance = self.toleranceToggle.isChecked() + self.toleranceBox.setEnabled(self.toleranceToggle.isChecked()) + self.parent.applyChanges() + + def _set_source_site_tolerance(self): + self.model.sourceSitesTolerance = self.toleranceBox.value() + self.parent.applyChanges() + + class ExportDataDialog(QtWidgets.QDialog): """ A dialog to facilitate generation of VTK files for @@ -36,7 +123,7 @@ def _warn(msg): msg_box.setText(msg) msg_box.setIcon(QtWidgets.QMessageBox.Information) msg_box.setStandardButtons(QtWidgets.QMessageBox.Ok) - msg_box.exec_() + msg_box.exec() def populate(self): cv = self.model.currentView @@ -168,33 +255,36 @@ def populate(self): mesh = mesh_filter.mesh assert(mesh.n_dimension == 3) - llc = mesh.lower_left + bbox = mesh.bounding_box + + llc = bbox.lower_left self.xminBox.setValue(llc[0]) self.yminBox.setValue(llc[1]) self.zminBox.setValue(llc[2]) - urc = mesh.upper_right + urc = bbox.upper_right self.xmaxBox.setValue(urc[0]) self.ymaxBox.setValue(urc[1]) self.zmaxBox.setValue(urc[2]) - dims = mesh.dimension - self.xResBox.setValue(dims[0]) - self.yResBox.setValue(dims[1]) - self.zResBox.setValue(dims[2]) - bounds_msg = "Using MeshFilter to set bounds automatically." for box in self.bounds_spin_boxes: box.setEnabled(False) box.setToolTip(bounds_msg) - resolution_msg = "Using MeshFilter to set resolution automatically." - self.xResBox.setEnabled(False) - self.xResBox.setToolTip(resolution_msg) - self.yResBox.setEnabled(False) - self.yResBox.setToolTip(resolution_msg) - self.zResBox.setEnabled(False) - self.zResBox.setToolTip(resolution_msg) + dims = mesh.dimension + if len(dims) == 3: + self.xResBox.setValue(dims[0]) + self.yResBox.setValue(dims[1]) + self.zResBox.setValue(dims[2]) + + resolution_msg = "Using MeshFilter to set resolution automatically." + self.xResBox.setEnabled(False) + self.xResBox.setToolTip(resolution_msg) + self.yResBox.setEnabled(False) + self.yResBox.setToolTip(resolution_msg) + self.zResBox.setEnabled(False) + self.zResBox.setToolTip(resolution_msg) else: # initialize using the bounds of the current view @@ -214,14 +304,12 @@ def populate(self): def export_data(self): # cache current and active views - cv = self.model.currentView av = self.model.activeView try: # export the tally data self._export_data() finally: - #always reset to the original view - self.model.currentView = cv + # always reset to the original view self.model.activeView = av self.model.makePlot() @@ -378,4 +466,4 @@ def _export_data(self): msg.setText("Export complete!") msg.setIcon(QtWidgets.QMessageBox.Information) msg.setStandardButtons(QtWidgets.QMessageBox.Ok) - msg.exec_() + msg.exec() diff --git a/pyproject.toml b/pyproject.toml index c953815..ca4045b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,2 +1,57 @@ [build-system] -requires = ["setuptools", "wheel"] \ No newline at end of file +requires = ["setuptools>=80", "setuptools_scm>=8", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "openmc-plotter" +dynamic = ["version"] +authors = [ + { name = "OpenMC Development Team", email = "openmc@anl.gov" }, +] +license = "MIT" +description = "Plotting tool for OpenMC models and tally data" +readme = "README.md" +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "Intended Audience :: End Users/Desktop", + "Intended Audience :: Science/Research", + "Natural Language :: English", + "Topic :: Scientific/Engineering", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.10" +dependencies = [ + "openmc>=0.15.0", + "numpy", + "matplotlib", + "PySide6", +] + +[project.optional-dependencies] +test = ["pytest", "pytest-qt"] +vtk = ["vtk"] + +[project.urls] +"Homepage" = "https://github.com/openmc-dev/plotter" +"Download" = "https://github.com/openmc-dev/plotter" +"Issue Tracker" = "https://github.com/openmc-dev/plotter/issues" +"Source Code" = "https://github.com/openmc-dev/plotter" + +[project.scripts] +openmc-plotter = "openmc_plotter.__main__:main" + +[tool.setuptools] +include-package-data = true + +[tool.setuptools.packages.find] +include = ["openmc_plotter*"] + +[tool.setuptools.package-data] +openmc_plotter = ["assets/*.png"] + +[tool.setuptools_scm] diff --git a/pytest.ini b/pytest.ini index 818dfa8..c834d18 100644 --- a/pytest.ini +++ b/pytest.ini @@ -1,6 +1,6 @@ [pytest] -qt_api=pyside2 +qt_api=pyside6 python_files = test*.py python_classes = NoThanks -filter_warnings = ignore::UserWarning -addopts = -rs \ No newline at end of file +filterwarnings = ignore::UserWarning +addopts = -rs diff --git a/screenshots/atr.png b/screenshots/atr.png new file mode 100644 index 0000000..2506fdc Binary files /dev/null and b/screenshots/atr.png differ diff --git a/screenshots/beavrs.png b/screenshots/beavrs.png new file mode 100644 index 0000000..07bda5f Binary files /dev/null and b/screenshots/beavrs.png differ diff --git a/screenshots/beavrs_zoomed.png b/screenshots/beavrs_zoomed.png new file mode 100644 index 0000000..345c66c Binary files /dev/null and b/screenshots/beavrs_zoomed.png differ diff --git a/screenshots/color_dialog.png b/screenshots/color_dialog.png new file mode 100644 index 0000000..89ee2aa Binary files /dev/null and b/screenshots/color_dialog.png differ diff --git a/screenshots/dagmc.png b/screenshots/dagmc.png new file mode 100644 index 0000000..83a8a42 Binary files /dev/null and b/screenshots/dagmc.png differ diff --git a/screenshots/pincell_tally.png b/screenshots/pincell_tally.png new file mode 100644 index 0000000..46075f1 Binary files /dev/null and b/screenshots/pincell_tally.png differ diff --git a/screenshots/shortcuts.png b/screenshots/shortcuts.png new file mode 100644 index 0000000..5ef32cd Binary files /dev/null and b/screenshots/shortcuts.png differ diff --git a/screenshots/source-sites.png b/screenshots/source-sites.png new file mode 100644 index 0000000..517dccf Binary files /dev/null and b/screenshots/source-sites.png differ diff --git a/setup.py b/setup.py deleted file mode 100644 index 654c047..0000000 --- a/setup.py +++ /dev/null @@ -1,48 +0,0 @@ -from setuptools import setup - -kwargs = { - 'name': 'openmc-plotter', - 'version': '0.1.1', - 'packages': ['openmc_plotter'], - 'package_data': {'openmc_plotter' : ['assets/*.png']}, - 'entry_points': { - 'console_scripts': [ - 'openmc-plotter=openmc_plotter.__main__:main' - ] - }, - - # Metadata - 'author': 'OpenMC Development Team', - 'author_email': 'openmc-users@googlegroups.com', - 'description': 'Plotting tool for OpenMC models and tally data', - 'url': 'https://github.com/openmc-dev/plotter', - 'download_url': 'https://github.com/openmc-dev/plotter', - 'project_urls': { - 'Issue Tracker': 'https://github.com/openmc-dev/plotter/issues', - 'Source Code': 'https://github.com/openmc-dev/plotter', - }, - 'classifiers': [ - 'Development Status :: 4 - Beta', - 'Intended Audience :: Developers', - 'Intended Audience :: End Users/Desktop', - 'Intended Audience :: Science/Research', - 'Natural Language :: English', - 'Topic :: Scientific/Engineering', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - ], - - # Dependencies - 'python_requires': '>=3.5', - 'install_requires': [ - 'openmc>0.12.0', 'numpy', 'matplotlib', 'PySide2' - ], - 'extras_require': { - 'test' : ['pytest', 'pytest-qt'], - 'vtk' : ['vtk'] - }, -} - -setup(**kwargs) diff --git a/tests/setup_test/ref.png b/tests/setup_test/ref.png new file mode 100644 index 0000000..87be998 Binary files /dev/null and b/tests/setup_test/ref.png differ diff --git a/tests/setup_test/ref1.png b/tests/setup_test/ref1.png new file mode 100644 index 0000000..1afd42c Binary files /dev/null and b/tests/setup_test/ref1.png differ diff --git a/tests/setup_test/test.pltvw b/tests/setup_test/test.pltvw new file mode 100644 index 0000000..2e48adf Binary files /dev/null and b/tests/setup_test/test.pltvw differ diff --git a/tests/setup_test/test.py b/tests/setup_test/test.py index f017d59..2782736 100644 --- a/tests/setup_test/test.py +++ b/tests/setup_test/test.py @@ -1,11 +1,112 @@ -import openmc.lib +import filecmp +import shutil + +import pytest +from PySide6 import QtGui, QtWidgets from openmc_plotter.main_window import MainWindow, _openmcReload -def test_window(qtbot): - _openmcReload() +@pytest.fixture +def run_in_tmpdir(tmpdir): + orig = tmpdir.chdir() + try: + yield + finally: + orig.chdir() + +def test_window(tmpdir, qtbot): + orig = tmpdir.chdir() + mw = MainWindow(model_path=orig) + _openmcReload(model_path=orig) + mw.loadGui() + + try: + assert mw.waitForPlotIdle(60000) + mw.saveImage(tmpdir / 'test.png') + + qtbot.addWidget(mw) + finally: + orig.chdir() + + filecmp.cmp(orig / 'ref.png', tmpdir / 'test.png') + + mw.close() + +def test_batch_image(tmpdir, qtbot): + orig = tmpdir.chdir() + + # move view file into tmpdir + shutil.copy2(orig / 'test.pltvw', tmpdir) + shutil.copy2(orig / 'test1.pltvw', tmpdir) + + _openmcReload(model_path=orig) + + mw = MainWindow(model_path=orig) + mw.loadGui() + + try: + mw.saveBatchImage('test.pltvw') + qtbot.addWidget(mw) + + mw.saveBatchImage('test1.pltvw') + qtbot.addWidget(mw) + finally: + orig.chdir() + + filecmp.cmp(orig / 'ref.png', tmpdir / 'test.png') + filecmp.cmp(orig / 'ref1.png', tmpdir / 'test1.png') - mw = MainWindow() + mw.close() + +def test_copy_image_to_clipboard(tmpdir, monkeypatch, qtbot): + orig = tmpdir.chdir() + QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) + mw = MainWindow(model_path=orig) + _openmcReload(model_path=orig) mw.loadGui() - mw.plotIm.figure.savefig("test.png") qtbot.addWidget(mw) + mw.show() + + class FakeClipboard: + def __init__(self): + self.image = None + + def setImage(self, image): + self.image = image + + fake_clipboard = FakeClipboard() + monkeypatch.setattr(QtGui.QGuiApplication, + 'clipboard', + staticmethod(lambda: fake_clipboard)) + + try: + assert mw.waitForPlotIdle(60000) + mw.model.currentView.domainVisible = False + mw.plotIm.updatePixmap() + assert mw.copyImageToClipboard() + finally: + orig.chdir() + + assert fake_clipboard.image is not None + assert not fake_clipboard.image.isNull() + assert fake_clipboard.image.hasAlphaChannel() + + canvas_width, canvas_height = mw.plotIm.get_width_height() + expected_width = round( + min(mw.frame.viewport().width(), mw.plotIm.width()) + * canvas_width + / mw.plotIm.width() + ) + expected_height = round( + min(mw.frame.viewport().height(), mw.plotIm.height()) + * canvas_height + / mw.plotIm.height() + ) + assert fake_clipboard.image.width() == pytest.approx(expected_width, abs=1) + assert fake_clipboard.image.height() == pytest.approx(expected_height, abs=1) + + center = fake_clipboard.image.pixelColor(fake_clipboard.image.width() // 2, + fake_clipboard.image.height() // 2) + assert center.alpha() == 0 + + mw.close() diff --git a/tests/setup_test/test1.pltvw b/tests/setup_test/test1.pltvw new file mode 100644 index 0000000..1ff0d13 Binary files /dev/null and b/tests/setup_test/test1.pltvw differ diff --git a/tests/test_plotgui_clipboard.py b/tests/test_plotgui_clipboard.py new file mode 100644 index 0000000..e65e593 --- /dev/null +++ b/tests/test_plotgui_clipboard.py @@ -0,0 +1,80 @@ +from types import SimpleNamespace + +import numpy as np +import pytest +from PySide6 import QtGui, QtWidgets + +from openmc_plotter.plotgui import PlotImage + + +class FakeClipboard: + + def __init__(self): + self.image = None + + def setImage(self, image): + self.image = image + + +@pytest.fixture +def qapp(): + return QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) + + +def test_copy_image_to_clipboard_crops_to_plot_and_preserves_alpha( + qapp, monkeypatch +): + scroll = QtWidgets.QScrollArea() + scroll.resize(220, 160) + main_window = SimpleNamespace( + logicalDpiX=lambda: 100, + zoom=100, + coord_label=SimpleNamespace(show=lambda: None, hide=lambda: None), + statusBar=lambda: SimpleNamespace(showMessage=lambda *args, **kwargs: None), + ) + plot = PlotImage(model=None, parent=scroll, main_window=main_window) + scroll.setWidget(plot) + plot.resize(400, 300) + plot.figure.clear() + plot.ax = plot.figure.subplots() + plot.ax.imshow(np.zeros((10, 10, 4))) + scroll.show() + qapp.processEvents() + scroll.horizontalScrollBar().setValue(40) + scroll.verticalScrollBar().setValue(30) + qapp.processEvents() + + fake_clipboard = FakeClipboard() + monkeypatch.setattr( + QtGui.QGuiApplication, + "clipboard", + staticmethod(lambda: fake_clipboard), + ) + + try: + assert plot.copyImageToClipboard() + finally: + plot.close() + scroll.close() + + assert fake_clipboard.image is not None + assert not fake_clipboard.image.isNull() + assert fake_clipboard.image.hasAlphaChannel() + + canvas_width, canvas_height = plot.get_width_height() + expected_width = round( + min(scroll.viewport().width(), plot.width()) * canvas_width / plot.width() + ) + expected_height = round( + min(scroll.viewport().height(), plot.height()) * canvas_height / plot.height() + ) + assert fake_clipboard.image.width() == pytest.approx(expected_width, abs=1) + assert fake_clipboard.image.height() == pytest.approx(expected_height, abs=1) + assert fake_clipboard.image.width() < canvas_width + assert fake_clipboard.image.height() < canvas_height + + center = fake_clipboard.image.pixelColor( + fake_clipboard.image.width() // 2, + fake_clipboard.image.height() // 2, + ) + assert center.alpha() == 0