MatterViz

repository·main·Indexed 43 days ago

https://github.com/janosh/matterviz

Interactive visualizations for materials science, providing tools for 3D crystal structures, molecular systems, MD trajectories, periodic tables, and spectral data. Available as a VSCode extension, a JupyterLab extension (requires JupyterLab 4), and an npm toolkit for web projects. Supports a wide range of formats including CIF, POSCAR, XYZ, TRAJ, HDF5, and volumetric data like CUBE and CHGCAR. Version 0.7.0.

Tokens
124.6K
Snippets
404
Records
499
Agent score
56%

What's inside MatterViz

  1. Overview of MatterViz toolkit

    main

    MatterViz is a toolkit designed for building interactive web UIs specifically for materials science. It provides components for visualizing a wide range of scientific data, including:

    • 3D Structures: Crystal structures, molecules, and MD/relaxation trajectories.
    • Chemical Data: Periodic tables, phase diagrams, and element details.
    • Spectral & Diffraction Data: Spectral bands, DOS, IR/Raman, XRD, SAED, and PDF/RDF.
    • Analysis Visualizations: Convex hulls, diffusion analysis (MSD), reaction paths (NEB), heatmaps, and scatter plots.
  2. Configure vector color modes in MatterViz

    main

    MatterViz supports several color modes for visualizing vector data. These modes determine how the direction and magnitude of vectors are mapped to colors.

    Available Color Modes

    • auto: Automatically maps force* keys to element colors and magmom/spin keys to signed-z colors.
    • element: Colors vectors based on the element type.
    • spin direction: Colors vectors based on their orientation (e.g., red for up, blue for down).
    • magnitude: Uses the vector_color_scale to map vector length to color.
    • uniform: Uses the vector_color setting for a single uniform color.

    Note: When multiple vector keys are present, multi-key data receives a distinct, editable color per key.

  3. Handle line clipping with fixed axis ranges

    main

    When using fixed ranges for axes via x_axis.range or y_axis.range, any lines in the series that extend beyond these boundaries are automatically clipped at the plot edges using a clipPath. This ensures that data points or lines outside the specified viewport do not bleed into the axis labels or surrounding UI.

    <ScatterPlot
      series={clipping_series.map((srs) => ({ ...srs, markers: 'line' }))}
      x_axis={{ range: [-5, 5], label: 'X Axis (Fixed Range)' }}
      y_axis={{ range: [-5, 5], label: 'Y Axis (Fixed Range)' }}
      style="height: 400px"
    />
  4. Use the MatterViz anywidget bundle in notebook environments

    main

    The matterviz-anywidget bundle is a prebuilt ESM module designed to render MatterViz components in notebook environments like Jupyter, marimo, and VS Code.

    It works by using anywidget.ts as an entry point that dispatches to specific MatterViz Svelte components based on a widget_type string. It automatically forwards traitlet values as props to the component. The bundle is self-contained, inlining the Svelte runtime, three.js, and other dependencies into a single .js file and a corresponding .css file.

    To use it in a custom Python or JS wrapper, call the default export's render method with an anywidget-compatible model that implements a get(key) method to provide the widget_type and required props.

    // Example of how a consumer might call the render method
    // The model must expose get(key) for widget_type and props
    import matterviz from 'matterviz-anywidget';
    
    await matterviz.render({ model, el });
  5. Configure Marginal Distributions in ScatterPlot

    main

    Marginal distributions are summary plots (strips) displayed alongside the main plot. The marginals prop is a layered API that can be configured per side (top, right, bottom, left).

    Supported Built-in Types

    • histogram
    • kde (Kernel Density Estimation)
    • cdf (Cumulative Distribution Function)
    • rug

    Configuration Options

    For each side, you can pass an object to control:

    • type: The distribution type (e.g., 'histogram').
    • per_series: Boolean. If true, shows one curve per series; if false, shows one merged curve.
    • placement: Where the strip sits relative to the axis. Options: 'auto', 'flush', or 'outer'.
    • size: The size of the marginal strip.
    • bins: (For histograms) Number of bins.
    • bandwidth: (For KDE) Use 'silverman', 'scott', or a specific number.
    • curve: (For KDE) The interpolation curve.
    • normalize: (For histograms) 'count', 'density', or 'probability'.
    • axis: Bind to a secondary axis ('x2' or 'y2').
    • data: Provide external data via number[] or a function (ctx) => number[].
    • reduce: Compute a bespoke curve via (values, weights, ctx) => MarginalCurve.

    Custom Marginal Snippets

    If built-ins are insufficient, use the snippet key to provide a custom Svelte snippet. The snippet receives a context object: { rect, positional_scale, value_scale, baseline, curves, series }.

    <ScatterPlot
      {series}
      marginals={{
        top: { type: 'histogram', bins: 40, fill: '#0ca678', normalize: 'density' },
        right: { type: 'kde', bandwidth: 'scott', curve: 'natural' },
      }}
    />
  6. Requirements for Equation of State (EOS) fitting

    main

    When performing an Equation of State fit using fit_eos or EosPlot, ensure your data meets the following criteria:

    1. Minimum Data Points: You need at least four volume points.
    2. Bracketing the Minimum: The volumes must bracket the energy minimum ($V_0$). A scan that lies entirely on one side of the equilibrium volume will be refused (consistent with pymatgen behavior).
    3. Noise Handling: The fitting algorithm is robust to moderate noise (e.g., ~1 meV) and can handle cases where the energy minimum is located via the curvature of neighboring points rather than a single absolute minimum point.
  7. Use logarithmic and arcsinh scales in Histograms

    main

    For data spanning multiple orders of magnitude, use non-linear scales.

    • Log Scale: Set scale_type: 'log' in the x_axis or y_axis object. Bins are calculated as equal-ratio bins (uniform in log10 x).
    • Arcsinh Scale: Set scale_type: 'asinh' in the x_axis or y_axis object. This is useful for handling data that includes zero or negative values while maintaining logarithmic-like behavior for large values.

    When switching scales, the component automatically re-bins the samples so that bar widths remain visually uniform on the screen.

    <Histogram
      {series}
      x_axis={{ scale_type: 'log' }}
      y_axis={{ scale_type: 'linear' }}
    />
  8. Assign Axis Groups and Units to Series

    main

    You can control how series are grouped on axes using metadata within the series object:

    • unit: Grouping compatible values onto a single axis by providing a common unit string. The component infers labels and scales based on the visible series.
    • axis_group: Explicitly separates series that require an independent scale, even if they share the same units. Providing a unique string to axis_group creates a new axis group for that series.
    <script lang="ts">
      import { ScatterPlot } from 'matterviz'
    
      const series = [
        {
          x: [0, 1, 2],
          y: [10, 20, 30],
          label: `Total energy`,
          unit: `eV`,
          markers: `line+points` as const,
        },
        {
          x: [0, 1, 2],
          y: [0.1, 0.01, 0.001],
          label: `SCF residual`,
          unit: `eV`,
          axis_group: `scf-residual`,
          markers: `line+points` as const,
        },
      ]
    </script>
    
    <ScatterPlot {series} />
  9. Configure BarPlot modes and orientation

    main

    The BarPlot component supports different display modes and orientations:

    • mode: Controls how series are displayed relative to each other. Options are grouped (side-by-side), stacked (summed), or overlay.
    • orientation: Controls the direction of the bars. Options are vertical or horizontal.

    When using categorical data (strings in the x array), you can use x_axis.categories to explicitly define the order of categories on the axis.

    <BarPlot 
      series={band_gaps} 
      mode="grouped" 
      orientation="horizontal" 
      x_axis={{ label: "Band Gap (eV)", categories: ["Diamond", "GaN", "ZnO", "GaAs", "CdTe", "Si"] }} 
      y_axis={{ label: "Semiconductor" }} 
    />
  10. Configure Spectral components (Bands and DOS)

    main

    Spectral components like Bands and Dos accept keyed canonical collections via props like bands_structs or doses.

    Data Requirements:

    • Bands: Requires type: "phonon" | "electronic". Data is in THz for phonons.
    • DOS: Uses the same discriminator with frequencies or energies. Data is in eV for electrons.
    • Constraint: A shared plot cannot mix phonon and electronic types.

    Configuration:

    • units: A shared units prop (default THz) controls both panels. Changing units resets frequency zoom to the converted shared range. Note that bands_props and dos_props do not accept units independently.
    • fermi_level: Both paired viewers accept a shared fermi_level reference (including zero). Omit it to use dataset metadata.

    Data Processing:

    • Use normalize_band_structure or normalize_dos to parse external files.
    • Use extract_pdos(raw, "atom" | "orbital", filter) to extract projections before rendering.
  11. Understand the difference between TDB files and pre-computed JSON diagrams

    main

    When working with MatterViz, it is important to distinguish between raw thermodynamic data and pre-computed visualizations:

    1. TDB Files: Contain the underlying Gibbs energy functions. They require a thermodynamic solver (like pycalphad) to compute phase boundaries.
    2. Pre-computed JSON Files: Located in the ../binary/ directory. These are simplified, approximate representations used for UI demonstrations. They are not thermodynamically rigorous and may omit complex intermetallic phases (e.g., Al-Mg $\beta$/$\gamma$ or Cu-Zn $\beta$/$\gamma$/$\delta$/$\epsilon$).
  12. MatterViz performance limits and constraints

    main

    When using MatterViz in JupyterLab, be aware of the following technical constraints:

    • 100 MB File Limit: Files larger than 100 MB will refuse to parse. Unlike the VS Code extension, there is no host-side streaming; you must parse these in the kernel (e.g., using pymatviz).
    • Web Worker Parsing: Parsing runs in a Web Worker to keep the UI responsive. If parsing fails, it may be due to a Web Worker issue.
    • Trajectory Indexing: For XYZ/EXTXYZ and ASE .traj files exceeding 25 MB (DEFAULTS.trajectory.index_above_bytes), the extension indexes them and decodes frames on demand to save memory.
    • No Auto-Refresh: MatterViz does not automatically refresh when files are updated externally. To see changes, use File $\rightarrow$ Reload from Disk in JupyterLab.