### Set Up Git Hooks using pre-commit Source: https://github.com/scipp/plopp/blob/main/docs/developer/getting-started.md Installs pre-commit hooks to automatically run code formatting and static analysis tools before committing changes. This helps maintain code quality and consistency. ```sh pre-commit install ``` -------------------------------- ### Install Development Dependencies using pip Source: https://github.com/scipp/plopp/blob/main/docs/developer/getting-started.md Installs the development dependencies for the project, as specified in the `requirements/dev.txt` file. This is a prerequisite for development. ```sh pip install -r requirements/dev.txt ``` -------------------------------- ### Test Documentation Manually using Sphinx (doctest) Source: https://github.com/scipp/plopp/blob/main/docs/developer/getting-started.md Tests the project documentation using Sphinx's doctest builder. This command extracts and runs code examples embedded in the documentation. ```sh python -m sphinx -v -b doctest -d .tox/docs_doctrees docs html ``` -------------------------------- ### Build Documentation Manually using Sphinx Source: https://github.com/scipp/plopp/blob/main/docs/developer/getting-started.md Builds the project documentation manually using Sphinx. This command specifies the source directory, builder, and output directory. ```sh python -m sphinx -v -b html -d .tox/docs_doctrees docs html ``` -------------------------------- ### Install Plopp Package in Editable Mode Source: https://github.com/scipp/plopp/blob/main/docs/developer/getting-started.md Installs the Plopp package in editable mode, allowing changes to the source code to be immediately reflected without reinstallation. This is useful for development. ```sh pip install -e . ``` -------------------------------- ### Build Documentation using tox Source: https://github.com/scipp/plopp/blob/main/docs/developer/getting-started.md Builds the project documentation using tox. The `-e docs` option specifies the documentation environment, which includes building the docs and running doctests. ```sh tox -e docs ``` -------------------------------- ### Installing plopp using pip Source: https://github.com/scipp/plopp/blob/main/docs/getting-started/installation.md Installs plopp using pip. Use this if you already have scipp installed. ```sh pip install plopp ``` -------------------------------- ### Test Documentation Manually using Sphinx (linkcheck) Source: https://github.com/scipp/plopp/blob/main/docs/developer/getting-started.md Tests the project documentation using Sphinx's linkcheck builder. This command verifies that all links in the documentation are valid. ```sh python -m sphinx -v -b linkcheck -d .tox/docs_doctrees docs html ``` -------------------------------- ### Run Linkcheck using tox Source: https://github.com/scipp/plopp/blob/main/docs/developer/getting-started.md Runs the linkcheck tool using tox to verify that all links in the documentation are valid. This helps ensure the documentation is up-to-date and accurate. ```sh tox -e linkcheck ``` -------------------------------- ### Installing plopp with all optional dependencies using pip Source: https://github.com/scipp/plopp/blob/main/docs/getting-started/installation.md Installs plopp with all optional dependencies, including those required for interactive figures and 3D rendering. ```sh pip install plopp[all] ``` -------------------------------- ### Installing plopp using conda Source: https://github.com/scipp/plopp/blob/main/docs/getting-started/installation.md Installs plopp from the conda-forge channel using conda. ```sh conda install -c conda-forge plopp ``` -------------------------------- ### Installing plopp with scipp using pip Source: https://github.com/scipp/plopp/blob/main/docs/getting-started/installation.md Installs plopp and its dependency scipp using pip. This is the recommended method if you don't already have scipp installed. ```sh pip install plopp[scipp] ``` -------------------------------- ### Run Tests using tox Source: https://github.com/scipp/plopp/blob/main/docs/developer/getting-started.md Executes the project's test suite using tox, a tool for running tests in isolated environments. The `-e py310` option specifies the Python 3.10 environment. ```sh tox -e py310 ``` -------------------------------- ### Run Tests Manually using pytest Source: https://github.com/scipp/plopp/blob/main/docs/developer/getting-started.md Executes the project's test suite using pytest directly. This provides an alternative to using tox for running tests. ```sh python -m pytest ``` -------------------------------- ### Installing Plopp using pip Source: https://github.com/scipp/plopp/blob/main/README.md This command installs the plopp package using pip, the Python package installer. It ensures that plopp and its dependencies are downloaded and installed in the current Python environment. ```sh python -m pip install plopp ``` -------------------------------- ### NumPy Docstring Example Source: https://github.com/scipp/plopp/blob/main/docs/developer/coding-conventions.md This example demonstrates the recommended structure and formatting for NumPy-style docstrings in Python. It includes a short description, long description, parameter descriptions, return value description, exception handling, related functions, and usage examples. ```python def foo(x: int, y: float) -> float: """Short description. Long description. With multiple paragraphs. Warning ------- Be careful! Parameters ---------- x: First input. y: Second input. Returns ------- : The result. Raises ------ ValueError If the input is bad. IndexError If some lookup failed. See Also -------- scitacean.bar: A bit less foo. Examples -------- This is how to use it: >>> foo(1, 2) 3 And also: >>> foo(1, 3) 6 """ ``` -------------------------------- ### Single-Line Docstring Example Source: https://github.com/scipp/plopp/blob/main/docs/developer/coding-conventions.md This example demonstrates a concise, single-line docstring for simple functions. It shows how to omit the 'Parameters' and 'Returns' sections when a function can be sufficiently described in a single sentence. ```python def bar(self) -> int: """Returns the number of dimensions.""" ``` -------------------------------- ### Generate Example Data with Three Bands Source: https://github.com/scipp/plopp/blob/main/docs/gallery/interactive-masking.ipynb Generates example data containing three bands of peaks with different spreads using the `three_bands` function from `plopp.data.examples`. This data will be used for the interactive masking demonstration. ```python from plopp.data.examples import three_bands da = three_bands() ``` -------------------------------- ### Import Plopp, Scipp, and NumPy Source: https://github.com/scipp/plopp/blob/main/docs/customization/graph-node-tips.ipynb Imports the necessary libraries: plopp for plotting, scipp for scientific data structures, and numpy for numerical operations. This is a standard setup for using plopp. ```python %matplotlib widget import plopp as pp import scipp as sc import numpy as np ``` -------------------------------- ### Generating Example Data Source: https://github.com/scipp/plopp/blob/main/docs/gallery/rectangle-selection.ipynb Generates example data containing three bands of peaks with different spreads using the `three_bands` function from `plopp.data.examples`. The data is stored in a Scipp DataArray. ```python from plopp.data.examples import three_bands da = three_bands() ``` -------------------------------- ### Show the Data Node Graph Source: https://github.com/scipp/plopp/blob/main/docs/customization/graph-node-tips.ipynb Displays the graph of the `data_node`, which is the root node containing the original 3D DataArray. This shows the starting point of the node graph. ```python pp.show_graph(data_node) ``` -------------------------------- ### Import Plopp and Create Sample Data Source: https://github.com/scipp/plopp/blob/main/docs/plotting/super-plot.ipynb This snippet imports the plopp library and creates a sample 2D data array for demonstration purposes. It requires the plopp library to be installed. ```python %matplotlib widget import plopp as pp da = pp.data.data2d() ``` -------------------------------- ### Loading and Displaying NYC Taxi Data with Scipp Source: https://github.com/scipp/plopp/blob/main/docs/gallery/nyc-taxi.ipynb This snippet loads the NYC taxi dataset using scipp.io.load_hdf5 and displays the loaded data. It requires the scipp and plopp libraries, as well as the nyc_taxi example data. ```python %matplotlib widget import scipp as sc import plopp as pp from plopp import widgets from plopp.data import examples from scipp.scipy.ndimage import gaussian_filter import ipywidgets as ipw data = sc.io.load_hdf5(examples.nyc_taxi()) data ``` -------------------------------- ### Generating Example Data with Three Bands Source: https://github.com/scipp/plopp/blob/main/docs/gallery/masking-a-range.ipynb Generates example data containing three bands of peaks with different spreads using the `three_bands` function from `plopp.data.examples`. This data is used as input for the masking and plotting demonstration. ```python from plopp.data.examples import three_bands da = three_bands() ``` -------------------------------- ### Docstring for Multiple Return Values Source: https://github.com/scipp/plopp/blob/main/docs/developer/coding-conventions.md This example shows how to document a function that returns multiple values using the NumPy docstring format. It demonstrates the required name and type annotations for each return value to ensure proper formatting in the generated documentation. ```python """ Returns ------- n: int The first return value. z: float The second return value. """ ``` -------------------------------- ### Specifying index URLs for package installation Source: https://github.com/scipp/plopp/blob/main/requirements/nightly.txt These lines specify the index URLs to be used by pip when installing packages. It configures pip to first look at the scipp-nightly-wheels Anaconda channel, and then the default PyPI repository. ```Text --index-url https://pypi.anaconda.org/scipp-nightly-wheels/simple/ --extra-index-url https://pypi.org/simple ``` -------------------------------- ### Importing Libraries for Polar Plots in Plopp Source: https://github.com/scipp/plopp/blob/main/docs/gallery/polar-plots.ipynb Imports necessary libraries including numpy, scipp, plopp, and matplotlib for creating polar plots. Sets the matplotlib backend to inline for displaying plots within the notebook and turns off interactive mode. ```python %matplotlib inline import numpy as np import scipp as sc import plopp as pp import matplotlib.pyplot as plt plt.ioff() ``` -------------------------------- ### Enabling Interactive Polar Plots in Plopp Source: https://github.com/scipp/plopp/blob/main/docs/gallery/polar-plots.ipynb Configures the environment for interactive polar plots using Plopp. Sets the Matplotlib backend to 'widget' for interactive plots and disables the initial display of the figure to prevent duplication. ```python %matplotlib widget plt.ioff() # Prevent the figure from showing up twice ``` -------------------------------- ### Enable Interactive Plots in Matplotlib Source: https://github.com/scipp/plopp/blob/main/docs/getting-started/overview.ipynb This command enables interactive plots in Jupyter notebooks using the Matplotlib widget backend. It needs to be executed at the start of the notebook. ```python %matplotlib widget ``` -------------------------------- ### Polar Image Plot with Plopp and Matplotlib Source: https://github.com/scipp/plopp/blob/main/docs/gallery/polar-plots.ipynb Creates a polar image plot using 2D data. Defines a Scipp DataArray and assigns coordinates for the x-axis in radians. The data is then plotted on polar axes using plopp. ```python da = pp.data.data2d(binedges=True, unit='K') da.coords['x'] = sc.linspace('x', 0, 2 * np.pi, da.sizes['x'] + 1, unit='rad') fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}) pp.plot(da, ax=ax) ``` -------------------------------- ### Loading mesh data from HDF5 file Source: https://github.com/scipp/plopp/blob/main/docs/plotting/mesh3d-plot.ipynb Loads mesh data (vertices and faces) from an HDF5 file using scipp's io module. The example uses the Utah teapot dataset. ```python dg = sc.io.load_hdf5(examples.teapot()) dg ``` -------------------------------- ### Declaring a package dependency with a specific version Source: https://github.com/scipp/plopp/blob/main/requirements/nightly.txt This line declares a dependency on the 'anywidget' package, specifying that version 0.9.13 should be installed. The '# via -r nightly.in' comment indicates that this dependency is listed in the 'nightly.in' file. ```Text anywidget==0.9.13 # via -r nightly.in ``` -------------------------------- ### Saving Thumbnail for Documentation Gallery Source: https://github.com/scipp/plopp/blob/main/docs/gallery/polar-plots.ipynb Saves the generated polar plot as a PNG image for use as a thumbnail in the documentation gallery. This snippet is intended for internal use and is hidden from the online documentation. ```python # This cell is used to generate the thumbnail for the docs gallery. # It is hidden from the online documentation. polar1d.save('../_static/gallery/polar-plots-thumbnail.png') ``` -------------------------------- ### Declaring a package dependency with multiple transitive dependencies Source: https://github.com/scipp/plopp/blob/main/requirements/nightly.txt This line declares a dependency on the 'traitlets' package, specifying that version 5.14.3 should be installed. The '# via comm', '# via ipympl', '# via ipython', '# via ipywidgets', '# via matplotlib-inline', '# via pythreejs', '# via traittypes' comments indicate that this dependency is required by multiple packages. ```Text traitlets==5.14.3 # via # comm # ipympl # ipython # ipywidgets # matplotlib-inline # pythreejs # traittypes ``` -------------------------------- ### Simple Polar Plot with Scipp DataArray Source: https://github.com/scipp/plopp/blob/main/docs/gallery/polar-plots.ipynb Generates a simple polar plot using scipp.DataArray for radial and angular coordinates. Creates a Matplotlib figure with polar projection, plots the data using plopp.plot, and enables grid lines. ```python # Make some spiral data N = 150 r = sc.linspace('theta', 0, 10, N, unit='m') theta = sc.linspace('theta', 0, 12, N, unit='rad') da = sc.DataArray(data=r, coords={'theta': theta}) # Construct figure axes with Matplotlib fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}) # Make the plot and tweak the axes polar1d = pp.plot(da, ax=ax, grid=True) polar1d ``` -------------------------------- ### Declaring a package dependency transitively Source: https://github.com/scipp/plopp/blob/main/requirements/nightly.txt This line declares a dependency on the 'asttokens' package, specifying that version 3.0.0 should be installed. The '# via stack-data' comment indicates that this dependency is required by the 'stack-data' package. ```Text asttokens==3.0.0 # via stack-data ``` -------------------------------- ### Importing Libraries for Data Masking Source: https://github.com/scipp/plopp/blob/main/docs/gallery/masking-a-range.ipynb Imports necessary libraries including plopp for plotting, scipp for scientific data structures, and ipywidgets for interactive widgets. These libraries are essential for creating the interactive data masking example. ```python %matplotlib widget import plopp as pp import scipp as sc import ipywidgets as ipw ``` -------------------------------- ### Declaring a package dependency with multiple transitive dependencies Source: https://github.com/scipp/plopp/blob/main/requirements/nightly.txt This line declares a dependency on the 'exceptiongroup' package, specifying that version 1.2.2 should be installed. The '# via ipython' and '# via pytest' comments indicate that this dependency is required by both the 'ipython' and 'pytest' packages. ```Text exceptiongroup==1.2.2 # via # ipython # pytest ``` -------------------------------- ### Declaring a package dependency with multiple transitive dependencies Source: https://github.com/scipp/plopp/blob/main/requirements/nightly.txt This line declares a dependency on the 'numpy' package, specifying that version 2.2.3 should be installed. The '# via contourpy', '# via h5py', '# via ipydatawidgets', '# via ipympl', '# via matplotlib', '# via mpltoolbox', '# via pandas', '# via pythreejs', '# via scipp', '# via scipy', '# via xarray' comments indicate that this dependency is required by multiple packages. ```Text numpy==2.2.3 # via # contourpy # h5py # ipydatawidgets # ipympl # matplotlib # mpltoolbox # pandas # pythreejs # scipp # scipy # xarray ``` -------------------------------- ### Declaring a package dependency with multiple transitive dependencies Source: https://github.com/scipp/plopp/blob/main/requirements/nightly.txt This line declares a dependency on the 'ipywidgets' package, specifying that version 8.1.5 should be installed. The '# via -r nightly.in', '# via anywidget', '# via ipydatawidgets', '# via ipympl', '# via pythreejs' comments indicate that this dependency is required by multiple packages. ```Text ipywidgets==8.1.5 # via # -r nightly.in # anywidget # ipydatawidgets # ipympl # pythreejs ``` -------------------------------- ### Interactive Polar Plot with Slicer Source: https://github.com/scipp/plopp/blob/main/docs/gallery/polar-plots.ipynb Generates an interactive polar plot using Plopp's slicer function. Creates a 2D Scipp DataArray with random data and angular coordinates, then uses plopp.slicer to create an interactive plot with sliders for exploring the data. ```python # Make data N = 50 r = np.random.normal(loc=50, scale=5, size=(N, N)) theta = np.radians(np.linspace(180, 200, N)) phi = np.radians(np.linspace(0, 90, N)) da = sc.DataArray( data=sc.array(dims=['phi', 'theta'], values=r, unit='m'), coords={ 'theta': sc.array(dims=['theta'], values=theta, unit='rad'), 'phi': sc.array(dims=['phi'], values=phi, unit='rad'), }, ) # Make axes fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}) ax.set_rorigin(0) # Use slicer plot pp.slicer(da, ax=ax, grid=True, autoscale=False) ``` -------------------------------- ### Plotting a Sector on Polar Axes Source: https://github.com/scipp/plopp/blob/main/docs/gallery/polar-plots.ipynb Demonstrates plotting data on polar axes where the angular coordinate does not wrap around 2π. Generates random data for the radius and defines angular coordinates in radians, then plots the sector using plopp. ```python # Make data N = 50 r = np.random.normal(loc=50, scale=5, size=N) theta = np.radians(np.linspace(180, 200, N)) da = sc.DataArray( data=sc.array(dims=['theta'], values=r, unit='m'), coords={'theta': sc.array(dims=['theta'], values=theta, unit='rad')}, ) # Make axes and plot fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}) ax.set_rorigin(0) pp.plot(da, ax=ax, grid=True) ``` -------------------------------- ### Import Plopp and Create Sample Data Source: https://github.com/scipp/plopp/blob/main/docs/plotting/slicer-plot.ipynb This snippet imports the Plopp library and generates a 3D data cube using `pp.data.data3d()`. The `%matplotlib widget` magic command enables interactive plots in Jupyter notebooks. ```python %matplotlib widget import plopp as pp da = pp.data.data3d() ``` -------------------------------- ### Importing Libraries for Data Visualization Source: https://github.com/scipp/plopp/blob/main/docs/customization/custom-interfaces.ipynb Imports necessary libraries for data visualization and numerical computation. Includes plopp for plotting, scipp for data arrays, and numpy for numerical operations. `%matplotlib widget` enables interactive plots in Jupyter notebooks. ```python %matplotlib widget import plopp as pp import scipp as sc import numpy as np ``` -------------------------------- ### Import necessary libraries Source: https://github.com/scipp/plopp/blob/main/docs/gallery/tiled-random-samples.ipynb Imports the required libraries: numpy for random number generation, scipp for data handling, plopp for plotting, and collections.abc for abstract base classes. ```python import numpy as np import scipp as sc import plopp as pp from collections.abc import Callable, Generator ``` -------------------------------- ### Importing Scipp and Plopp Source: https://github.com/scipp/plopp/blob/main/docs/plotting/line-plot.ipynb Imports the necessary libraries, scipp for data handling and plopp for plotting. ```python import scipp as sc import plopp as pp ``` -------------------------------- ### Importing Scipp and Plopp Source: https://github.com/scipp/plopp/blob/main/docs/plotting/image-plot.ipynb This snippet imports the necessary libraries, scipp for data handling and plopp for plotting. ```python import scipp as sc import plopp as pp ``` -------------------------------- ### Create key-argument name strings Source: https://github.com/scipp/plopp/blob/main/docs/gallery/tiled-random-samples.ipynb Defines functions to create descriptive names for the keyword arguments, used for labeling the plots. `key_arg_name` joins a key and argument with a colon. `keys_args_name` joins multiple key-argument names with commas. ```python def key_arg_name(key: str, arg) -> str: return ": ".join([key, str(arg)]) def keys_args_name(**kwargs) -> str: return ",".join([key_arg_name(key, arg) for key, arg in kwargs.items()]) ``` -------------------------------- ### Plot multiple DataArrays using Plopp Source: https://github.com/scipp/plopp/blob/main/docs/getting-started/overview.ipynb Plot multiple Scipp DataArrays together by passing a Python dictionary to the `pp.plot()` function. This example also demonstrates how uncertainties are displayed as error bars. ```python pp.plot({'temp1': da1, 'temp2': da2}) ``` -------------------------------- ### Importing Libraries for Scatter3d Plot Source: https://github.com/scipp/plopp/blob/main/docs/plotting/scatter3d-plot.ipynb This snippet imports the necessary libraries for creating scatter3d plots using plopp, scipp, and numpy. It sets up the environment for subsequent data generation and plotting. ```python import plopp as pp import scipp as sc import numpy as np ``` -------------------------------- ### Import Plopp and Scipp Source: https://github.com/scipp/plopp/blob/main/docs/gallery/interactive-masking.ipynb Imports the necessary libraries: plopp for plotting and scipp for scientific data structures. The `%matplotlib widget` magic command enables interactive plots in Jupyter notebooks. ```python %matplotlib widget import plopp as pp import scipp as sc ``` -------------------------------- ### Creating a Data Node and Image Figure Source: https://github.com/scipp/plopp/blob/main/docs/customization/custom-interfaces.ipynb Creates a data node from a Scipp DataArray using `plopp.Node`. An image figure is then created from the data node using `plopp.imagefigure`. The graph structure is displayed using `plopp.show_graph`. ```python data_node = pp.Node(da) fig = pp.imagefigure(data_node) pp.show_graph(data_node) # display the graph ``` -------------------------------- ### Class Documentation Template Source: https://github.com/scipp/plopp/blob/main/docs/_templates/scipp-class-template.rst This Jinja2 template generates documentation for a class, including its full name, module, members, special members (like __getitem__), and a summary of its methods and attributes. It uses the 'autoclass' and 'automethod' directives to automatically extract documentation from the class definition. ```Jinja2 {{ fullname | escape | underline }} .. currentmodule:: {{ module }} .. autoclass:: {{ objname }} :members: :special-members: __getitem__ {% block methods %} .. automethod:: __init__ {% if methods %} .. rubric:: {{ _('Methods') }} .. autosummary:: {% for item in methods %} ~{{ name }}.{{ item }} {%- endfor %} {% endif %} {% endblock %} {% block attributes %} {% if attributes %} .. rubric:: {{ _('Attributes') }} .. autosummary:: {% for item in attributes %} ~{{ name }}.{{ item }} {%- endfor %} {% endif %} {% endblock %} ``` -------------------------------- ### Importing Plopp and Scipp Source: https://github.com/scipp/plopp/blob/main/docs/gallery/peeling-layers.ipynb Imports the necessary libraries, plopp for plotting and scipp for scientific data structures. ```python import plopp as pp import scipp as sc ``` -------------------------------- ### Displaying the Plopp Graph Source: https://github.com/scipp/plopp/blob/main/docs/customization/custom-interfaces.ipynb This snippet shows how to display the graph of the Plopp figure, which helps visualize the data flow and dependencies between nodes. ```python pp.show_graph(fig) ``` -------------------------------- ### Importing scipp and plopp Source: https://github.com/scipp/plopp/blob/main/docs/plotting/mesh3d-plot.ipynb Imports the necessary libraries: scipp for scientific data structures and plopp for plotting. ```python import scipp as sc import plopp as pp from plopp.data import examples ``` -------------------------------- ### Displaying the Figure in the Notebook Source: https://github.com/scipp/plopp/blob/main/docs/customization/custom-interfaces.ipynb Displays the created figure directly in the Jupyter notebook. This allows for interactive visualization of the data. ```python fig ``` -------------------------------- ### Creating Figures in Plopp Source: https://github.com/scipp/plopp/blob/main/docs/customization/custom-interfaces.ipynb Creates an image figure and a line figure in Plopp, connected to the `hide_node` and `slice_node` respectively. Requires the `plopp` library. ```python fig2d = pp.imagefigure(hide_node) fig1d = pp.linefigure(slice_node) pp.show_graph(masks_node) ``` -------------------------------- ### Generate keyword arguments for random functions Source: https://github.com/scipp/plopp/blob/main/docs/gallery/tiled-random-samples.ipynb Defines a generator function that yields dictionaries of keyword arguments for the random sample generators. It uses itertools.product to create all possible combinations of arguments. ```python def generate_kwargs(arguments_map: dict[str, list]) -> Generator[dict, None, None]: from itertools import product key_arg_pairs = [ [(key, val) for val in values] for key, values in arguments_map.items() ] for arguments in product(*key_arg_pairs): yield {str(args[0]): args[1] for args in arguments} ``` -------------------------------- ### Make a 3D DataArray with Random Values Source: https://github.com/scipp/plopp/blob/main/docs/customization/graph-node-tips.ipynb Creates a 3D Scipp DataArray `da` filled with random values using `pp.data.random`. This DataArray will be used for demonstrating the slicer plot. ```python # Make a 3D array with random values da = pp.data.random((100, 150, 200)) da ``` -------------------------------- ### Create Visualization Interface with Custom Tool Source: https://github.com/scipp/plopp/blob/main/docs/gallery/interactive-masking.ipynb Creates the visualization interface using Plopp. It defines a node for the data array and a node for applying masks. It then creates an image figure and adds the custom `RectangleTool` to the toolbar, enabling interactive masking. ```python data_node = pp.Node(da) def apply_masks(da, *masks): out = da.copy(deep=False) for i, mask in enumerate(masks): out.masks[str(i)] = mask return out masking_node = pp.Node(apply_masks, data_node) fig = pp.imagefigure(masking_node, norm='log') r = RectangleTool( figure=fig, input_node=data_node, func=define_mask, destination=masking_node ) fig.toolbar['roi'] = r ``` -------------------------------- ### Importing Plopp and Scipp Source: https://github.com/scipp/plopp/blob/main/docs/plotting/scatter-plot.ipynb Imports the necessary libraries, Plopp for plotting and Scipp for data handling. ```python import plopp as pp import scipp as sc ``` -------------------------------- ### Generating Thumbnail for Documentation Gallery Source: https://github.com/scipp/plopp/blob/main/docs/gallery/nyc-taxi.ipynb This snippet generates a thumbnail image for the documentation gallery. It sets the aspect ratio of the 2D plot to 'equal' and saves the figure as a PNG file. ```python # This cell is used to generate the thumbnail for the docs gallery. # It is hidden from the online documentation. fig2d.ax.set_aspect('equal') fig2d.save('../_static/gallery/nyc-taxi-thumbnail.png') ``` -------------------------------- ### Displaying Widgets and Figures in a Box Layout Source: https://github.com/scipp/plopp/blob/main/docs/customization/custom-interfaces.ipynb Displays the slider, masks widget, 2D figure, and 1D figure in a Box layout using `ipywidgets`. Requires the `ipywidgets` library. ```python Box([[slider, masks_widget], fig2d, fig1d]) ``` -------------------------------- ### Basic Image Plot with Plopp Source: https://github.com/scipp/plopp/blob/main/docs/plotting/image-plot.ipynb This snippet demonstrates how to create a basic 2D image plot using the `plot` function in Plopp. It uses the `data2d` function to generate sample data. ```python da = pp.data.data2d() da.plot() ``` -------------------------------- ### Importing Plopp and Scipp Source: https://github.com/scipp/plopp/blob/main/docs/gallery/rectangle-selection.ipynb Imports the necessary libraries: plopp for plotting and scipp for scientific data structures. Also sets up the matplotlib widget. ```python %matplotlib widget import plopp as pp import scipp as sc ``` -------------------------------- ### Activate Tool and Simulate Clicks Source: https://github.com/scipp/plopp/blob/main/docs/gallery/interactive-masking.ipynb Activates the rectangle tool and simulates clicks on the figure to create rectangles. These rectangles will define the areas to be masked. ```python r.value = True r._tool.click(50, 200) r._tool.click(200, 250) r._tool.click(30, 50) r._tool.click(250, 170) ``` -------------------------------- ### Displaying the Updated Graph Source: https://github.com/scipp/plopp/blob/main/docs/customization/custom-interfaces.ipynb Displays the updated graph structure, including the data node, smoothing node, and image figure. This visualization helps understand the data flow and dependencies in the graph. ```python pp.show_graph(data_node) ``` -------------------------------- ### Create a Gaussian Filter Node with Slider Source: https://github.com/scipp/plopp/blob/main/docs/customization/graph-node-tips.ipynb Creates a node graph for applying a Gaussian filter to a 3D DataArray. It includes a slider to control the smoothing width, a node for the slider value, and a node for the Gaussian filter operation. It imports ipywidgets for the slider and gaussian_filter from scipp.scipy.ndimage. ```python import ipywidgets as ipw from scipp.scipy.ndimage import gaussian_filter # Raw data root node data_node = pp.Node(da) # Slider to control width of smoothing kernel slider = ipw.IntSlider(min=1, max=20, description="Smoothing") slider_node = pp.widget_node(slider) # Node that performs the gaussian smoothing smooth_node = pp.Node(gaussian_filter, data_node, sigma=slider_node) pp.show_graph(smooth_node) ``` -------------------------------- ### Creating a Data Node in Plopp Source: https://github.com/scipp/plopp/blob/main/docs/customization/custom-interfaces.ipynb Creates a Plopp Node from a Scipp DataArray. This node can then be used as input to other nodes in the Plopp graph. Requires the `plopp` library. ```python data_node = pp.Node(da) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/scipp/plopp/blob/main/docs/getting-started/overview.ipynb Import NumPy, Scipp, and Plopp libraries for data manipulation and plotting. ```python import numpy as np import scipp as sc import plopp as pp ``` -------------------------------- ### Plotting 1D Data with Plopp Source: https://github.com/scipp/plopp/blob/main/docs/getting-started/saving-figures.ipynb This snippet initializes and plots 1D data using the Plopp library. It creates a 1D data array and then generates a plot of that data, displaying the resulting figure. ```python import plopp as pp da1d = pp.data.data1d() f1d = pp.plot(da1d) f1d ``` -------------------------------- ### Create Noisy Signal DataArray and Plot Source: https://github.com/scipp/plopp/blob/main/docs/customization/graph-node-tips.ipynb Generates noisy signal data using NumPy, creates a Scipp DataArray from it, and then creates a Plopp node `a` containing the DataArray. Finally, it plots the data using `pp.linefigure`. ```python noise = 0.5 * (np.random.random(100) - 0.5) signal = np.sin(0.1 * np.arange(100.0)) + noise # Noisy data a = pp.Node( sc.DataArray( data=sc.array(dims=['time'], values=signal), coords={'time': sc.arange('time', 100.0, unit='s')}, ) ) fig = pp.linefigure(a) fig ``` -------------------------------- ### Define random sample generators and arguments Source: https://github.com/scipp/plopp/blob/main/docs/gallery/tiled-random-samples.ipynb Defines a dictionary mapping numpy.random functions to their respective arguments. This allows for easy iteration and generation of random samples with different parameters. ```python pdf_maps = { np.random.uniform: {'low': [0], 'high': [0.5, 1, 2]}, np.random.normal: {'loc': [0], 'scale': [0.5, 1, 2]}, np.random.gumbel: {'loc': [0], 'scale': [0.5, 1, 2]}, np.random.laplace: {'loc': [0], 'scale': [0.5, 1, 2]}, np.random.gamma: {'shape': [1, 2, 4], 'scale': [1]}, np.random.beta: {'a': [1, 2], 'b': [1, 2]}, np.random.chisquare: {'df': [0.1, 1, 2]}, np.random.poisson: {'lam': [1, 2, 3]}, np.random.binomial: {'n': [1, 2, 3, 4, 5], 'p': [0.5, 0.5]}, np.random.logseries: {'p': [0.25, 0.5, 0.75]}, np.random.pareto: {'a': [16, 24, 32]}, np.random.geometric: {'p': [0.5, 0.7, 0.9]}, np.random.power: {'a': [1, 2, 4]}, np.random.triangular: {'left': [0], 'right': [1], 'mode': [0.2, 0.4, 0.8]}, np.random.vonmises: {'mu': [0], 'kappa': [1, 2, 4]}, np.random.exponential: {'scale': [1, 2, 3]}, np.random.wald: {'mean': [1], 'scale': [16, 32, 64]}, np.random.weibull: {'a': [2, 4, 8, 16]}, np.random.f: {'dfnum': [100], 'dfden': [100]}, np.random.rayleigh: {'scale': [2, 3, 4]}, } ``` -------------------------------- ### Creating Multiple Views: 2D Image and 1D Line Plot with Smoothing Source: https://github.com/scipp/plopp/blob/main/docs/customization/custom-interfaces.ipynb This snippet demonstrates how to create multiple views of the same data in Plopp, including a 2D image of the smoothed data and a 1D line plot showing the sum of both the raw and smoothed data along the vertical dimension. It uses a slider to control the smoothing and displays both figures together. ```python data_node = pp.Node(da) slider = ipw.IntSlider(min=1, max=20, value=10) slider_node = pp.widget_node(slider) smooth_node = pp.Node(gaussian_filter, data_node, sigma=slider_node) fig2d = pp.imagefigure(smooth_node) # Sum the raw data along the vertical dimension sum_raw = pp.Node(sc.sum, data_node, dim='y') # Sum the smoothed data along the vertical dimension sum_smoothed = pp.Node(sc.sum, smooth_node, dim='y') # Give two nodes to a figure to display both on the same axes fig1d = pp.linefigure(sum_raw, sum_smoothed) ``` -------------------------------- ### Plotting 2D Data with Plopp Widget Source: https://github.com/scipp/plopp/blob/main/docs/getting-started/saving-figures.ipynb This snippet initializes and plots 2D data using the Plopp library with the `%matplotlib widget` backend. It creates a 2D data array and then generates a plot of that data, displaying the resulting interactive figure in the notebook. ```python %matplotlib widget da2d = pp.data.data2d() f2d = pp.plot(da2d) f2d ``` -------------------------------- ### Creating a basic 3D mesh plot Source: https://github.com/scipp/plopp/blob/main/docs/plotting/mesh3d-plot.ipynb Creates a 3D mesh plot using plopp.mesh3d, specifying vertices, faces, and vertex colors based on the z-coordinate of the vertices. ```python pp.mesh3d( vertices=dg["vertices"], faces=dg["faces"], vertexcolors=dg["vertices"].fields.z, ) ``` -------------------------------- ### Interactive Slicing and Plotting with Plopp Source: https://github.com/scipp/plopp/blob/main/docs/gallery/nyc-taxi.ipynb This snippet creates an interactive visualization with a slider to control the hour-of-day slice, a 2D map, and a 1D plot with Gaussian smoothing. It uses plopp nodes to define the data processing pipeline and ipywidgets for the slider. ```python # Slider node that provides index to slice slider = ipywidgets.IntSlider(description='Hour:', min=0, max=23) slider_node = pp.widget_node(slider) # Node that actually does the slicing slice_node = pp.Node(lambda da, ind: da['hour', ind], da=data, ind=slider_node) # Add a 2D figure to show the NYC map fig2d = pp.imagefigure(slice_node, norm='log') # Add a node after the slicing to sum along the latitude dimension sum_lat = pp.Node(sc.sum, slice_node, dim='latitude') # Add a node after the sum that performs as Gaussian smoothing smooth = pp.Node(gaussian_filter, sum_lat, sigma=5) # Add a 1D figure that will display both raw sum and smoothed data fig1d = pp.linefigure(sum_lat, smooth, norm='log') widgets.Box([slider, fig2d, fig1d]) # Container box ``` -------------------------------- ### Generate and plot histograms for each distribution Source: https://github.com/scipp/plopp/blob/main/docs/gallery/tiled-random-samples.ipynb Iterates through the defined probability distribution functions and their arguments, generates histograms using the `sample_and_hist` function, and plots them using plopp. The plots are stored in a dictionary for later use. ```python plots = {} for pdf, arguments_map in pdf_maps.items(): hists = { keys_args_name(**kwargs): sample_and_hist(pdf, size=10_000, **kwargs) for kwargs in generate_kwargs(arguments_map) } plot = pp.plot(hists, title=f"{pdf.__name__} distribution", alpha=0.8, linewidth=4) plots[pdf.__name__] = plot ``` -------------------------------- ### Display the Figure Source: https://github.com/scipp/plopp/blob/main/docs/gallery/interactive-masking.ipynb Displays the Plopp figure with the applied masks. This shows the interactive masking in action. ```python fig ``` -------------------------------- ### Calling a Data Node Source: https://github.com/scipp/plopp/blob/main/docs/customization/custom-interfaces.ipynb Demonstrates calling a data node to retrieve the underlying data. In this case, calling `data_node()` returns the original Scipp DataArray. ```python data_node() ``` -------------------------------- ### Simple Scatter Plot with Plopp Source: https://github.com/scipp/plopp/blob/main/docs/plotting/scatter-plot.ipynb Creates a basic scatter plot using the `pp.scatter` function with default settings. ```python a = pp.data.scatter() pp.scatter(a) ``` -------------------------------- ### Add Data from Two Nodes Using a Function Source: https://github.com/scipp/plopp/blob/main/docs/customization/graph-node-tips.ipynb Defines a function `add` that adds two inputs and then creates a Plopp node `c` that uses this function to add the data from nodes `a` and `b`. This demonstrates the 'classical' way of performing operations on nodes. ```python def add(x, y): return x + y c = pp.Node(add, a, b) c() ``` -------------------------------- ### Displaying the Smoothed Data Figure Source: https://github.com/scipp/plopp/blob/main/docs/customization/custom-interfaces.ipynb Displays the figure with the smoothed data. The Gaussian filter applied in the previous step results in a smoother visualization of the data. ```python fig ``` -------------------------------- ### Import ipywidgets for interactive plot Source: https://github.com/scipp/plopp/blob/main/docs/customization/subplots.ipynb Import ipywidgets for interactive plot ```python %matplotlib widget import ipywidgets as ipw ``` -------------------------------- ### Basic Line Plot with Plopp Source: https://github.com/scipp/plopp/blob/main/docs/plotting/line-plot.ipynb Creates a basic line plot using the plopp.plot() function on a Scipp DataArray. ```python da = pp.data.data1d() da.plot() ``` -------------------------------- ### Create a 2D Scipp DataArray Source: https://github.com/scipp/plopp/blob/main/docs/getting-started/overview.ipynb Create a 2D Scipp DataArray with coordinates and data values for plotting. ```python size = 50 rng = np.random.default_rng(seed=0) x = sc.linspace('x', 1.0, 300.0, num=size, unit='m') time = sc.linspace('time', 1.0, 200.0, num=2 * size, unit='us') temp = sc.array(dims=['x', 'time'], values=rng.random((size, 2 * size)), unit='K') temp += sc.linspace('x', 100, 105, num=size, unit='K') da = sc.DataArray(temp, coords={'x': x, 'time': time}) da.name = 'temperature' # Data array name is optional and will be used as a label ``` -------------------------------- ### Show the Graph Source: https://github.com/scipp/plopp/blob/main/docs/gallery/interactive-masking.ipynb Displays the graph representation of the figure, showing the data flow and the nodes involved in the masking process. ```python pp.show_graph(fig) ``` -------------------------------- ### Creating a 2D Data Array with Scipp Source: https://github.com/scipp/plopp/blob/main/docs/customization/custom-interfaces.ipynb Generates a 2D data array using numpy and scipp. The data is created using a sine function with added random noise. The data array includes coordinates for x and y dimensions, and the values have units of Kelvin. ```python nx = 200 ny = 150 x = np.arange(float(nx)) y = np.arange(float(ny)) noise = np.random.random((ny, nx)) z = 3.0 * np.sin(np.sqrt(x**2 + y.reshape(ny, 1) ** 2) / 10.0) + noise + 300.0 da = sc.DataArray( data=sc.array(dims=['y', 'x'], values=z, unit='K'), coords={ 'x': sc.array(dims=['x'], values=x, unit='m'), 'y': sc.array(dims=['y'], values=y, unit='m'), }, ) da ``` -------------------------------- ### Displaying the Slider Node Graph Source: https://github.com/scipp/plopp/blob/main/docs/customization/custom-interfaces.ipynb This snippet shows how to display the graph of the slider node, which helps visualize the data flow and dependencies related to the slider widget. ```python pp.show_graph(slider_node) ``` -------------------------------- ### Jinja2 Template for Class Documentation Source: https://github.com/scipp/plopp/blob/main/docs/_templates/class-template.rst This Jinja2 template generates documentation for a Python class using Sphinx directives. It includes class name, module, members, special members, and supports custom blocks for methods and attributes. ```Jinja2 {{ fullname | escape | underline }} .. currentmodule:: {{ module }} .. autoclass:: {{ objname }} :members: :special-members: __getitem__ {% block methods %} .. automethod:: __init__ {% if methods %} .. rubric:: {{ _('Methods') }} .. autosummary:: {% for item in methods %} ~{{ name }}.{{ item }} {%- endfor %} {% endif %} {% endblock %} {% block attributes %} {% if attributes %} .. rubric:: {{ _('Attributes') }} .. autosummary:: {% for item in attributes %} ~{{ name }}.{{ item }} {%- endfor %} {% endif %} {% endblock %} ``` -------------------------------- ### Displaying the Graph of Connected Nodes with Plopp Source: https://github.com/scipp/plopp/blob/main/docs/gallery/nyc-taxi.ipynb This snippet displays the graph of connected nodes for the interactive visualization using plopp.show_graph. It helps visualize the data processing pipeline. ```python pp.show_graph(fig1d) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/scipp/plopp/blob/main/docs/gallery/scatter3d-with-slider.ipynb Imports the required libraries: plopp for plotting, plopp.widgets for creating widgets, scipp for scientific data structures, and numpy for numerical operations. ```python import plopp as pp import plopp.widgets as pw import scipp as sc import numpy as np ``` -------------------------------- ### Importing Libraries for Plotting with Plopp Source: https://github.com/scipp/plopp/blob/main/docs/customization/tweaking-figures.ipynb This snippet imports the necessary libraries for creating plots with Plopp, including scipp, plopp, numpy, and matplotlib.pyplot. It also defines a sample DataArray for plotting. ```python %matplotlib inline import scipp as sc import plopp as pp import numpy as np import matplotlib.pyplot as plt da = pp.data.data1d() ``` -------------------------------- ### Create Noise DataArray and Subtract from Signal Source: https://github.com/scipp/plopp/blob/main/docs/customization/graph-node-tips.ipynb Creates a Scipp DataArray containing noise data and creates a Plopp node `b` from it. It then subtracts the noise (node `b`) from the signal (node `a`) using the `-` operator and plots the result using `pp.linefigure`. ```python b = pp.Node( sc.DataArray( data=sc.array(dims=['time'], values=noise), coords={'time': sc.arange('time', 100.0, unit='s')}, ) ) # Remove noise from signal diff = a - b pp.linefigure(diff) ``` -------------------------------- ### Loading and Preparing Xarray Data Source: https://github.com/scipp/plopp/blob/main/docs/getting-started/numpy-pandas-xarray.ipynb This snippet loads an Xarray dataset and prepares it for plotting with Plopp. It removes attributes that are not well-handled by Scipp and sets the units for the latitude coordinate. ```python import xarray as xr air = xr.tutorial.open_dataset("air_temperature").air # We modify a few entries which are not well handled by Scipp del air.attrs['precision'] del air.attrs['GRIB_id'] del air.attrs['actual_range'] air.coords['lat'].attrs['units'] = 'degrees' air ``` -------------------------------- ### Creating a Checkboxes Widget in Plopp Source: https://github.com/scipp/plopp/blob/main/docs/customization/custom-interfaces.ipynb Creates a Checkboxes widget from the `plopp.widgets` module, populated with the keys from the DataArray's masks. This widget allows toggling the masks on and off. Requires the `plopp` library. ```python from plopp.widgets import Checkboxes, Box masks_widget = Checkboxes(da.masks.keys()) masks_widget ``` -------------------------------- ### Create and plot a 1D Scipp DataArray Source: https://github.com/scipp/plopp/blob/main/docs/getting-started/overview.ipynb Create a 1D Scipp DataArray with coordinates and plot it using the `.plot()` method. The plot will display the data values against the 'x' coordinate. ```python size = 50 rng = np.random.default_rng(seed=0) x = sc.linspace('x', 0.0, 2.0, num=size, unit='m') y = sc.linspace('y', 0.0, 1.0, num=5, unit='us') temp1 = sc.array(dims=['x'], values=rng.random(size), unit='K') temp1 += sc.linspace('x', 100, 105, num=size, unit='K') da1 = sc.DataArray(temp1, coords={'x': x}) da1.name = 'temp1' # Data array name is optional and will be used as a label temp2 = sc.array(dims=['x'], values=rng.random(size), unit='K') temp2.variances = 0.5 * (temp2.values + 0.5) temp2 += sc.linspace('x', 99, 102, num=size, unit='K') da2 = sc.DataArray(temp2, coords={'x': x}) ``` ```python da1.plot() ``` -------------------------------- ### Create four plots with specified figure size Source: https://github.com/scipp/plopp/blob/main/docs/customization/subplots.ipynb Create four plots with specified figure size ```python subplot_size = (4, 3) p1 = pp.plot(da['z', 0], figsize=subplot_size) p2 = pp.plot(da['z', 0]['y', 0], figsize=subplot_size) p3 = pp.plot(da['x', 0]['y', 0], figsize=subplot_size) p4 = pp.plot(da['x', -1], cmap='magma', figsize=subplot_size) ```