From d3445fc0354ddd03cb688d7a81487b19260d1b91 Mon Sep 17 00:00:00 2001 From: Peter Willendrup Date: Tue, 13 Oct 2026 08:50:16 +0200 Subject: [PATCH 1/7] Add plopp-based prototypes: mcplot-plopp and mcdisplay-plopp New Python tools built on ESS plopp/scipp, alongside the matplotlib and pyqtgraph frontends. Both reuse mccodelib for loading and tracing. By default they open a one-cell JupyterLab notebook (ipympl widgets); -o FILE writes a static png/pdf/svg instead. mcplot-plopp (tools/Python/mcplot/plopp/mcplopp.py) - Monitors via McCodeDataLoader, converted to scipp DataArrays: 1D with I_err^2 variances and bin edges from xlimits; 2D as (y, x), consistent with the matplotlib frontend - Axis units parsed from "[...]" labels (AA/Angs, meV, deg, us, cm, m, s); unknown units stay in the label and the axis is dimensionless - Scans: each monitor stacked over the scan parameter (1D->2D, 2D->3D); UI offers a monitor dropdown plus a per-step slicer with player - No variances for 2D monitors yet (mcplotloader skips "# Errors") mcdisplay-plopp (tools/Python/mcdisplay/plopp/mcdisplopp.py) - Traces via McDisplayReader (unset params take defaults); draws the z-x and z-y projections of components and rays - UI: params text field, ray count and a Trace button that re-traces - Wireframe primitives only (line/multiline/circle, as pyqtgraph); no 3D view, since plopp has no 3D line primitive Build/packaging - CMake subprojects in parallel to the matplotlib tools; installs {mc,mx}plot-plopp and {mc,mx}display-plopp. The bash wrappers check the plopp stack and suggest pip if it is missing - Windows: plot-plopp/display-plopp .bat wrappers registered in InstallMCCODE.cmake; mkdist nsis64 lines in build_windows_mcstas and build_windows_mcxtrace; both packages added to the MinGW metapackage .iss files; scipp and plopp added to meta-pkgs/windows/environment.yml - No Debian packaging: scipp/plopp are not packaged by Debian Tested on macOS (mccode-dev env): static and UI paths against real single-run, scan and McStas 2.7 output, and BNL_H8/mini traces. CMake configure/build/install checked standalone for McStas and McXtrace. Not yet tested: Windows/NSIS builds and Linux. --- buildscripts/build_windows_mcstas | 2 + buildscripts/build_windows_mcxtrace | 2 + cmake/Modules/InstallMCCODE.cmake | 2 +- .../support/run-scripts/display-plopp.bat.in | 6 + cmake/support/run-scripts/plot-plopp.bat.in | 6 + .../windows/McStas-metapackage64-MinGW.iss | 4 + .../windows/McXtrace-metapackage64-MinGW.iss | 4 + meta-pkgs/windows/environment.yml | 2 + tools/Python/mcdisplay/CMakeLists.txt | 1 + tools/Python/mcdisplay/plopp/CMakeLists.txt | 77 ++ tools/Python/mcdisplay/plopp/COPYING | 674 ++++++++++++++++++ tools/Python/mcdisplay/plopp/cmake | 1 + tools/Python/mcdisplay/plopp/mcdisplay.in | 33 + tools/Python/mcdisplay/plopp/mcdisplopp.py | 129 ++++ .../Python/mcdisplay/plopp/test_mcdisplopp.py | 9 + tools/Python/mcplot/CMakeLists.txt | 1 + tools/Python/mcplot/plopp/CMakeLists.txt | 77 ++ tools/Python/mcplot/plopp/COPYING | 674 ++++++++++++++++++ tools/Python/mcplot/plopp/cmake | 1 + tools/Python/mcplot/plopp/mcplopp.py | 149 ++++ tools/Python/mcplot/plopp/mcplot.in | 33 + tools/Python/mcplot/plopp/test_mcplopp.py | 13 + 22 files changed, 1899 insertions(+), 1 deletion(-) create mode 100644 cmake/support/run-scripts/display-plopp.bat.in create mode 100644 cmake/support/run-scripts/plot-plopp.bat.in create mode 100644 tools/Python/mcdisplay/plopp/CMakeLists.txt create mode 100644 tools/Python/mcdisplay/plopp/COPYING create mode 120000 tools/Python/mcdisplay/plopp/cmake create mode 100644 tools/Python/mcdisplay/plopp/mcdisplay.in create mode 100644 tools/Python/mcdisplay/plopp/mcdisplopp.py create mode 100644 tools/Python/mcdisplay/plopp/test_mcdisplopp.py create mode 100644 tools/Python/mcplot/plopp/CMakeLists.txt create mode 100644 tools/Python/mcplot/plopp/COPYING create mode 120000 tools/Python/mcplot/plopp/cmake create mode 100644 tools/Python/mcplot/plopp/mcplopp.py create mode 100644 tools/Python/mcplot/plopp/mcplot.in create mode 100644 tools/Python/mcplot/plopp/test_mcplopp.py diff --git a/buildscripts/build_windows_mcstas b/buildscripts/build_windows_mcstas index 735be40487..e52814a463 100755 --- a/buildscripts/build_windows_mcstas +++ b/buildscripts/build_windows_mcstas @@ -43,6 +43,7 @@ export MCCODE_USE_LEGACY_DESTINATIONS=ON ./mkdist mcstas-tools-matlab-mcplot $1 tools/matlab/mcplot/ "" mingw64 "" -- nsis64 ./mkdist mcstas-tools-python-mcplot-pyqtgraph $1 tools/Python/mcplot/pyqtgraph/ "" mingw64 "" -- nsis64 ./mkdist mcstas-tools-python-mcplot-matplotlib $1 tools/Python/mcplot/matplotlib/ "" mingw64 "" -- nsis64 +./mkdist mcstas-tools-python-mcplot-plopp $1 tools/Python/mcplot/plopp/ "" mingw64 "" -- nsis64 ./mkdist mcstas-tools-python-mcplot-html $1 tools/Python/mcplot/html/ "" mingw64 "" -- nsis64 ./mkdist mcstas-tools-python-mcplot-terminal $1 tools/Python/mcplot/terminal/ "" mingw64 "" -- nsis64 ./mkdist mcstas-tools-python-mcrun $1 tools/Python/mcrun/ "" mingw64 "" -- nsis64 @@ -54,6 +55,7 @@ export MCCODE_USE_LEGACY_DESTINATIONS=ON ./mkdist mcstas-tools-python-mcdisplay-webgl-classic $1 tools/Python/mcdisplay/webgl-classic/ "" mingw64 "" -- nsis64 ./mkdist mcstas-tools-python-mcdisplay-pyqtgraph $1 tools/Python/mcdisplay/pyqtgraph/ "" mingw64 "" -- nsis64 ./mkdist mcstas-tools-python-mcdisplay-matplotlib $1 tools/Python/mcdisplay/matplotlib/ "" mingw64 "" -- nsis64 +./mkdist mcstas-tools-python-mcdisplay-plopp $1 tools/Python/mcdisplay/plopp/ "" mingw64 "" -- nsis64 ./mkdist mcstas-tools-python-mcdisplay-mantid $1 tools/Python/mcdisplay/mantid_xml/ "" mingw64 "" -- nsis64 ./mkdist mcstas-tools-python-mcdisplay-cad $1 tools/Python/mcdisplay/cad/ "" mingw64 "" -- nsis64 ./mkdist mcstas-manuals $1 docpkg/manuals/mcstas/ "" mingw64 "" -- nsis64 diff --git a/buildscripts/build_windows_mcxtrace b/buildscripts/build_windows_mcxtrace index 6d47af39b7..d407fb44ac 100755 --- a/buildscripts/build_windows_mcxtrace +++ b/buildscripts/build_windows_mcxtrace @@ -44,6 +44,7 @@ export MCCODE_USE_LEGACY_DESTINATIONS=ON ./mkdist mcxtrace-tools-matlab-mxplot $1 tools/matlab/mcplot/ "" mingw64 "" -- nsis64 ./mkdist mcxtrace-tools-python-mccodelib $1 tools/Python/mccodelib/ "" mingw64 "" -- nsis64 ./mkdist mcxtrace-tools-python-mxplot-matplotlib $1 tools/Python/mcplot/matplotlib/ "" mingw64 "" -- nsis64 +./mkdist mcxtrace-tools-python-mxplot-plopp $1 tools/Python/mcplot/plopp/ "" mingw64 "" -- nsis64 ./mkdist mcxtrace-tools-python-mxplot-pyqtgraph $1 tools/Python/mcplot/pyqtgraph/ "" mingw64 "" -- nsis64 ./mkdist mcxtrace-tools-python-mxplot-html $1 tools/Python/mcplot/html/ "" mingw64 "" -- nsis64 ./mkdist mcxtrace-tools-python-mxplot-terminal $1 tools/Python/mcplot/terminal/ "" mingw64 "" -- nsis64 @@ -52,6 +53,7 @@ export MCCODE_USE_LEGACY_DESTINATIONS=ON ./mkdist mcxtrace-tools-python-mxgui $1 tools/Python/mcgui/ "" mingw64 "" -- nsis64 ./mkdist mcxtrace-tools-python-mxdisplay-pyqtgraph $1 tools/Python/mcdisplay/pyqtgraph/ "" mingw64 "" -- nsis64 ./mkdist mcxtrace-tools-python-mxdisplay-matplotlib $1 tools/Python/mcdisplay/matplotlib/ "" mingw64 "" -- nsis64 +./mkdist mcxtrace-tools-python-mxdisplay-plopp $1 tools/Python/mcdisplay/plopp/ "" mingw64 "" -- nsis64 ./mkdist mcxtrace-tools-python-mxdisplay-webgl $1 tools/Python/mcdisplay/webgl/ "" mingw64 "" -- nsis64 ./mkdist mcxtrace-tools-python-mxdisplay-webgl-classic $1 tools/Python/mcdisplay/webgl-classic/ "" mingw64 "" -- nsis64 ./mkdist mcxtrace-manuals $1 docpkg/manuals/mcxtrace/ "" mingw64 "o" -- nsis64 diff --git a/cmake/Modules/InstallMCCODE.cmake b/cmake/Modules/InstallMCCODE.cmake index d15aad80a1..f10afa1548 100644 --- a/cmake/Modules/InstallMCCODE.cmake +++ b/cmake/Modules/InstallMCCODE.cmake @@ -415,7 +415,7 @@ macro(installMCCODE) install(PROGRAMS ${WORK}/support/${FLAVOR}-labenv.bat DESTINATION "${DEST_BINDIR}") # Python/Perl related batches special handling - foreach (name run.bat doc.bat test.bat viewtest.bat resplot.bat plot.bat coplot.bat plotdiff.bat display.bat gui.bat guistart.bat plot-pyqtgraph.bat coplot-pyqtgraph.bat plotdiff-pyqtgraph.bat plot-matplotlib.bat coplot-matplotlib.bat plotdiff-matplotlib.bat plot-matlab.bat plot-html.bat plot-terminal.bat coplot-html.bat plotdiff-html.bat display-webgl.bat display-webgl-classic.bat display-pyqtgraph.bat display-cad.bat display-matplotlib.bat display-mantid.bat display-matlab.bat) + foreach (name run.bat doc.bat test.bat viewtest.bat resplot.bat plot.bat coplot.bat plotdiff.bat display.bat gui.bat guistart.bat plot-pyqtgraph.bat coplot-pyqtgraph.bat plotdiff-pyqtgraph.bat plot-matplotlib.bat coplot-matplotlib.bat plotdiff-matplotlib.bat plot-matlab.bat plot-html.bat plot-terminal.bat coplot-html.bat plotdiff-html.bat display-webgl.bat display-webgl-classic.bat display-pyqtgraph.bat display-cad.bat display-matplotlib.bat display-mantid.bat display-matlab.bat plot-plopp.bat display-plopp.bat) configure_file( cmake/support/run-scripts/${name}.in work/support/${MCCODE_PREFIX}${name} diff --git a/cmake/support/run-scripts/display-plopp.bat.in b/cmake/support/run-scripts/display-plopp.bat.in new file mode 100644 index 0000000000..95b28db4b6 --- /dev/null +++ b/cmake/support/run-scripts/display-plopp.bat.in @@ -0,0 +1,6 @@ +@echo off +@set BINDIR=%~dp0 +@CALL %BINDIR%\@FLAVOR@env.bat +@SET PATH=%BINDIR%\@MCCODE_RELPATH_BINDIR2TOOLDIR@\Python\@MCCODE_PREFIX@display\plopp;%PATH% +@python %BINDIR%\@MCCODE_RELPATH_BINDIR2TOOLDIR@\Python\@MCCODE_PREFIX@display\plopp\mcdisplopp.py %* +@exit diff --git a/cmake/support/run-scripts/plot-plopp.bat.in b/cmake/support/run-scripts/plot-plopp.bat.in new file mode 100644 index 0000000000..a1579fae49 --- /dev/null +++ b/cmake/support/run-scripts/plot-plopp.bat.in @@ -0,0 +1,6 @@ +@echo off +@set BINDIR=%~dp0 +@CALL %BINDIR%\@FLAVOR@env.bat +@SET PATH=%BINDIR%\@MCCODE_RELPATH_BINDIR2TOOLDIR@\Python\@MCCODE_PREFIX@plot\plopp;%PATH% +@python %BINDIR%\@MCCODE_RELPATH_BINDIR2TOOLDIR@\Python\@MCCODE_PREFIX@plot\plopp\mcplopp.py %* +@exit diff --git a/meta-pkgs/windows/McStas-metapackage64-MinGW.iss b/meta-pkgs/windows/McStas-metapackage64-MinGW.iss index fd0bceec3b..46a0c86372 100644 --- a/meta-pkgs/windows/McStas-metapackage64-MinGW.iss +++ b/meta-pkgs/windows/McStas-metapackage64-MinGW.iss @@ -45,6 +45,7 @@ Source: "dist\mcstas-tools-python-mcgui-NSIS64-@VERSION@-mingw64.exe"; DestDir: Source: "dist\mcstas-tools-python-mccodelib-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "dist\mcstas-tools-python-mcplot-pyqtgraph-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "dist\mcstas-tools-python-mcplot-matplotlib-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" +Source: "dist\mcstas-tools-python-mcplot-plopp-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "dist\mcstas-tools-python-mcplot-html-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "dist\mcstas-tools-python-mcplot-terminal-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "dist\mcstas-tools-matlab-mcplot-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" @@ -53,6 +54,7 @@ Source: "dist\mcstas-tools-python-mcdisplay-webgl-classic-NSIS64-@VERSION@-mingw Source: "dist\mcstas-tools-python-mcdisplay-cad-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "dist\mcstas-tools-python-mcdisplay-pyqtgraph-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "dist\mcstas-tools-python-mcdisplay-matplotlib-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" +Source: "dist\mcstas-tools-python-mcdisplay-plopp-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "dist\mcstas-tools-python-mcdisplay-mantid-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "dist\mcstas-tools-python-mcdoc-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "Support\micromamba.exe"; DestDir: "{tmp}" @@ -69,6 +71,7 @@ Filename: "{tmp}\mcstas-tools-python-mcgui-NSIS64-@VERSION@-mingw64.exe"; Parame Filename: "{tmp}\mcstas-tools-python-mccodelib-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\mcstas-tools-python-mcplot-pyqtgraph-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\mcstas-tools-python-mcplot-matplotlib-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" +Filename: "{tmp}\mcstas-tools-python-mcplot-plopp-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\mcstas-tools-python-mcplot-html-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\mcstas-tools-python-mcplot-terminal-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\mcstas-tools-matlab-mcplot-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" @@ -77,6 +80,7 @@ Filename: "{tmp}\mcstas-tools-python-mcdisplay-webgl-classic-NSIS64-@VERSION@-mi Filename: "{tmp}\mcstas-tools-python-mcdisplay-cad-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\mcstas-tools-python-mcdisplay-pyqtgraph-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\mcstas-tools-python-mcdisplay-matplotlib-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" +Filename: "{tmp}\mcstas-tools-python-mcdisplay-plopp-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\mcstas-tools-python-mcdisplay-mantid-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\mcstas-tools-python-mcdoc-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\docupdate.bat"; diff --git a/meta-pkgs/windows/McXtrace-metapackage64-MinGW.iss b/meta-pkgs/windows/McXtrace-metapackage64-MinGW.iss index d55b31d4e8..dd8bc8d228 100644 --- a/meta-pkgs/windows/McXtrace-metapackage64-MinGW.iss +++ b/meta-pkgs/windows/McXtrace-metapackage64-MinGW.iss @@ -44,11 +44,13 @@ Source: "dist\mcxtrace-tools-python-mxgui-NSIS64-@VERSION@-mingw64.exe"; DestDir Source: "dist\mcxtrace-tools-python-mccodelib-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "dist\mcxtrace-tools-python-mxplot-pyqtgraph-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "dist\mcxtrace-tools-python-mxplot-matplotlib-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" +Source: "dist\mcxtrace-tools-python-mxplot-plopp-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "dist\mcxtrace-tools-python-mxplot-html-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "dist\mcxtrace-tools-python-mxplot-terminal-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "dist\mcxtrace-tools-python-mxdisplay-webgl-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "dist\mcxtrace-tools-python-mxdisplay-pyqtgraph-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "dist\mcxtrace-tools-python-mxdisplay-matplotlib-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" +Source: "dist\mcxtrace-tools-python-mxdisplay-plopp-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "dist\mcxtrace-tools-python-mxdoc-NSIS64-@VERSION@-mingw64.exe"; DestDir: "{tmp}" Source: "Support\micromamba.exe"; DestDir: "{tmp}" @@ -63,11 +65,13 @@ Filename: "{tmp}\mcxtrace-tools-python-mxgui-NSIS64-@VERSION@-mingw64.exe"; Para Filename: "{tmp}\mcxtrace-tools-python-mccodelib-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\mcxtrace-tools-python-mxplot-pyqtgraph-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\mcxtrace-tools-python-mxplot-matplotlib-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" +Filename: "{tmp}\mcxtrace-tools-python-mxplot-plopp-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\mcxtrace-tools-python-mxplot-html-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\mcxtrace-tools-python-mxplot-terminal-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\mcxtrace-tools-python-mxdisplay-webgl-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\mcxtrace-tools-python-mxdisplay-pyqtgraph-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\mcxtrace-tools-python-mxdisplay-matplotlib-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" +Filename: "{tmp}\mcxtrace-tools-python-mxdisplay-plopp-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\mcxtrace-tools-python-mxdoc-NSIS64-@VERSION@-mingw64.exe"; Parameters: "/S" Filename: "{tmp}\docupdate.bat"; diff --git a/meta-pkgs/windows/environment.yml b/meta-pkgs/windows/environment.yml index 8cf82f8f05..376bca6498 100644 --- a/meta-pkgs/windows/environment.yml +++ b/meta-pkgs/windows/environment.yml @@ -40,6 +40,8 @@ dependencies: - jupytext - jupyterlab - ipympl + - scipp + - plopp - jinja2 - mslex - typish diff --git a/tools/Python/mcdisplay/CMakeLists.txt b/tools/Python/mcdisplay/CMakeLists.txt index 4f49d49a28..f8ed79875d 100644 --- a/tools/Python/mcdisplay/CMakeLists.txt +++ b/tools/Python/mcdisplay/CMakeLists.txt @@ -7,3 +7,4 @@ add_subdirectory(pyqtgraph) add_subdirectory(webgl) add_subdirectory(webgl-classic) add_subdirectory(cad) +add_subdirectory(plopp) diff --git a/tools/Python/mcdisplay/plopp/CMakeLists.txt b/tools/Python/mcdisplay/plopp/CMakeLists.txt new file mode 100644 index 0000000000..b5dad85cc1 --- /dev/null +++ b/tools/Python/mcdisplay/plopp/CMakeLists.txt @@ -0,0 +1,77 @@ +cmake_minimum_required(VERSION 3.19) +cmake_policy(VERSION 3.17.0) + +# This will install McStas or McXtrace mc/mxdisplay-plopp +project(python-tools-mcdisplay-plopp C) + +message(STATUS "Configure ${CMAKE_PROJECT_NAME} ${FLAVOR} ${PROJECT_NAME}") + +# Choose between McStas or McXtrace +option(BUILD_MCSTAS "Choose the McStas flavor" off) +option(BUILD_MCXTRACE "Choose the McXtrace flavor (trumps BUILD_MCSTAS)" Off) + +# Set module path +set(CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH}" "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules/") + +# Set McCode values (from mkdist or defaults) +include(MCUtil) + +if (${BUILD_MCXTRACE}) + set(FLAVOR "mcxtrace") + set(CPACK_PACKAGE_HOMEPAGE_URL "http://mcxtrace.org/") +elseif(${BUILD_MCSTAS}) + set(FLAVOR "mcstas") + set(CPACK_PACKAGE_HOMEPAGE_URL "http://mcstas.org/") +else() + message(FATAL_ERROR "No flavor specified!\n" + "Please use either -DBUILD_MCSTAS=1 or -DBUILD_MCXTRACE=1") +endif() + +setupMCCODE("${FLAVOR}") + +# Select prefix +set(P "${MCCODE_PREFIX}") + +set(TOOLS_NAME "Python/${P}display/plopp") + +# CPack configuration +set(CPACK_PACKAGE_NAME "${FLAVOR}-tools-python-${P}display-plopp") +set(CPACK_RESOURCE_FilE_LICENSE "${PROJECT_SOURCE_DIR}/COPYING") +set(CPACK_PACKAGE_CONTACT "pkwi@fysik.dtu.dk") + +set(CPACK_PACKAGE_VERSION "${MCCODE_MAJOR}.${MCCODE_MINOR}.${MCCODE_PATCH}") +set(CPACK_PACKAGE_VERSION_MAJOR "${MCCODE_MAJOR}") +set(CPACK_PACKAGE_VERSION_MINOR "${MCCODE_MINOR}") +set(CPACK_PACKAGE_VERSION_PATCH "${MCCODE_PATCH}") + +# NSIS +set(NSIS_NAME "Plopp-based mcdisplay (mcdisplay-plopp), ${MCCODE_STRING}") +set(CPACK_NSIS_PACKAGE_NAME "${NSIS_NAME}") +set(CPACK_NSIS_DISPLAY_NAME "${NSIS_NAME}") +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "${NSIS_NAME}") + +include(CPack) + +set(WORK "${PROJECT_BINARY_DIR}/work") + +# Configure fallback script +configure_file("${CMAKE_CURRENT_SOURCE_DIR}/mcdisplay.in" "${WORK}/${P}display-plopp" @ONLY) + +# Main script - NOT renamed per flavor: the generated notebook imports it by this name +install( + PROGRAMS "${PROJECT_SOURCE_DIR}/mcdisplopp.py" + DESTINATION "${DEST_TOOLDIR}/${TOOLS_NAME}" + ) + +# Wrapper-scripts on windows are handled via +# cmake Modules/MCUtil +if(NOT WINDOWS) + add_custom_target( + "CREATE_${PROJECT_NAME}_SYMLINK" ALL DEPENDS "${WORK}/${P}display-plopp" + ) + + install( + PROGRAMS "${WORK}/${P}display-plopp" + DESTINATION ${DEST_BINDIR} + ) +endif() diff --git a/tools/Python/mcdisplay/plopp/COPYING b/tools/Python/mcdisplay/plopp/COPYING new file mode 100644 index 0000000000..f288702d2f --- /dev/null +++ b/tools/Python/mcdisplay/plopp/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/tools/Python/mcdisplay/plopp/cmake b/tools/Python/mcdisplay/plopp/cmake new file mode 120000 index 0000000000..a6ce9d7581 --- /dev/null +++ b/tools/Python/mcdisplay/plopp/cmake @@ -0,0 +1 @@ +../../../../cmake \ No newline at end of file diff --git a/tools/Python/mcdisplay/plopp/mcdisplay.in b/tools/Python/mcdisplay/plopp/mcdisplay.in new file mode 100644 index 0000000000..01390c045a --- /dev/null +++ b/tools/Python/mcdisplay/plopp/mcdisplay.in @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# Wrapper script for @P@display-plopp + +@MCCODE_BASH_STANDARD_PREAMBLE@ + +TOOL="mcdisplopp" +UTILDIR="${MCCODE_TOOLDIR}/Python/@P@display/plopp" + + +#NB: miniconda should be installed next to the tool folder: +if [ -d "${MCCODE_TOOLDIR}/../miniconda3" ]; then + source "${MCCODE_TOOLDIR}/../miniconda3/bin/activate" "${MCCODE_TOOLDIR}/../miniconda3" + export PATH=${MCCODE_TOOLDIR}/../miniconda3/bin/:$PATH +fi + +canrun() { + if ! [ -x "${UTILDIR}/${TOOL}.py" ]; then + exit 127; + fi + + modules="numpy scipp plopp ipywidgets ipympl" + cmd="" + for name in ${modules}; do + cmd="${cmd}import ${name}; " + done + python3 -c "${cmd}" +} + +if ( canrun ); then + python3 -u ${UTILDIR}/${TOOL}.py "$@" +else + @FLAVOR@_errmsg Failed to run Python ${TOOL} - missing dependencies\? Try: python3 -m pip install plopp ipympl jupyterlab +fi diff --git a/tools/Python/mcdisplay/plopp/mcdisplopp.py b/tools/Python/mcdisplay/plopp/mcdisplopp.py new file mode 100644 index 0000000000..33049a3c37 --- /dev/null +++ b/tools/Python/mcdisplay/plopp/mcdisplopp.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +''' +mcdisplopp: draw a McStas/McXtrace instrument and traced rays with plopp (scipp). + +UI: mcdisplopp.py [-n 100] [param=value ...] (opens JupyterLab) +Static: mcdisplopp.py [-n 100] [param=value ...] -o out.png +''' +import argparse +import json +import os +import subprocess +import sys +import warnings + +import numpy as np +import scipp as sc +import plopp as pp + +sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) +from mccodelib.mcdisplayutils import McDisplayReader +from mccodelib.instrgeom import Vector3d, DrawLine, DrawMultiline, DrawCircle + +warnings.filterwarnings('ignore', 'The input contains a coordinate with unsorted', RuntimeWarning) # polylines, not histograms +BREAK = [(np.nan,) * 3] # NaN between polylines lifts the pen, so one line per component + + +def _xyz(v): + return v.x, v.y, v.z + + +def _polylines(pls): + return np.array([p for pl in pls for p in list(pl) + BREAK]).reshape(-1, 3) + + +def trace(instr, n=100, params=()): + ''' run mcrun --trace (unset params take defaults); returns ({component: (N,3) xyz}, (M,3) ray xyz), NaN-separated ''' + reader = McDisplayReader(instr=instr, n=n, options=list(params), no_mpi=True, default=True) + instrument = reader.read_instrument() + bundle = reader.read_particles() + + geom = {} + for c in instrument.components: + pls = [] + for d in c.drawcalls: + # ponytail: wireframe primitives only (as mcdisplay-pyqtgraph); --trace=2 solids are skipped + pts = ([d.point_1, d.point_2] if isinstance(d, DrawLine) else d.points if isinstance(d, DrawMultiline) + else d.get_points_on_circle() if isinstance(d, DrawCircle) else None) + if pts: + pls.append([_xyz(c.transform.apply(p)) for p in pts]) + if pls: + geom[c.name] = _polylines(pls) + + tf = {c.name: c.transform for c in instrument.components} + ray_pls = [[_xyz(tf[g.compname].apply(Vector3d(*e.args[:3]))) for g in story.groups if g.compname in tf + for e in g.events] for story in (bundle.rays if bundle else [])] + return geom, _polylines(ray_pls) + + +def _projection(xyz, h, v): + ''' 1D DataArray: values = vertical axis, coord = horizontal axis (McStas: z beam, y up) ''' + ax = 'xyz' + return sc.DataArray(sc.array(dims=[h], values=xyz[:, ax.index(v)], unit='m'), + coords={h: sc.array(dims=[h], values=xyz[:, ax.index(h)], unit='m')}) + + +def view(geom, rays): + ''' top (z-x) above side (z-y) projection; one colour per component, rays in grey ''' + z = np.concatenate([rays[:, 2]] + [xyz[:, 2] for xyz in geom.values()]) + pad = 0.02 * (np.nanmax(z) - np.nanmin(z)) # plopp's autoscale overshoots on the NaN separators + figs = [] + for v in 'xy': + lines = {'rays': _projection(rays, 'z', v)} # first, so components draw on top + lines.update({name: _projection(xyz, 'z', v) for name, xyz in geom.items()}) + figs.append(pp.plot(lines, linestyle='-', marker='', legend=False, + color={'rays': 'lightgrey'}, ylabel=f'{v} [m]', title=f'z-{v}', + xmin=np.nanmin(z) - pad, xmax=np.nanmax(z) + pad)) + return figs[0] / figs[1] + + +def ui(instr, n=100, params=''): + ''' Jupyter (%matplotlib widget): edit params / ray count, re-trace on click ''' + import ipywidgets as w + from IPython.display import display + pars = w.Text(value=params, description='params', placeholder='lambda=2.36 ...', layout={'width': '40em'}) + rays = w.IntText(value=n, description='rays') + go = w.Button(description='Trace', button_style='primary') + out = w.Output() + + def run(_=None): + go.disabled = True + out.clear_output(wait=True) + try: + with out: + display(view(*trace(instr, rays.value, pars.value.split()))) + finally: + go.disabled = False + go.on_click(run) + run() + return w.VBox([w.HBox([pars, rays, go]), out]) + + +def launch(call): + ''' write a one-cell notebook running `call` next to this tool's import, open it in JupyterLab ''' + src = f"%matplotlib widget\nimport sys; sys.path.insert(0, {os.path.dirname(os.path.abspath(__file__))!r})\n{call}" + nb = {'nbformat': 4, 'nbformat_minor': 4, 'metadata': {'kernelspec': {'name': 'python3', 'display_name': 'Python 3', 'language': 'python'}}, + 'cells': [{'cell_type': 'code', 'metadata': {}, 'execution_count': None, 'outputs': [], 'source': src}]} + name = os.path.splitext(os.path.basename(__file__))[0] + '.ipynb' + with open(name, 'w') as f: + json.dump(nb, f) + print(f'wrote {name}; run its cell in JupyterLab') + subprocess.run([sys.executable, '-m', 'jupyter', 'lab', name]) + + +def main(): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument('instr', help='.instr or compiled instrument') + p.add_argument('params', nargs='*', help='instrument parameters, name=value') + p.add_argument('-n', type=int, default=100, help='number of rays to trace') + p.add_argument('-o', '--output', help='write a static png/pdf/svg instead of opening the UI') + args = p.parse_args() + if not args.output: + return launch(f'import mcdisplopp; mcdisplopp.ui({os.path.abspath(args.instr)!r}, {args.n}, {" ".join(args.params)!r})') + + view(*trace(args.instr, args.n, args.params)).save(args.output) + print(f'saved {args.output}') + + +if __name__ == '__main__': + main() diff --git a/tools/Python/mcdisplay/plopp/test_mcdisplopp.py b/tools/Python/mcdisplay/plopp/test_mcdisplopp.py new file mode 100644 index 0000000000..7240f0f4a0 --- /dev/null +++ b/tools/Python/mcdisplay/plopp/test_mcdisplopp.py @@ -0,0 +1,9 @@ +import numpy as np +from mcdisplopp import _polylines, _projection + +xyz = _polylines([[(0, 0, 0), (1, 2, 3)], [(4, 5, 6)]]) +assert xyz.shape == (5, 3) and np.isnan(xyz[2]).all() and np.isnan(xyz[4]).all() +assert _polylines([]).shape == (0, 3) # -n 0: no rays +da = _projection(xyz, 'z', 'x') # z horizontal, x vertical +assert da.dims == ('z',) and da.coords['z'].values[1] == 3 and da.values[1] == 1 +print('ok') diff --git a/tools/Python/mcplot/CMakeLists.txt b/tools/Python/mcplot/CMakeLists.txt index 28beebd27f..fac654ae25 100644 --- a/tools/Python/mcplot/CMakeLists.txt +++ b/tools/Python/mcplot/CMakeLists.txt @@ -5,3 +5,4 @@ add_subdirectory(matplotlib) add_subdirectory(pyqtgraph) add_subdirectory(html) add_subdirectory(terminal) +add_subdirectory(plopp) diff --git a/tools/Python/mcplot/plopp/CMakeLists.txt b/tools/Python/mcplot/plopp/CMakeLists.txt new file mode 100644 index 0000000000..1f8cc29bee --- /dev/null +++ b/tools/Python/mcplot/plopp/CMakeLists.txt @@ -0,0 +1,77 @@ +cmake_minimum_required(VERSION 3.19) +cmake_policy(VERSION 3.17.0) + +# This will install McStas or McXtrace mc/mxplot-plopp +project(python-tools-mcplot-plopp C) + +message(STATUS "Configure ${CMAKE_PROJECT_NAME} ${FLAVOR} ${PROJECT_NAME}") + +# Choose between McStas or McXtrace +option(BUILD_MCSTAS "Choose the McStas flavor" off) +option(BUILD_MCXTRACE "Choose the McXtrace flavor (trumps BUILD_MCSTAS)" Off) + +# Set module path +set(CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH}" "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules/") + +# Set McCode values (from mkdist or defaults) +include(MCUtil) + +if (${BUILD_MCXTRACE}) + set(FLAVOR "mcxtrace") + set(CPACK_PACKAGE_HOMEPAGE_URL "http://mcxtrace.org/") +elseif(${BUILD_MCSTAS}) + set(FLAVOR "mcstas") + set(CPACK_PACKAGE_HOMEPAGE_URL "http://mcstas.org/") +else() + message(FATAL_ERROR "No flavor specified!\n" + "Please use either -DBUILD_MCSTAS=1 or -DBUILD_MCXTRACE=1") +endif() + +setupMCCODE("${FLAVOR}") + +# Select prefix +set(P "${MCCODE_PREFIX}") + +set(TOOLS_NAME "Python/${P}plot/plopp") + +# CPack configuration +set(CPACK_PACKAGE_NAME "${FLAVOR}-tools-python-${P}plot-plopp") +set(CPACK_RESOURCE_FilE_LICENSE "${PROJECT_SOURCE_DIR}/COPYING") +set(CPACK_PACKAGE_CONTACT "pkwi@fysik.dtu.dk") + +set(CPACK_PACKAGE_VERSION "${MCCODE_MAJOR}.${MCCODE_MINOR}.${MCCODE_PATCH}") +set(CPACK_PACKAGE_VERSION_MAJOR "${MCCODE_MAJOR}") +set(CPACK_PACKAGE_VERSION_MINOR "${MCCODE_MINOR}") +set(CPACK_PACKAGE_VERSION_PATCH "${MCCODE_PATCH}") + +# NSIS +set(NSIS_NAME "Plopp-based mcplot (mcplot-plopp), ${MCCODE_STRING}") +set(CPACK_NSIS_PACKAGE_NAME "${NSIS_NAME}") +set(CPACK_NSIS_DISPLAY_NAME "${NSIS_NAME}") +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "${NSIS_NAME}") + +include(CPack) + +set(WORK "${PROJECT_BINARY_DIR}/work") + +# Configure fallback script +configure_file("${CMAKE_CURRENT_SOURCE_DIR}/mcplot.in" "${WORK}/${P}plot-plopp" @ONLY) + +# Main script - NOT renamed per flavor: the generated notebook imports it by this name +install( + PROGRAMS "${PROJECT_SOURCE_DIR}/mcplopp.py" + DESTINATION "${DEST_TOOLDIR}/${TOOLS_NAME}" + ) + +# Wrapper-scripts on windows are handled via +# cmake Modules/MCUtil +if(NOT WINDOWS) + add_custom_target( + "CREATE_${PROJECT_NAME}_SYMLINK" ALL DEPENDS "${WORK}/${P}plot-plopp" + ) + + install( + PROGRAMS "${WORK}/${P}plot-plopp" + DESTINATION ${DEST_BINDIR} + ) +endif() diff --git a/tools/Python/mcplot/plopp/COPYING b/tools/Python/mcplot/plopp/COPYING new file mode 100644 index 0000000000..f288702d2f --- /dev/null +++ b/tools/Python/mcplot/plopp/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/tools/Python/mcplot/plopp/cmake b/tools/Python/mcplot/plopp/cmake new file mode 120000 index 0000000000..a6ce9d7581 --- /dev/null +++ b/tools/Python/mcplot/plopp/cmake @@ -0,0 +1 @@ +../../../../cmake \ No newline at end of file diff --git a/tools/Python/mcplot/plopp/mcplopp.py b/tools/Python/mcplot/plopp/mcplopp.py new file mode 100644 index 0000000000..a867fb5ff1 --- /dev/null +++ b/tools/Python/mcplot/plopp/mcplopp.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +''' +mcplopp: plot McStas/McXtrace output with plopp (scipp). + +UI: mcplopp.py (opens JupyterLab) +Static: mcplopp.py -o out.png [--log] +''' +import argparse +import json +import math +import os +import re +import subprocess +import sys + +import numpy as np +import scipp as sc +import plopp as pp + +sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) +from mccodelib.mcplotloader import McCodeDataLoader, Data1D, Data2D +from mccodelib.plotgraph import PNMultiple + +UNITS = {'AA': 'angstrom', 'Angs': 'angstrom', 'meV': 'meV', 'deg': 'deg', 'us': 'us', 'cm': 'cm', 'm': 'm', 's': 's'} + + +def _edges(label, lo, hi, n): + ''' bin-edge coord from an axis label like "Wavelength [AA]"; unknown units stay in the label ''' + m = re.search(r'\s*\[(.*?)\]', label) + unit = UNITS.get(m.group(1)) if m else None + dim = label.replace(m.group(0), '').strip() if unit else label.strip() + return dim, sc.linspace(dim, lo, hi, n + 1, unit=unit or '') + + +def to_dataarray(d): + ''' Data1D/Data2D -> DataArray with bin edges; 0D/event lists -> None ''' + if isinstance(d, Data1D): + x, ex = _edges(d.xlabel, *d.xlimits, len(d.yvals)) + da = sc.DataArray(sc.array(dims=[x], values=d.yvals, variances=np.square(d.y_err_vals)), coords={x: ex}) + elif isinstance(d, Data2D): + z = np.array(d.zvals) # rows are y: (ny, nx), as in the matplotlib frontend + x, ex = _edges(d.xlabel, *d.xlimits[:2], z.shape[1]) + y, ey = _edges(d.ylabel, *d.xlimits[2:], z.shape[0]) + if y == x: + y += ' (y)' + ey = ey.rename_dims({x: y}) + # ponytail: no variances for 2D, mcplotloader skips the "# Errors" block + da = sc.DataArray(sc.array(dims=[y, x], values=z), coords={x: ex, y: ey}) + else: + return None + da.name = 'I' # colorbar/y label; the title goes in the load() key + return da + + +def load(path): + ''' {name: DataArray}. Scans stack each monitor over the scan parameter (1D->2D, 2D->3D). ''' + loader = McCodeDataLoader(simfile=path) + loader.load() + root = loader.plot_graph + secs = root.get_secondaries() + if not (secs and isinstance(secs[0], PNMultiple)): # single run or single monitor + ds = root.getdata_lst() + return {f'{d.title.strip()} [{i}]': to_dataarray(d) for i, d in enumerate(ds) if isinstance(d, (Data1D, Data2D))} + + scan = root.getdata_idx(0) # mccode.dat curve: xvals are the scan points + out = {} + for i, sec in enumerate(secs): + steps = [to_dataarray(d) for d in sec.getdata_lst()] + if steps[0] is None: + continue + da = sc.concat(steps, dim=scan.xvar) + # ponytail: failed scan steps leave no subfolder; fall back to step index if counts differ + vals = scan.xvals if len(scan.xvals) == len(steps) else np.arange(len(steps)) + da.coords[scan.xvar] = sc.array(dims=[scan.xvar], values=vals) + out[f'{sec.getdata_idx(0).title.strip()} [{i}]'] = da + return out + + +def scan_slicer(da, log=False): + ''' Jupyter (ipympl) only: step through a stacked scan monitor ''' + return pp.slicer(da, keep=list(da.dims[1:]), # load() puts the scan dim first + enable_player=True, mode='single', autoscale=log, norm='log' if log else 'linear') + + +def ui(path): + ''' Jupyter (%matplotlib widget): pick a monitor; scans get the step player, log via the plot toolbar ''' + import ipywidgets as w + from IPython.display import display + das = load(path) + pick = w.Dropdown(options=list(das), description='monitor', layout={'width': '40em'}) + out = w.Output() + + def show(_=None): # ponytail: one figure at a time, so 100+ monitor instruments stay responsive + da = das[pick.value] + out.clear_output(wait=True) + with out: + display(scan_slicer(da) if not da.coords.is_edges(da.dims[0]) else pp.plot(da, title=pick.value)) + pick.observe(show, 'value') + show() + return w.VBox([pick, out]) + + +def launch(call): + ''' write a one-cell notebook running `call` next to this tool's import, open it in JupyterLab ''' + src = f"%matplotlib widget\nimport sys; sys.path.insert(0, {os.path.dirname(os.path.abspath(__file__))!r})\n{call}" + nb = {'nbformat': 4, 'nbformat_minor': 4, 'metadata': {'kernelspec': {'name': 'python3', 'display_name': 'Python 3', 'language': 'python'}}, + 'cells': [{'cell_type': 'code', 'metadata': {}, 'execution_count': None, 'outputs': [], 'source': src}]} + name = os.path.splitext(os.path.basename(__file__))[0] + '.ipynb' + with open(name, 'w') as f: + json.dump(nb, f) + print(f'wrote {name}; run its cell in JupyterLab') + subprocess.run([sys.executable, '-m', 'jupyter', 'lab', name]) + + +def figures(das, log=False): + ''' static figures; 3D scan monitors become one tile per step ''' + norm = 'log' if log else 'linear' + figs = [] + for name, da in das.items(): + if da.ndim == 3: + scan_dim = da.dims[0] + figs += [pp.plot(da[scan_dim, j], norm=norm, title=f'{name} {scan_dim}={da.coords[scan_dim][j].value:g}') + for j in range(da.sizes[scan_dim])] + else: + figs.append(pp.plot(da, norm=norm, title=name)) + return figs + + +def main(): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument('simfile', nargs='?', default='.', help='output dir, mccode.sim, or a monitor file') + p.add_argument('-o', '--output', help='write a static png/pdf/svg instead of opening the UI') + p.add_argument('--log', action='store_true', help='log intensity scale') + args = p.parse_args() + if not args.output: + return launch(f'import mcplopp; mcplopp.ui({os.path.abspath(args.simfile)!r})') + + figs = figures(load(args.simfile), args.log) + ncols = math.ceil(math.sqrt(len(figs))) + nrows = math.ceil(len(figs) / ncols) + tiled = pp.tiled(nrows, ncols, figsize=(4 * ncols, 3 * nrows)) + for k, f in enumerate(figs): + tiled[k // ncols, k % ncols] = f + tiled.save(args.output) + print(f'saved {args.output}') + + +if __name__ == '__main__': + main() diff --git a/tools/Python/mcplot/plopp/mcplot.in b/tools/Python/mcplot/plopp/mcplot.in new file mode 100644 index 0000000000..4708af5bce --- /dev/null +++ b/tools/Python/mcplot/plopp/mcplot.in @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# Wrapper script for @P@plot-plopp + +@MCCODE_BASH_STANDARD_PREAMBLE@ + +TOOL="mcplopp" +UTILDIR="${MCCODE_TOOLDIR}/Python/@P@plot/plopp" + + +#NB: miniconda should be installed next to the tool folder: +if [ -d "${MCCODE_TOOLDIR}/../miniconda3" ]; then + source "${MCCODE_TOOLDIR}/../miniconda3/bin/activate" "${MCCODE_TOOLDIR}/../miniconda3" + export PATH=${MCCODE_TOOLDIR}/../miniconda3/bin/:$PATH +fi + +canrun() { + if ! [ -x "${UTILDIR}/${TOOL}.py" ]; then + exit 127; + fi + + modules="numpy scipp plopp ipywidgets ipympl" + cmd="" + for name in ${modules}; do + cmd="${cmd}import ${name}; " + done + python3 -c "${cmd}" +} + +if ( canrun ); then + python3 -u ${UTILDIR}/${TOOL}.py "$@" +else + @FLAVOR@_errmsg Failed to run Python ${TOOL} - missing dependencies\? Try: python3 -m pip install plopp ipympl jupyterlab +fi diff --git a/tools/Python/mcplot/plopp/test_mcplopp.py b/tools/Python/mcplot/plopp/test_mcplopp.py new file mode 100644 index 0000000000..05af2d28f7 --- /dev/null +++ b/tools/Python/mcplot/plopp/test_mcplopp.py @@ -0,0 +1,13 @@ +from mcplopp import _edges, to_dataarray +from mccodelib.mcplotloader import Data2D + +dim, e = _edges('Wavelength [AA]', 0, 10, 20) +assert dim == 'Wavelength' and str(e.unit) == 'Å' and e.sizes == {dim: 21} +dim, e = _edges('TOF [\\gms]', 0, 1, 4) # unknown unit: kept in label, dimensionless +assert dim == 'TOF [\\gms]' and str(e.unit) == 'dimensionless' + +d = Data2D() # array_2d(3, 2): 2 rows (y) x 3 columns (x) +d.xlabel, d.ylabel, d.xlimits, d.zvals = 'x [cm]', 'y [cm]', (0, 3, 0, 2), [[1, 2, 3], [4, 5, 6]] +da = to_dataarray(d) +assert da.dims == ('y', 'x') and da.coords['x'].sizes == {'x': 4} and da['x', 2]['y', 1].value == 6 +print('ok') From 7cb4943b44b7415379a1798a28b77ac7e18c3936 Mon Sep 17 00:00:00 2001 From: Peter Willendrup Date: Tue, 13 Oct 2026 09:37:52 +0200 Subject: [PATCH 2/7] mcdisplay-plopp: 3D tube display in the UI The JupyterLab UI now draws the instrument in 3D with plopp's mesh3d (pythreejs) instead of the 2D projections: - Lines, multilines and circles become thin 6-sided tubes, with a low-poly sphere (icosahedron) at each corner where the polyline turns by more than ~20 deg. Line ends, straight joints and arc points get none, which keeps the mesh light - Components are coloured by index (tab20); rays are light grey tubes at half the radius - Tube radius = thickness x instrument bounding-box diagonal (default 2.5e-4, ~2 mm on BNL_H8). A thickness slider in the UI redraws the last trace without re-running mcrun - Circles are drawn with 24 points instead of mccodelib's default 60 (also used by the 2D view) -o FILE still writes the 2D z-x/z-y projections, since pythreejs cannot render without a browser. Tests: closed icosahedron, ring radius about the segment axis, mesh counts, and corner detection on an L-shaped line. The BNL_H8 UI (initial draw and slider redraw) runs in an executed notebook without errors; not yet viewed in a live browser session. Co-Authored-By: Claude Opus 5.5 --- tools/Python/mcdisplay/plopp/mcdisplopp.py | 71 +++++++++++++++++-- .../Python/mcdisplay/plopp/test_mcdisplopp.py | 16 +++++ 2 files changed, 80 insertions(+), 7 deletions(-) diff --git a/tools/Python/mcdisplay/plopp/mcdisplopp.py b/tools/Python/mcdisplay/plopp/mcdisplopp.py index 33049a3c37..fdac7beac4 100644 --- a/tools/Python/mcdisplay/plopp/mcdisplopp.py +++ b/tools/Python/mcdisplay/plopp/mcdisplopp.py @@ -2,8 +2,8 @@ ''' mcdisplopp: draw a McStas/McXtrace instrument and traced rays with plopp (scipp). -UI: mcdisplopp.py [-n 100] [param=value ...] (opens JupyterLab) -Static: mcdisplopp.py [-n 100] [param=value ...] -o out.png +UI: mcdisplopp.py [-n 100] [param=value ...] (opens JupyterLab, 3D) +Static: mcdisplopp.py [-n 100] [param=value ...] -o out.png (2D projections) ''' import argparse import json @@ -44,7 +44,7 @@ def trace(instr, n=100, params=()): for d in c.drawcalls: # ponytail: wireframe primitives only (as mcdisplay-pyqtgraph); --trace=2 solids are skipped pts = ([d.point_1, d.point_2] if isinstance(d, DrawLine) else d.points if isinstance(d, DrawMultiline) - else d.get_points_on_circle() if isinstance(d, DrawCircle) else None) + else d.get_points_on_circle(24) if isinstance(d, DrawCircle) else None) # 60 by default; 24 is round enough if pts: pls.append([_xyz(c.transform.apply(p)) for p in pts]) if pls: @@ -77,26 +77,83 @@ def view(geom, rays): return figs[0] / figs[1] +_G = (1 + 5 ** 0.5) / 2 # icosahedron: the sphere at each polyline vertex +ICO_V = np.array([(-1, _G, 0), (1, _G, 0), (-1, -_G, 0), (1, -_G, 0), (0, -1, _G), (0, 1, _G), + (0, -1, -_G), (0, 1, -_G), (_G, 0, -1), (_G, 0, 1), (-_G, 0, -1), (-_G, 0, 1)]) / np.hypot(1, _G) +ICO_F = np.array([(0, 11, 5), (0, 5, 1), (0, 1, 7), (0, 7, 10), (0, 10, 11), (1, 5, 9), (5, 11, 4), + (11, 10, 2), (10, 7, 6), (7, 1, 8), (3, 9, 4), (3, 4, 2), (3, 2, 6), (3, 6, 8), + (3, 8, 9), (4, 9, 5), (2, 4, 11), (6, 2, 10), (8, 6, 7), (9, 8, 1)]) + + +def _tubes(xyz, r, k=6): + ''' NaN-separated polylines -> (vertices, faces): a k-sided open cylinder per segment, a sphere per corner ''' + a, b = xyz[:-1], xyz[1:] + keep = np.isfinite(a).all(1) & np.isfinite(b).all(1) & (np.linalg.norm(b - a, axis=1) > 0) + a, b = a[keep], b[keep] + d = (b - a) / np.linalg.norm(b - a, axis=1, keepdims=True) + u = np.cross(d, np.where(abs(d[:, :1]) < 0.9, [1., 0, 0], [0., 1, 0])) # helper axis not parallel to d + u /= np.linalg.norm(u, axis=1, keepdims=True) + v = np.cross(d, u) + th = 2 * np.pi * np.arange(k) / k + ring = r * (np.cos(th)[None, :, None] * u[:, None] + np.sin(th)[None, :, None] * v[:, None]) # (n, k, 3) + cyl = np.concatenate([a[:, None] + ring, b[:, None] + ring], axis=1).reshape(-1, 3) + j, j1 = np.arange(k), (np.arange(k) + 1) % k + side = np.concatenate([np.stack([j, j1, k + j], 1), np.stack([j1, k + j1, k + j], 1)]) + cyl_f = (side[None] + 2 * k * np.arange(len(a))[:, None, None]).reshape(-1, 3) + + d1, d2 = xyz[1:-1] - xyz[:-2], xyz[2:] - xyz[1:-1] # joints only where the polyline turns > ~20 deg; + with np.errstate(invalid='ignore', divide='ignore'): # NaN breaks, ends and smooth arcs get none + cos = (d1 * d2).sum(1) / (np.linalg.norm(d1, axis=1) * np.linalg.norm(d2, axis=1)) + pts = xyz[1:-1][cos < 0.94] + sph = (pts[:, None] + r * ICO_V[None]).reshape(-1, 3) + sph_f = (ICO_F[None] + len(cyl) + 12 * np.arange(len(pts))[:, None, None]).reshape(-1, 3) + return np.concatenate([cyl, sph]), np.concatenate([cyl_f, sph_f]) + + +def view3d(geom, rays, thickness=2.5e-4): + ''' 3D (Jupyter/pythreejs): components as tubes coloured per component, rays as thinner grey tubes. + Tube radius = thickness x the instrument's bounding-box diagonal; rays get half of it ''' + allpts = np.concatenate([rays] + list(geom.values())) + r = thickness * np.linalg.norm(np.nanmax(allpts, 0) - np.nanmin(allpts, 0)) + parts = [(_tubes(xyz, r), i % 20) for i, xyz in enumerate(geom.values())] + [(_tubes(rays, r / 2), np.nan)] + verts, faces, cols, off = [], [], [], 0 + for (vv, ff), c in parts: + verts.append(vv), faces.append(ff + off), cols.append(np.full(len(vv), c, dtype=float)) + off += len(vv) + return pp.mesh3d(vertices=sc.vectors(dims=['vertices'], values=np.concatenate(verts), unit='m'), + faces=sc.array(dims=['faces', 'vertex'], values=np.concatenate(faces)), + vertexcolors=sc.array(dims=['vertices'], values=np.concatenate(cols)), + cmap='tab20', cmin=0, cmax=19, nan_color='lightgrey', figsize=(900, 600)) + + def ui(instr, n=100, params=''): - ''' Jupyter (%matplotlib widget): edit params / ray count, re-trace on click ''' + ''' Jupyter: 3D view; edit params / ray count, re-trace on click ''' import ipywidgets as w from IPython.display import display pars = w.Text(value=params, description='params', placeholder='lambda=2.36 ...', layout={'width': '40em'}) rays = w.IntText(value=n, description='rays') go = w.Button(description='Trace', button_style='primary') + thick = w.FloatLogSlider(value=2.5e-4, base=10, min=-5, max=-2, description='thickness', readout_format='.1e') out = w.Output() + last = {} + + def draw(_=None): # redraws the last trace, no mcrun + out.clear_output(wait=True) + with out: + display(view3d(*last['trace'], thick.value)) def run(_=None): go.disabled = True - out.clear_output(wait=True) try: with out: - display(view(*trace(instr, rays.value, pars.value.split()))) + last['trace'] = trace(instr, rays.value, pars.value.split()) + draw() finally: go.disabled = False go.on_click(run) + thick.observe(draw, 'value') run() - return w.VBox([w.HBox([pars, rays, go]), out]) + return w.VBox([w.HBox([pars, rays, go, thick]), out]) def launch(call): diff --git a/tools/Python/mcdisplay/plopp/test_mcdisplopp.py b/tools/Python/mcdisplay/plopp/test_mcdisplopp.py index 7240f0f4a0..a60f8e14e0 100644 --- a/tools/Python/mcdisplay/plopp/test_mcdisplopp.py +++ b/tools/Python/mcdisplay/plopp/test_mcdisplopp.py @@ -7,3 +7,19 @@ da = _projection(xyz, 'z', 'x') # z horizontal, x vertical assert da.dims == ('z',) and da.coords['z'].values[1] == 3 and da.values[1] == 1 print('ok') + +from collections import Counter +from mcdisplopp import _tubes, ICO_F, ICO_V +edges = Counter(tuple(sorted(e)) for f in ICO_F for e in ((f[0], f[1]), (f[1], f[2]), (f[2], f[0]))) +assert len(edges) == 30 and set(edges.values()) == {2} # closed icosahedron +assert np.allclose(np.linalg.norm(ICO_V, axis=1), 1) + +v, f = _tubes(xyz, r=0.1, k=6) # 1 valid segment (others hit NaN), no corners +assert v.shape == (2 * 6, 3) and f.shape == (2 * 6, 3) and f.max() == len(v) - 1 +vL, fL = _tubes(np.array([(0, 0, 0), (1, 0, 0), (1, 1, 0), (1, 2, 0.)]), r=0.1, k=6) # one 90 deg corner, one straight joint +assert vL.shape == (3 * 12 + 1 * 12, 3) and fL.shape == (3 * 12 + 1 * 20, 3) and np.allclose(vL[36:].mean(0), (1, 0, 0)) +a, b = np.array([0, 0, 0]), np.array([1, 2, 3]) +d = (b - a) / np.linalg.norm(b - a) +off = v[:12] - a +assert np.allclose(np.linalg.norm(off - np.outer(off @ d, d), axis=1), 0.1) # ring radius about the axis +print('ok tubes') From 1f04d4ecdacb67b98590cbad15bf71b87632c253 Mon Sep 17 00:00:00 2001 From: Peter Willendrup Date: Tue, 13 Oct 2026 11:02:10 +0200 Subject: [PATCH 3/7] mcdisplay-plopp: --trace=2 solids as 3D meshes, -y forwarding Trace in --trace=2 mode (was the McDisplayReader default, 1), so the runtime's 3D draw calls reach plopp: - cylinder (solid or hollow), cone, disc, annulus and sphere are swept around their axis n into triangle meshes (one _loft ring-stitching helper, 24 segments) - box (solid or hollow) is rotated so local +y lies along n; a hollow box is open along that axis - polyhedron JSON (OFF / polygon) is used as-is, with polygon faces fanned into triangles - line, multiline, circle and new_circle stay as thin tubes; solids take their component's colour in the 3D view, and the 2D -o view draws them as triangle outlines Conventions follow mcdisplay-webgl, the reference trace=2 renderer: shapes are centred on (x,y,z), a cone's apex is at +h/2 along n, and annulus's 5th argument is a ring width (as in webgl and matplotlib, although the runtime names it inner_radius; no shipped component calls annulus() directly). new_circle is drawn as a tube ring rather than webgl's 1 cm band. DrawPolygon is not handled; at trace=2 the runtime emits polygons as polyhedra. -y/--yes is forwarded to mcrun so the instrument uses defaults for unset parameters; this replaces auto-answering every stdin prompt. Without -y, mcrun prompts as usual. The UI always passes -y, because a widget cannot answer prompts. Tests: box placement and rotation, cylinder/cone extents, closed surfaces (vertices welded by position), polyhedron fan-out. Checked against a scratch instrument with Incoherent in every shape (bounding boxes match the parameters, including a hollow box rotated 30 deg) and BNL_H8 / Polygon_ESS_butterfly_image in the 2D view. The 3D UI runs without errors in an executed notebook; not yet viewed in a live browser session. Co-Authored-By: Claude Opus 5.5 --- tools/Python/mcdisplay/plopp/mcdisplopp.py | 179 +++++++++++++++--- .../Python/mcdisplay/plopp/test_mcdisplopp.py | 24 +++ 2 files changed, 172 insertions(+), 31 deletions(-) diff --git a/tools/Python/mcdisplay/plopp/mcdisplopp.py b/tools/Python/mcdisplay/plopp/mcdisplopp.py index fdac7beac4..105f286d48 100644 --- a/tools/Python/mcdisplay/plopp/mcdisplopp.py +++ b/tools/Python/mcdisplay/plopp/mcdisplopp.py @@ -3,7 +3,7 @@ mcdisplopp: draw a McStas/McXtrace instrument and traced rays with plopp (scipp). UI: mcdisplopp.py [-n 100] [param=value ...] (opens JupyterLab, 3D) -Static: mcdisplopp.py [-n 100] [param=value ...] -o out.png (2D projections) +Static: mcdisplopp.py [-n 100] [-y] [param=value ...] -o out.png (2D projections) ''' import argparse import json @@ -18,10 +18,12 @@ sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) from mccodelib.mcdisplayutils import McDisplayReader -from mccodelib.instrgeom import Vector3d, DrawLine, DrawMultiline, DrawCircle +from mccodelib.instrgeom import (Vector3d, DrawLine, DrawMultiline, DrawCircle, DrawNewCircle, DrawSphere, + DrawCone, DrawCylinder, DrawDisc, DrawAnnulus, DrawBox, DrawPolyhedron) warnings.filterwarnings('ignore', 'The input contains a coordinate with unsorted', RuntimeWarning) # polylines, not histograms BREAK = [(np.nan,) * 3] # NaN between polylines lifts the pen, so one line per component +K = 24 # segments around circles and solids of revolution def _xyz(v): @@ -29,26 +31,131 @@ def _xyz(v): def _polylines(pls): - return np.array([p for pl in pls for p in list(pl) + BREAK]).reshape(-1, 3) - - -def trace(instr, n=100, params=()): - ''' run mcrun --trace (unset params take defaults); returns ({component: (N,3) xyz}, (M,3) ray xyz), NaN-separated ''' - reader = McDisplayReader(instr=instr, n=n, options=list(params), no_mpi=True, default=True) + return np.array([p for pl in pls for p in list(pl) + BREAK], dtype=float).reshape(-1, 3) + + +def _frame(n): + ''' unit axis n plus two unit vectors u, v spanning the plane normal to it ''' + n = np.asarray(n, float) / np.linalg.norm(n) + u = np.cross(n, [1., 0, 0] if abs(n[0]) < 0.9 else [0., 1, 0]) + u /= np.linalg.norm(u) + return n, u, np.cross(n, u) + + +def _loft(rings, closed=False): + ''' (m, k, 3) stack of k-point rings -> (vertices, triangles) joining ring i to i+1 (and last to first) ''' + m, k = rings.shape[:2] + i, j = np.arange(m if closed else m - 1)[:, None], np.arange(k)[None] + a, b = i * k + j, i * k + (j + 1) % k + c, d = (i + 1) % m * k + j, (i + 1) % m * k + (j + 1) % k + return rings.reshape(-1, 3), np.stack([np.stack([a, b, d], -1), np.stack([a, d, c], -1)], 2).reshape(-1, 3) + + +def _revolve(c, n, rr, hh, closed=False): + ''' solid of revolution about axis n through c: profile points (radius rr, height hh along n) ''' + n, u, v = _frame(n) + th = 2 * np.pi * np.arange(K) / K + ring = np.cos(th)[:, None] * u + np.sin(th)[:, None] * v + rings = np.asarray(c, float) + np.asarray(hh, float)[:, None, None] * n + np.asarray(rr, float)[:, None, None] * ring + return _loft(rings, closed) + + +def _rot_y_to(n): + ''' rotation taking +y onto n (as three.js setFromUnitVectors, used by mcdisplay-webgl for boxes) ''' + n = np.asarray(n, float) / np.linalg.norm(n) + w, c = np.cross([0., 1, 0], n), n[1] + if c < -1 + 1e-9: + return np.diag([1., -1, -1]) + W = np.array([[0, -w[2], w[1]], [w[2], 0, -w[0]], [-w[1], w[0], 0]]) + return np.eye(3) + W + W @ W / (1 + c) + + +def _box(x, y, z, w, h, l, t, nx, ny, nz): + ''' box of size (w, h, l) about (x, y, z), local y turned onto n; t > 0: hollow, open along local y ''' + rect = lambda hx, hz, yy: [(-hx, yy, -hz), (hx, yy, -hz), (hx, yy, hz), (-hx, yy, hz)] + hx, hy, hz = w / 2, h / 2, l / 2 + if t > 0: + v, f = _loft(np.array([rect(hx - t, hz - t, -hy), rect(hx, hz, -hy), rect(hx, hz, hy), rect(hx - t, hz - t, hy)]), True) + else: + v, f = _loft(np.array([[(0, -hy, 0)] * 4, rect(hx, hz, -hy), rect(hx, hz, hy), [(0, hy, 0)] * 4])) + return v @ _rot_y_to((nx, ny, nz)).T + (x, y, z), f + + +def _polyhedron(js): + ''' OFF/polygon JSON from the runtime; polygon faces fanned into triangles ''' + d = json.loads(js) + tri = [(f[0], f[i], f[i + 1]) for face in d['faces'] for f in [face['face']] for i in range(1, len(f) - 1)] + return np.array(d['vertices'], float).reshape(-1, 3), np.array(tri, int).reshape(-1, 3) + + +def _wire(d): + ''' polyline (local coords) for the line-like draw calls, else None ''' + if isinstance(d, DrawLine): + return [_xyz(d.point_1), _xyz(d.point_2)] + if isinstance(d, DrawMultiline): + return [_xyz(p) for p in d.points] + if isinstance(d, DrawCircle): + return [_xyz(p) for p in d.get_points_on_circle(K + 1)] + if isinstance(d, DrawNewCircle): + x, y, z, r, *n = d.args + n, u, v = _frame(n) + th = 2 * np.pi * np.arange(K + 1) / K + return (np.array([x, y, z]) + r * (np.cos(th)[:, None] * u + np.sin(th)[:, None] * v)).tolist() + + +def _solid(d): + ''' (vertices, triangles) in local coords for --trace=2 solids, else None. Centred shapes along n, as + mcdisplay-webgl (the annulus "inner_radius" is a ring width there and in mcdisplay-matplotlib) ''' + if isinstance(d, DrawPolyhedron): + return _polyhedron(d.faces_vertices) + a = d.args + if isinstance(d, DrawSphere): + x, y, z, r = a + phi = np.linspace(0, np.pi, K // 2 + 1) + return _revolve((x, y, z), (0, 1, 0), r * np.sin(phi), -r * np.cos(phi)) + if isinstance(d, DrawCone): + x, y, z, r, h, *n = a + return _revolve((x, y, z), n, [0, r, 0], [-h / 2, -h / 2, h / 2]) + if isinstance(d, DrawCylinder): + x, y, z, r, h, t, *n = a + if t > 0: + return _revolve((x, y, z), n, [r - t, r, r, r - t], [-h / 2, -h / 2, h / 2, h / 2], closed=True) + return _revolve((x, y, z), n, [0, r, r, 0], [-h / 2, -h / 2, h / 2, h / 2]) + if isinstance(d, DrawDisc): + x, y, z, r, *n = a + return _revolve((x, y, z), n, [0, r], [0, 0]) + if isinstance(d, DrawAnnulus): + x, y, z, r, w, *n = a + return _revolve((x, y, z), n, [r - w, r], [0, 0]) + if isinstance(d, DrawBox): + return _box(*a[:10]) + + +def _merge(parts): + ''' [(vertices, triangles), ...] -> one (vertices, triangles) ''' + parts = [p for p in parts if len(p[0])] or [(np.zeros((0, 3)), np.zeros((0, 3), int))] + off = np.cumsum([0] + [len(v) for v, f in parts[:-1]]) + return np.concatenate([v for v, f in parts]), np.concatenate([f + o for (v, f), o in zip(parts, off)]) + + +def trace(instr, n=100, params=(), yes=False): + ''' run mcrun --trace=2; yes forwards -y (unset params take defaults), otherwise mcrun prompts for them. + Returns ({component: (lines, solid vertices, solid triangles)}, ray xyz); lines/rays are NaN-separated + (N,3) polylines, all in instrument coordinates ''' + reader = McDisplayReader(instr=instr, n=n, options=list(params) + ['-y'] * yes, no_mpi=True, trace=2) instrument = reader.read_instrument() bundle = reader.read_particles() geom = {} for c in instrument.components: - pls = [] - for d in c.drawcalls: - # ponytail: wireframe primitives only (as mcdisplay-pyqtgraph); --trace=2 solids are skipped - pts = ([d.point_1, d.point_2] if isinstance(d, DrawLine) else d.points if isinstance(d, DrawMultiline) - else d.get_points_on_circle(24) if isinstance(d, DrawCircle) else None) # 60 by default; 24 is round enough - if pts: - pls.append([_xyz(c.transform.apply(p)) for p in pts]) - if pls: - geom[c.name] = _polylines(pls) + t = c.transform + M = np.array([[t.a11, t.a12, t.a13], [t.a21, t.a22, t.a23], [t.a31, t.a32, t.a33]]) + t0 = np.array([t.a14, t.a24, t.a34]) + wires = [w for w in map(_wire, c.drawcalls) if w] + solids = [s for s in map(_solid, c.drawcalls) if s is not None] + if wires or solids: + v, f = _merge(solids) + geom[c.name] = (_polylines(wires) @ M.T + t0, v @ M.T + t0, f) # ponytail: DrawPolygon (unused at trace=2) skipped tf = {c.name: c.transform for c in instrument.components} ray_pls = [[_xyz(tf[g.compname].apply(Vector3d(*e.args[:3]))) for g in story.groups if g.compname in tf @@ -56,6 +163,12 @@ def trace(instr, n=100, params=()): return geom, _polylines(ray_pls) +def _edges(v, f): + ''' triangle outlines as NaN-separated polylines, for the 2D view ''' + tri = v[f] + return np.concatenate([tri, tri[:, :1], np.full((len(f), 1, 3), np.nan)], 1).reshape(-1, 3) + + def _projection(xyz, h, v): ''' 1D DataArray: values = vertical axis, coord = horizontal axis (McStas: z beam, y up) ''' ax = 'xyz' @@ -64,13 +177,14 @@ def _projection(xyz, h, v): def view(geom, rays): - ''' top (z-x) above side (z-y) projection; one colour per component, rays in grey ''' - z = np.concatenate([rays[:, 2]] + [xyz[:, 2] for xyz in geom.values()]) + ''' top (z-x) above side (z-y) projection; one colour per component (solids as triangle outlines), rays in grey ''' + flat = {name: np.concatenate([lines, _edges(v, f)]) for name, (lines, v, f) in geom.items()} + z = np.concatenate([rays[:, 2]] + [xyz[:, 2] for xyz in flat.values()]) pad = 0.02 * (np.nanmax(z) - np.nanmin(z)) # plopp's autoscale overshoots on the NaN separators figs = [] for v in 'xy': lines = {'rays': _projection(rays, 'z', v)} # first, so components draw on top - lines.update({name: _projection(xyz, 'z', v) for name, xyz in geom.items()}) + lines.update({name: _projection(xyz, 'z', v) for name, xyz in flat.items()}) figs.append(pp.plot(lines, linestyle='-', marker='', legend=False, color={'rays': 'lightgrey'}, ylabel=f'{v} [m]', title=f'z-{v}', xmin=np.nanmin(z) - pad, xmax=np.nanmax(z) + pad)) @@ -111,17 +225,18 @@ def _tubes(xyz, r, k=6): def view3d(geom, rays, thickness=2.5e-4): - ''' 3D (Jupyter/pythreejs): components as tubes coloured per component, rays as thinner grey tubes. + ''' 3D (Jupyter/pythreejs): solids as meshes, lines as tubes, coloured per component; rays as thinner grey tubes. Tube radius = thickness x the instrument's bounding-box diagonal; rays get half of it ''' - allpts = np.concatenate([rays] + list(geom.values())) + allpts = np.concatenate([rays] + [np.concatenate([lines, v]) for lines, v, f in geom.values()]) r = thickness * np.linalg.norm(np.nanmax(allpts, 0) - np.nanmin(allpts, 0)) - parts = [(_tubes(xyz, r), i % 20) for i, xyz in enumerate(geom.values())] + [(_tubes(rays, r / 2), np.nan)] - verts, faces, cols, off = [], [], [], 0 - for (vv, ff), c in parts: - verts.append(vv), faces.append(ff + off), cols.append(np.full(len(vv), c, dtype=float)) - off += len(vv) - return pp.mesh3d(vertices=sc.vectors(dims=['vertices'], values=np.concatenate(verts), unit='m'), - faces=sc.array(dims=['faces', 'vertex'], values=np.concatenate(faces)), + parts, cols = [], [] + for i, (lines, v, f) in enumerate(geom.values()): + for part in (_tubes(lines, r), (v, f)): + parts.append(part), cols.append(np.full(len(part[0]), i % 20, dtype=float)) + parts.append(_tubes(rays, r / 2)), cols.append(np.full(len(parts[-1][0]), np.nan)) + verts, faces = _merge(parts) + return pp.mesh3d(vertices=sc.vectors(dims=['vertices'], values=verts, unit='m'), + faces=sc.array(dims=['faces', 'vertex'], values=faces), vertexcolors=sc.array(dims=['vertices'], values=np.concatenate(cols)), cmap='tab20', cmin=0, cmax=19, nan_color='lightgrey', figsize=(900, 600)) @@ -146,7 +261,7 @@ def run(_=None): go.disabled = True try: with out: - last['trace'] = trace(instr, rays.value, pars.value.split()) + last['trace'] = trace(instr, rays.value, pars.value.split(), yes=True) # a widget can't answer prompts draw() finally: go.disabled = False @@ -174,11 +289,13 @@ def main(): p.add_argument('params', nargs='*', help='instrument parameters, name=value') p.add_argument('-n', type=int, default=100, help='number of rays to trace') p.add_argument('-o', '--output', help='write a static png/pdf/svg instead of opening the UI') + p.add_argument('-y', '--yes', action='store_true', help='forwarded to mcrun: use defaults for unset parameters ' + '(always on in the UI)') args = p.parse_args() if not args.output: return launch(f'import mcdisplopp; mcdisplopp.ui({os.path.abspath(args.instr)!r}, {args.n}, {" ".join(args.params)!r})') - view(*trace(args.instr, args.n, args.params)).save(args.output) + view(*trace(args.instr, args.n, args.params, args.yes)).save(args.output) print(f'saved {args.output}') diff --git a/tools/Python/mcdisplay/plopp/test_mcdisplopp.py b/tools/Python/mcdisplay/plopp/test_mcdisplopp.py index a60f8e14e0..acd5120270 100644 --- a/tools/Python/mcdisplay/plopp/test_mcdisplopp.py +++ b/tools/Python/mcdisplay/plopp/test_mcdisplopp.py @@ -23,3 +23,27 @@ off = v[:12] - a assert np.allclose(np.linalg.norm(off - np.outer(off @ d, d), axis=1), 0.1) # ring radius about the axis print('ok tubes') + +from mcdisplopp import _box, _revolve, _polyhedron, _rot_y_to, _edges, K +def closed(v, f): # welded by position, every edge shared by exactly two triangles (degenerate cap triangles dropped) + f = np.unique(np.round(v, 9), axis=0, return_inverse=True)[1].reshape(-1)[f] + f = f[(f[:, 0] != f[:, 1]) & (f[:, 1] != f[:, 2]) & (f[:, 0] != f[:, 2])] + return set(Counter(tuple(sorted(e)) for t in f for e in ((t[0], t[1]), (t[1], t[2]), (t[2], t[0]))).values()) == {2} + +v, f = _box(1, 2, 3, 0.2, 0.4, 0.6, 0, 0, 1, 0) # solid, unrotated: extents w, h, l about the centre +assert np.allclose(v.min(0), (0.9, 1.8, 2.7)) and np.allclose(v.max(0), (1.1, 2.2, 3.3)) +v, f = _box(0, 0, 0, 0.2, 0.4, 0.6, 0.05, 0, 0, 1) # hollow, local y (height 0.4) turned onto z +assert np.allclose(v.max(0), (0.1, 0.3, 0.2)) and len(v) == 16 +assert np.allclose(_rot_y_to((0, 0, 1)) @ (0, 1, 0), (0, 0, 1)) and np.allclose(_rot_y_to((0, -1, 0)) @ (0, 1, 0), (0, -1, 0)) + +v, f = _revolve((0, 0, 0), (1, 0, 0), [0, 0.5, 0.5, 0], [-1, -1, 1, 1]) # closed cylinder along x +assert np.allclose(np.abs(v).max(0), (1, 0.5, 0.5), atol=0.01) and closed(v, f) +v, f = _revolve((0, 0, 0), (0, 0, 1), [0.4, 0.5, 0.5, 0.4], [-1, -1, 1, 1], closed=True) # hollow cylinder +assert np.allclose(sorted(set(np.round(np.hypot(v[:, 0], v[:, 1]), 6))), (0.4, 0.5)) and closed(v, f) +v, f = _revolve((0, 0, 0), (0, 1, 0), [0, 0.5, 0], [-1, -1, 1]) # cone: base at -h/2, apex at +h/2 (three.js) +assert np.isclose(v[:, 1].max(), 1) and np.isclose(v[:, 1][np.hypot(v[:, 0], v[:, 2]) > 0.49].max(), -1) and closed(v, f) + +v, f = _polyhedron('{"vertices": [[0,0,0],[1,0,0],[1,1,0],[0,1,0],[0,0,1]], "faces": [{"face": [0,1,2,3]}, {"face": [0,1,4]}]}') +assert f.tolist() == [[0, 1, 2], [0, 2, 3], [0, 1, 4]] +assert _edges(v, f).shape == (3 * 5, 3) +print('ok solids') From e3ef42377f9c96e8bb0fec591db4149cba210f5a Mon Sep 17 00:00:00 2001 From: Peter Willendrup Date: Tue, 13 Oct 2026 20:53:26 +0200 Subject: [PATCH 4/7] Thinner lines by default --- tools/Python/mcdisplay/plopp/mcdisplopp.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/Python/mcdisplay/plopp/mcdisplopp.py b/tools/Python/mcdisplay/plopp/mcdisplopp.py index 105f286d48..8c3e0d3a1e 100644 --- a/tools/Python/mcdisplay/plopp/mcdisplopp.py +++ b/tools/Python/mcdisplay/plopp/mcdisplopp.py @@ -224,7 +224,7 @@ def _tubes(xyz, r, k=6): return np.concatenate([cyl, sph]), np.concatenate([cyl_f, sph_f]) -def view3d(geom, rays, thickness=2.5e-4): +def view3d(geom, rays, thickness=1e-4): ''' 3D (Jupyter/pythreejs): solids as meshes, lines as tubes, coloured per component; rays as thinner grey tubes. Tube radius = thickness x the instrument's bounding-box diagonal; rays get half of it ''' allpts = np.concatenate([rays] + [np.concatenate([lines, v]) for lines, v, f in geom.values()]) @@ -248,7 +248,7 @@ def ui(instr, n=100, params=''): pars = w.Text(value=params, description='params', placeholder='lambda=2.36 ...', layout={'width': '40em'}) rays = w.IntText(value=n, description='rays') go = w.Button(description='Trace', button_style='primary') - thick = w.FloatLogSlider(value=2.5e-4, base=10, min=-5, max=-2, description='thickness', readout_format='.1e') + thick = w.FloatLogSlider(value=1e-4, base=10, min=-6, max=-3, description='thickness', readout_format='.1e') out = w.Output() last = {} From 5ab10ec9391c122eba35c19b46f2a853e0b14e06 Mon Sep 17 00:00:00 2001 From: Peter Willendrup Date: Thu, 15 Oct 2026 19:47:52 +0200 Subject: [PATCH 5/7] plopp tools: guard scipp/plopp imports, drop wrapper import test - mcplopp.py and mcdisplopp.py wrap the scipp/plopp imports in try/except ImportError and exit with a message saying they are required, with conda and pip install hints (plus ipympl and jupyterlab for the UI) - The bash wrappers no longer test-import python modules; canrun() only checks that the tool script exists and is executable - scipp and plopp removed again from meta-pkgs/windows/environment.yml; on Windows the tools now print the guard message until plopp is installed Co-Authored-By: Claude Opus 5.5 --- meta-pkgs/windows/environment.yml | 2 -- tools/Python/mcdisplay/plopp/mcdisplay.in | 9 +-------- tools/Python/mcdisplay/plopp/mcdisplopp.py | 10 ++++++++-- tools/Python/mcplot/plopp/mcplopp.py | 10 ++++++++-- tools/Python/mcplot/plopp/mcplot.in | 9 +-------- 5 files changed, 18 insertions(+), 22 deletions(-) diff --git a/meta-pkgs/windows/environment.yml b/meta-pkgs/windows/environment.yml index 376bca6498..8cf82f8f05 100644 --- a/meta-pkgs/windows/environment.yml +++ b/meta-pkgs/windows/environment.yml @@ -40,8 +40,6 @@ dependencies: - jupytext - jupyterlab - ipympl - - scipp - - plopp - jinja2 - mslex - typish diff --git a/tools/Python/mcdisplay/plopp/mcdisplay.in b/tools/Python/mcdisplay/plopp/mcdisplay.in index 01390c045a..ab91c7cd50 100644 --- a/tools/Python/mcdisplay/plopp/mcdisplay.in +++ b/tools/Python/mcdisplay/plopp/mcdisplay.in @@ -17,17 +17,10 @@ canrun() { if ! [ -x "${UTILDIR}/${TOOL}.py" ]; then exit 127; fi - - modules="numpy scipp plopp ipywidgets ipympl" - cmd="" - for name in ${modules}; do - cmd="${cmd}import ${name}; " - done - python3 -c "${cmd}" } if ( canrun ); then python3 -u ${UTILDIR}/${TOOL}.py "$@" else - @FLAVOR@_errmsg Failed to run Python ${TOOL} - missing dependencies\? Try: python3 -m pip install plopp ipympl jupyterlab + @FLAVOR@_errmsg Failed to run Python ${TOOL} - permissions\? fi diff --git a/tools/Python/mcdisplay/plopp/mcdisplopp.py b/tools/Python/mcdisplay/plopp/mcdisplopp.py index 8c3e0d3a1e..8a5b2e9298 100644 --- a/tools/Python/mcdisplay/plopp/mcdisplopp.py +++ b/tools/Python/mcdisplay/plopp/mcdisplopp.py @@ -13,8 +13,14 @@ import warnings import numpy as np -import scipp as sc -import plopp as pp +try: + import scipp as sc + import plopp as pp +except ImportError as e: + sys.exit(f'mcdisplay-plopp: {e}. scipp and plopp are required for this tool to function ' + '(plus ipympl and jupyterlab for the interactive UI), e.g.:\n' + ' conda install -c conda-forge plopp ipympl jupyterlab\n' + ' python3 -m pip install plopp ipympl jupyterlab') sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) from mccodelib.mcdisplayutils import McDisplayReader diff --git a/tools/Python/mcplot/plopp/mcplopp.py b/tools/Python/mcplot/plopp/mcplopp.py index a867fb5ff1..0e8446ee0f 100644 --- a/tools/Python/mcplot/plopp/mcplopp.py +++ b/tools/Python/mcplot/plopp/mcplopp.py @@ -14,8 +14,14 @@ import sys import numpy as np -import scipp as sc -import plopp as pp +try: + import scipp as sc + import plopp as pp +except ImportError as e: + sys.exit(f'mcplot-plopp: {e}. scipp and plopp are required for this tool to function ' + '(plus ipympl and jupyterlab for the interactive UI), e.g.:\n' + ' conda install -c conda-forge plopp ipympl jupyterlab\n' + ' python3 -m pip install plopp ipympl jupyterlab') sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) from mccodelib.mcplotloader import McCodeDataLoader, Data1D, Data2D diff --git a/tools/Python/mcplot/plopp/mcplot.in b/tools/Python/mcplot/plopp/mcplot.in index 4708af5bce..c9397ba28b 100644 --- a/tools/Python/mcplot/plopp/mcplot.in +++ b/tools/Python/mcplot/plopp/mcplot.in @@ -17,17 +17,10 @@ canrun() { if ! [ -x "${UTILDIR}/${TOOL}.py" ]; then exit 127; fi - - modules="numpy scipp plopp ipywidgets ipympl" - cmd="" - for name in ${modules}; do - cmd="${cmd}import ${name}; " - done - python3 -c "${cmd}" } if ( canrun ); then python3 -u ${UTILDIR}/${TOOL}.py "$@" else - @FLAVOR@_errmsg Failed to run Python ${TOOL} - missing dependencies\? Try: python3 -m pip install plopp ipympl jupyterlab + @FLAVOR@_errmsg Failed to run Python ${TOOL} - permissions\? fi From db4a4479c8c0c430ccc60ce53b519a563b9054a2 Mon Sep 17 00:00:00 2001 From: Peter Willendrup Date: Thu, 15 Oct 2026 20:02:03 +0200 Subject: [PATCH 6/7] mcplot-plopp: read McCode NeXus (mccode.h5) output load() now hands *.h5 / *.nxs files, and directories that have mccode.h5 but no mccode.sim (the rule the matplotlib/pyqtgraph mcplot use before spawning nexpy), to a new load_nexus(): - Monitors are the NXdata groups under entry*/instrument/components//output/. type, title, labels and x(y)limits come from their attributes; edges come from the limits, since the axis datasets hold bin centres - 2D data is stored (nx, ny) with axis=1 on x, the transpose of the ASCII block, so it is transposed to the ('y', 'x') layout used for ASCII. The NeXus errors block gives 2D monitors variances (the ASCII loader skips "# Errors") - Scans: one NXentry per step. Monitors are stacked over the first parameter that varies across entry*/simulation/Param - 0D and event-list monitors are skipped, as for ASCII - h5py is imported only when reading NeXus; if it is missing the tool exits with a message _curve()/_image() are shared by the ASCII and NeXus paths. Validated against real mcrun --format=NeXus output: a non-square 30x10 PSD plus a 1D monitor gives DataArrays identical to the same-seed ASCII run (dims, edges, values); a 3-step lambda scan stacks correctly; BNL_H8 single and scan load all 9 monitors; the UI runs on the NeXus scan in an executed notebook. test_mcplopp.py gains a synthetic mccode.h5 check (orientation, variances, scan stacking). Co-Authored-By: Claude Opus 5.5 --- tools/Python/mcplot/plopp/mcplopp.py | 84 +++++++++++++++++++---- tools/Python/mcplot/plopp/test_mcplopp.py | 33 +++++++++ 2 files changed, 105 insertions(+), 12 deletions(-) diff --git a/tools/Python/mcplot/plopp/mcplopp.py b/tools/Python/mcplot/plopp/mcplopp.py index 0e8446ee0f..7ebc329139 100644 --- a/tools/Python/mcplot/plopp/mcplopp.py +++ b/tools/Python/mcplot/plopp/mcplopp.py @@ -2,8 +2,8 @@ ''' mcplopp: plot McStas/McXtrace output with plopp (scipp). -UI: mcplopp.py (opens JupyterLab) -Static: mcplopp.py -o out.png [--log] +UI: mcplopp.py (opens JupyterLab) +Static: mcplopp.py -o out.png [--log] ''' import argparse import json @@ -38,28 +38,88 @@ def _edges(label, lo, hi, n): return dim, sc.linspace(dim, lo, hi, n + 1, unit=unit or '') +def _curve(I, err, xlabel, lim): + x, ex = _edges(xlabel, *lim, len(I)) + return sc.DataArray(sc.array(dims=[x], values=I, variances=np.square(err)), coords={x: ex}) + + +def _image(z, err, xlabel, ylabel, lim): + ''' z is (ny, nx), rows are y, as in the ASCII files and the matplotlib frontend ''' + x, ex = _edges(xlabel, *lim[:2], z.shape[1]) + y, ey = _edges(ylabel, *lim[2:4], z.shape[0]) + if y == x: + y += ' (y)' + ey = ey.rename_dims({x: y}) + return sc.DataArray(sc.array(dims=[y, x], values=z, variances=None if err is None else np.square(err)), + coords={x: ex, y: ey}) + + def to_dataarray(d): ''' Data1D/Data2D -> DataArray with bin edges; 0D/event lists -> None ''' if isinstance(d, Data1D): - x, ex = _edges(d.xlabel, *d.xlimits, len(d.yvals)) - da = sc.DataArray(sc.array(dims=[x], values=d.yvals, variances=np.square(d.y_err_vals)), coords={x: ex}) + da = _curve(d.yvals, d.y_err_vals, d.xlabel, d.xlimits) elif isinstance(d, Data2D): - z = np.array(d.zvals) # rows are y: (ny, nx), as in the matplotlib frontend - x, ex = _edges(d.xlabel, *d.xlimits[:2], z.shape[1]) - y, ey = _edges(d.ylabel, *d.xlimits[2:], z.shape[0]) - if y == x: - y += ' (y)' - ey = ey.rename_dims({x: y}) # ponytail: no variances for 2D, mcplotloader skips the "# Errors" block - da = sc.DataArray(sc.array(dims=[y, x], values=z), coords={x: ex, y: ey}) + da = _image(np.array(d.zvals), None, d.xlabel, d.ylabel, d.xlimits) else: return None da.name = 'I' # colorbar/y label; the title goes in the load() key return da +def _nx_dataarray(g): + ''' McCode NeXus monitor (NXdata group) -> (title, DataArray), None for 0D / event lists ''' + a = {k: v.decode() if isinstance(v, bytes) else v for k, v in g.attrs.items()} + typ = a.get('type', '') + if typ.startswith('array_1d'): + da = _curve(g['data'][()], g['errors'][()], a['xlabel'], [float(v) for v in a['xlimits'].split()]) + elif typ.startswith('array_2d'): + # NeXus stores (nx, ny) with axis=1 on x, i.e. the transpose of the ASCII block + da = _image(g['data'][()].T, g['errors'][()].T, a['xlabel'], a['ylabel'], [float(v) for v in a['xylimits'].split()]) + else: + return None + da.name = 'I' + return a.get('title', '').strip(), da + + +def load_nexus(path): + ''' {name: DataArray} from a McCode mccode.h5; one NXentry per scan step, stacked over the scanned + parameter (taken from entry*/simulation/Param) as in load() ''' + try: + import h5py + except ImportError as e: + sys.exit(f'mcplot-plopp: {e}. h5py is required to read NeXus files') + with h5py.File(path, 'r') as f: + entries = sorted(f, key=lambda e: int(re.sub(r'\D', '', e) or 0)) + steps = [] + for e in entries: + comps = f[e]['instrument/components'] + mons = [_nx_dataarray(comps[c]['output'][m]) for c in sorted(comps) if 'output' in comps[c] + for m in comps[c]['output']] + par = f[e]['simulation/Param'].attrs if 'simulation/Param' in f[e] else {} + steps.append(([m for m in mons if m], {k: v.decode() if isinstance(v, bytes) else v for k, v in par.items()})) + + if len(steps) == 1: + return {f'{t} [{i}]': da for i, (t, da) in enumerate(steps[0][0])} + pars = [p for _, p in steps] + scanned = [k for k in pars[0] if k != 'NX_class' and len({p.get(k) for p in pars}) > 1] + dim = scanned[0] if scanned else 'step' # ponytail: first varying parameter only, as mccode.dat's single xvar + vals = [float(p[dim]) for p in pars] if scanned else np.arange(len(steps)) + out = {} + for i, (t, _) in enumerate(steps[0][0]): + da = sc.concat([mons[i][1] for mons, _ in steps], dim=dim) + da.coords[dim] = sc.array(dims=[dim], values=vals) + out[f'{t} [{i}]'] = da + return out + + def load(path): ''' {name: DataArray}. Scans stack each monitor over the scan parameter (1D->2D, 2D->3D). ''' + h5 = os.path.join(path, 'mccode.h5') + if path.endswith(('.h5', '.nxs')): + return load_nexus(path) + if os.path.isfile(h5) and not os.path.isfile(os.path.join(path, 'mccode.sim')): # as the matplotlib frontend + return load_nexus(h5) loader = McCodeDataLoader(simfile=path) loader.load() root = loader.plot_graph @@ -134,7 +194,7 @@ def figures(das, log=False): def main(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - p.add_argument('simfile', nargs='?', default='.', help='output dir, mccode.sim, or a monitor file') + p.add_argument('simfile', nargs='?', default='.', help='output dir, mccode.sim, a monitor file, or mccode.h5 (NeXus)') p.add_argument('-o', '--output', help='write a static png/pdf/svg instead of opening the UI') p.add_argument('--log', action='store_true', help='log intensity scale') args = p.parse_args() diff --git a/tools/Python/mcplot/plopp/test_mcplopp.py b/tools/Python/mcplot/plopp/test_mcplopp.py index 05af2d28f7..4d775e7b3d 100644 --- a/tools/Python/mcplot/plopp/test_mcplopp.py +++ b/tools/Python/mcplot/plopp/test_mcplopp.py @@ -11,3 +11,36 @@ da = to_dataarray(d) assert da.dims == ('y', 'x') and da.coords['x'].sizes == {'x': 4} and da['x', 2]['y', 1].value == 6 print('ok') + +# NeXus: (nx, ny) storage, transposed to the ASCII ('y', 'x') layout; errors -> variances; one entry per scan step +import os, tempfile +import h5py +import numpy as np +from mcplopp import load + +def entry(f, name, lam, scale): + out = f.create_group(f'{name}/instrument/components/0001_psd/output') + f.create_group(f'{name}/simulation/Param').attrs['lambda'] = str(lam) + g = out.create_group('psd_dat') + g.attrs.update({'type': 'array_2d(3, 2)', 'title': 'PSD', 'xlabel': 'X position [cm]', 'ylabel': 'Y position [cm]', + 'xylimits': '0 3 0 2'}) + g['data'] = scale * np.arange(6.).reshape(3, 2) # data[ix, iy] + g['errors'] = np.ones((3, 2)) + h = out.create_group('l_dat') + h.attrs.update({'type': 'array_1d(4)', 'title': 'L', 'xlabel': 'Wavelength [AA]', 'xlimits': '1 3'}) + h['data'], h['errors'] = np.arange(4.), np.full(4, 0.5) + +with tempfile.TemporaryDirectory() as d: + with h5py.File(os.path.join(d, 'mccode.h5'), 'w') as f: + entry(f, 'entry1', 2.0, 1) + das = load(d) # directory with mccode.h5 and no mccode.sim + psd = das['PSD [1]'] + assert psd.dims == ('Y position', 'X position') and psd.values[1, 2] == 5 # (iy=1, ix=2) <- data[2, 1] + assert psd.variances is not None and das['L [0]'].coords['Wavelength'].sizes == {'Wavelength': 5} + with h5py.File(os.path.join(d, 'scan.h5'), 'w') as f: + for i, lam in enumerate((1.5, 2.0, 2.5)): + entry(f, f'entry{i + 1}', lam, i + 1) + scan = load(os.path.join(d, 'scan.h5'))['PSD [1]'] + assert scan.dims[0] == 'lambda' and scan.coords['lambda'].values.tolist() == [1.5, 2.0, 2.5] + assert scan['lambda', 2].values[1, 2] == 15 +print('ok nexus') From e46b30be9a53dd50fdb04ad04ec19d928b5cfe5d Mon Sep 17 00:00:00 2001 From: Peter Willendrup Date: Fri, 16 Oct 2026 09:12:14 +0200 Subject: [PATCH 7/7] mcplot-plopp: Monitor_nD pixel event data via McStasToX (NeXus) List-mode Monitor_nD banks with pixel ids ("neutron pixel min=... t, list all neutrons") in a NeXus file are read through McStasToX (mccode-dev/McStasToX), which needs the source and sample component names: - load_events(): McStasToX export_scipp() events, grouped by pixel with pixel positions; adds per-event wavelength from the source -> sample -> pixel flight path, lambda = 2 pi AA2MS t / L (AA2MS from mcstas-r.h) - event_figures(): pixel intensity map (3D scatter in the UI, z-x top view for -o) plus time-of-flight and wavelength histograms - UI: an "Event data" row appears when the file has pixel-id banks, with source/sample dropdowns (defaulting to components named like "source"/"sample") and a Load button - CLI: --source/--sample add the event figures to the static output - mcstastox is imported only for event data and fails with an install hint if missing - The UI no longer fails on files that hold only event monitors (empty monitor dropdown) NeXus only: McStasToX does not read ASCII, and ASCII list files carry no rotations or pixel geometry. McStasToX reads entry1 only, i.e. the first step of a NeXus scan. Validated on a scratch instrument (Incoherent sample, two 32x16 pixel banks, one rotated 60 deg): wavelengths 1.50-2.51 AA for a 2 +- 0.5 AA source, TOF 1.1-1.9 ms over 3 m, banks placed correctly; the UI incl. the 3D view runs in an executed notebook (mcstastox 0.0.12). Co-Authored-By: Claude Opus 5.5 --- tools/Python/mcplot/plopp/mcplopp.py | 92 +++++++++++++++++++++++++--- 1 file changed, 84 insertions(+), 8 deletions(-) diff --git a/tools/Python/mcplot/plopp/mcplopp.py b/tools/Python/mcplot/plopp/mcplopp.py index 7ebc329139..87c8bbe747 100644 --- a/tools/Python/mcplot/plopp/mcplopp.py +++ b/tools/Python/mcplot/plopp/mcplopp.py @@ -3,7 +3,8 @@ mcplopp: plot McStas/McXtrace output with plopp (scipp). UI: mcplopp.py (opens JupyterLab) -Static: mcplopp.py -o out.png [--log] +Static: mcplopp.py -o out.png [--log] [--source S --sample S] +Events: Monitor_nD pixel/list data in NeXus files via McStasToX, given the source and sample components ''' import argparse import json @@ -113,13 +114,65 @@ def load_nexus(path): return out -def load(path): - ''' {name: DataArray}. Scans stack each monitor over the scan parameter (1D->2D, 2D->3D). ''' - h5 = os.path.join(path, 'mccode.h5') +def _nexus_file(path): + ''' the NeXus file to read for path, or None for ASCII output ''' if path.endswith(('.h5', '.nxs')): - return load_nexus(path) + return path + h5 = os.path.join(path, 'mccode.h5') if os.path.isfile(h5) and not os.path.isfile(os.path.join(path, 'mccode.sim')): # as the matplotlib frontend - return load_nexus(h5) + return h5 + + +AA2MS = 629.622368 # k[1/AA] -> v[m/s], as in mcstas-r.h; lambda[AA] = 2 pi AA2MS / v[m/s] + + +def _mcstastox(): + try: + import mcstastox + return mcstastox + except ImportError as e: + raise ImportError(f'{e}. McStasToX is required for event data: ' + 'conda install -c conda-forge mcstastox / python3 -m pip install mcstastox') from None + + +def event_components(path): + ''' (all components, components with pixel-id event data) of a NeXus file; [] , [] for ASCII output ''' + h5 = _nexus_file(path) + if not h5: + return [], [] # ponytail: McStasToX reads NeXus only; ASCII list files lack pixel geometry and rotations + with _mcstastox().Read(*os.path.split(os.path.abspath(h5))) as d: + return d.file_object.get_components(), d.file_object.get_components_with_ids() + + +def load_events(path, source, sample): + ''' Monitor_nD pixel events ("neutron pixel min=... t, list all neutrons") via McStasToX, grouped by pixel with + pixel positions. Adds per-event wavelength from the source -> sample -> pixel flight path. + McStasToX reads entry1 only, i.e. the first step of a NeXus scan ''' + with _mcstastox().Read(*os.path.split(os.path.abspath(_nexus_file(path)))) as d: + ev = d.export_scipp(source_name=source, sample_name=sample)['events'] + c = ev.coords + L = sc.norm(c['sample_position'] - c['source_position']) + sc.norm(c['position'] - c['sample_position']) + ev.bins.coords['wavelength'] = sc.scalar(2 * np.pi * AA2MS, unit='angstrom*m/s') * ev.bins.coords['t'] / L + return ev + + +def event_figures(ev, threed=False): + ''' pixel intensity map (3D scatter in Jupyter, z-x top view otherwise) + time-of-flight and wavelength spectra ''' + pix = ev.bins.sum() + if threed: + det = pp.scatter3d(pix, pos='position', cbar=True, title='pixel intensity') + else: + for ax in 'xz': + pix.coords[ax] = pix.coords['position'].fields.__getattribute__(ax) + det = pp.scatter(pix, x='z', y='x', cbar=True, title='pixel intensity (top view)') + allev = ev.bins.concat() + return [det, pp.plot(allev.hist(t=200), title='time of flight'), pp.plot(allev.hist(wavelength=200), title='wavelength')] + + +def load(path): + ''' {name: DataArray}. Scans stack each monitor over the scan parameter (1D->2D, 2D->3D). ''' + if _nexus_file(path): + return load_nexus(_nexus_file(path)) loader = McCodeDataLoader(simfile=path) loader.load() root = loader.plot_graph @@ -162,8 +215,27 @@ def show(_=None): # ponytail: one figure at a time, so 100+ monitor instruments with out: display(scan_slicer(da) if not da.coords.is_edges(da.dims[0]) else pp.plot(da, title=pick.value)) pick.observe(show, 'value') - show() - return w.VBox([pick, out]) + rows = [] + if das: # a file can hold only event monitors + show() + rows = [pick, out] + + comps, banks = event_components(path) + if banks: # pixel events present: which components are source and sample needs the user + guess = lambda key, i: next((c for c in comps if key in c.lower()), comps[i]) + src = w.Dropdown(options=comps, value=guess('source', 0), description='source') + smp = w.Dropdown(options=comps, value=guess('sample', len(comps) // 2), description='sample') + go = w.Button(description=f'Load events ({", ".join(banks)})', layout={'width': 'auto'}) + evout = w.Output() + + def show_events(_=None): + evout.clear_output(wait=True) + with evout: + det, tof, lam = event_figures(load_events(path, src.value, smp.value), threed=True) + display(w.VBox([det, w.HBox([tof, lam])])) + go.on_click(show_events) + rows += [w.HTML('Event data (McStasToX)'), w.HBox([src, smp, go]), evout] + return w.VBox(rows) def launch(call): @@ -197,11 +269,15 @@ def main(): p.add_argument('simfile', nargs='?', default='.', help='output dir, mccode.sim, a monitor file, or mccode.h5 (NeXus)') p.add_argument('-o', '--output', help='write a static png/pdf/svg instead of opening the UI') p.add_argument('--log', action='store_true', help='log intensity scale') + p.add_argument('--source', help='event data (NeXus, McStasToX): name of the source component') + p.add_argument('--sample', help='event data (NeXus, McStasToX): name of the sample component') args = p.parse_args() if not args.output: return launch(f'import mcplopp; mcplopp.ui({os.path.abspath(args.simfile)!r})') figs = figures(load(args.simfile), args.log) + if args.source and args.sample: + figs += event_figures(load_events(args.simfile, args.source, args.sample)) ncols = math.ceil(math.sqrt(len(figs))) nrows = math.ceil(len(figs) / ncols) tiled = pp.tiled(nrows, ncols, figsize=(4 * ncols, 3 * nrows))