Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

CView

CView

Crystal Structure Visualization & Analysis

Get Started

CView: Crystal Structure Visualization & Analysis

CView is a high-performance crystallographic tool written in Rust and GTK4. It bridges the gap between structure visualization and ab-initio calculation setup (VASP, QE, SPRKKR).

Tip

Quick Start: Download pre-built binaries for Linux, macOS, or Windows from the Releases Page. See Installation for details.

Important

This version of CView is built on GTK4, which primarily utilizes the CPU for rendering.
While the engine is optimized, it is designed for crystal structures (unit cells, supercells, slabs). It handles systems up to $\approx 5000$ atoms with ease, but it is not suitable for visualizing massive biological macromolecules (e.g., proteins, DNA) containing millions of atoms.
The largest molecule we have tested is of $6000$ atoms core shell polymer.

Tip

CView is not just a viewer; it is a pre-calculation validator. It focuses on Reciprocal Space and Geometric consistency to prevent wasted CPU hours on incorrect VASP/QE inputs.


Why CView?

FeatureDescription
Fast & LightweightBuilt on Rust/GTK4. The main viewer needs no GPU; the 3D charge density view and the trajectory player use OpenGL 3.3, which any laptop from the last decade provides.
Analysis FirstDedicated tools for K-Paths, Slabs, and Void Analysis.
DFT ReadyNative support for VASP (including every step of a vasprun.xml), Quantum Espresso and SPRKKR. LAMMPS dumps are read too — a dump is the same box-plus-coordinates trajectory data as the others, just from a classical-MD code, so it reuses the same reader rather than widening CView’s scope. Relaxations and MD runs play back in the Trajectory Player.
Publication QualityExport high-resolution PNG, PDF, and SVG figures with Cairo-based rendering, and journal-ready 3D charge density figures at a physical size and dpi.

Documentation Overview

This manual is divided into three parts:

  1. Installation: Get CView running on Linux, Windows, or macOS.
  2. User Guide: Deep dive into the scientific methodology.
  3. Tutorials: To Do.

Quick Start

Get up and running in seconds.

Clone and Run

git clone https://github.com/mavensgroup/cview.git
cd cview
cargo run --release

See the Installation Page for detailed OS-specific instructions.


Supported Formats

FormatVASPQuantum EspressoSPRKKRCIF / XYZPDBLAMMPS dump
Read🟢🟢🟢🟢🟢🟢
Write🟢🟠🟠🟢🟢—

Warning

This is a beta release. While the core functionality is operational, the software may contain incomplete features, bugs, or unstable behaviour.

Contributions from testers and developers are welcome.

License & Citation

CView is open-source software licensed under the MIT Licence.

If you use CView in your research, please cite the paper:

Banerjee, R. (2026). CView: a Rust-based integrated environment for inorganic crystallographic analysis and high-fidelity visualization. J. Appl. Cryst. 59(6). https://doi.org/10.1107/S1600576726009003

@article{Banerjee2026CView,
  author    = {Banerjee, Rudra},
  title     = {{CView}: a {Rust}-based integrated environment for inorganic
               crystallographic analysis and high-fidelity visualization},
  journal   = {Journal of Applied Crystallography},
  volume    = {59},
  number    = {6},
  year      = {2026},
  publisher = {International Union of Crystallography (IUCr)},
  doi       = {10.1107/S1600576726009003}
}

Installation

CView releases may provide ready-to-install packages. Check the release assets for your platform; package availability can vary by release.

Tip

New to software installation? Just pick your operating system below and follow the pictures-and-clicks instructions. It’s as easy as installing any app!


Windows 10 / 11

Step-by-Step Installation

  1. Download the installer

    • Go to: CView Releases
    • Click on: cview-installer.exe (19.8 MB)
    • The file will download to your Downloads folder
  2. Run the installer

    • Find cview-installer.exe in your Downloads folder
    • Double-click it to start installation
  3. Handle the security warning (if it appears)

    • Windows might show: “Windows protected your PC”
    • Click “More info”
    • Then click “Run anyway”

    Note

    The installer is not code-signed, so Windows SmartScreen shows it as coming from an “Unknown publisher”. This is expected for small open-source projects: a signing certificate costs money, and the free programmes for open-source software are limited to large projects. CView is built from its public source code by GitHub Actions; each release lists a cview-installer.exe.sha256 checksum you can compare against (Get-FileHash cview-installer.exe in PowerShell). Download it only from the official Releases page.

  4. Follow the installation wizard

    • Click “Next” through the steps
    • Choose install location (default is fine)
    • Wait for installation to complete (takes ~30 seconds)
  5. Launch CView

    • Find “CView” in your Start Menu
    • Or double-click the desktop shortcut (if you chose to create one)

That’s it! CView is now installed and ready to use.


macOS (Intel & Apple Silicon)

Step-by-Step Installation

  1. Download the disk image

    • Go to: CView Releases
    • Click on: cview-macos.dmg (15.9 MB)
    • The file will download to your Downloads folder
  2. Open the DMG file

    • Find cview-macos.dmg in Downloads
    • Double-click to open it
    • A new window will appear showing the CView icon
  3. Install CView

    • Drag the CView icon into the Applications folder icon
    • Wait for the copy to complete (a few seconds)
  4. First launch security step

    When you first open CView from Applications, macOS will block it because it’s not from the App Store.

    Option A: Right-click method (easiest)

    • Find CView in your Applications folder
    • Right-click (or Control-click) on CView
    • Select “Open” from the menu
    • Click “Open” again in the warning dialog

    Option B: Terminal command (if right-click doesn’t work)

    • Open Terminal (Applications → Utilities → Terminal)
    • Type: xattr -cr /Applications/CView.app
    • Press Enter
    • Now open CView normally
  5. Launch CView

    • Find CView in Applications or use Spotlight (⌘ + Space, type “CView”)
    • After the first launch, it will open normally like any Mac app

Important

The security step is only needed once. After that, CView opens normally.


Linux

File to download: cview.flatpak (1.11 MB)

CView for Linux ships as a Flatpak, which works on all Linux distributions.

One-time setup (if you haven’t used Flatpak before):

# Ubuntu/Debian
sudo apt install flatpak

# Fedora (already included)
# Nothing needed!

# Arch
sudo pacman -S flatpak

# openSUSE
sudo zypper install flatpak

Install CView:

# Download
wget https://github.com/mavensgroup/cview/releases/latest/download/cview.flatpak

# Install (no sudo needed with --user)
flatpak install --user cview.flatpak

# Run CView
flatpak run org.mavensgroup.cview

CView will also appear in your applications menu.

Note

Flatpak runs apps in a secure sandbox. Your files are accessible, but CView is isolated from the rest of your system.


Quick Reference Table

Operating SystemFile to DownloadSizeInstallation Method
Windows 10/11cview-installer.exe19.8 MBRun installer, click “Next”
macOS (Intel/M1/M2/M3)cview-macos.dmg15.9 MBDrag to Applications
Linux (any distribution)cview.flatpak1.11 MBflatpak install

Download from: https://github.com/mavensgroup/cview/releases/latest


Build from Source (Advanced Users)

If you want the latest development version or prefer to compile yourself, you can build CView from source.

Prerequisites

You need:

  • Rust (1.75 or newer)
  • GTK4 development libraries
  • Git

Install Dependencies

Ubuntu / Debian
# Install GTK4 development headers and build tools
sudo apt update
sudo apt install build-essential libgtk-4-dev libadwaita-1-dev git

# Install Rust (if not already installed)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
Fedora / RHEL
# Install GTK4 and build tools
sudo dnf install gcc gtk4-devel libadwaita-devel git

# Install Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
Arch Linux
# Install dependencies
sudo pacman -S base-devel gtk4 libadwaita git rust

# Rust is now installed
macOS
# Install Homebrew if you don't have it
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Install dependencies
brew install rust gtk4 libadwaita git
Windows (MSYS2)
  1. Install MSYS2 from msys2.org
  2. Open “MSYS2 MinGW 64-bit” terminal
  3. Run:
pacman -S mingw-w64-x86_64-gtk4 mingw-w64-x86_64-rust mingw-w64-x86_64-gcc git
  1. Add C:\msys64\mingw64\bin to your Windows PATH

Compile and Run

# Clone the repository
git clone https://github.com/mavensgroup/cview.git
cd cview

# Build and run (release mode for best performance)
cargo run --release

First compilation takes 5-10 minutes as Rust downloads and compiles all dependencies. Subsequent builds are much faster.

Install System-Wide (Optional)

# This installs the binary to ~/.cargo/bin/cview
cargo install --path .

# Make sure ~/.cargo/bin is in your PATH
# Add this to your ~/.bashrc or ~/.zshrc:
export PATH="$HOME/.cargo/bin:$PATH"

# Now you can run CView from anywhere
cview

Troubleshooting

macOS: “CView is damaged and can’t be opened”

This means the quarantine flag is still set. Remove it:

xattr -cr /Applications/CView.app

Then try opening CView again.

Windows: “VCRUNTIME140.dll is missing”

Install the Visual C++ Redistributable:

Build from source fails: “gtk4 not found”

Make sure you installed the development packages (with -dev or -devel suffix), not just the runtime libraries.

# Ubuntu/Debian - WRONG
sudo apt install gtk4

# Ubuntu/Debian - CORRECT
sudo apt install libgtk-4-dev libadwaita-1-dev

Flatpak: “No remote refs found”

Make sure Flathub is added:

flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo

Still Having Issues?

  1. Check the GitHub Issues page
  2. Open a new issue with:
    • Your operating system and version
    • The exact error message
    • What you’ve already tried
  3. We’ll help you get CView running!

Verifying Your Installation

After installation, launch CView and try:

  1. Click File → Open
  2. Load a sample structure (we include examples in the repository)
  3. If you see atoms and can rotate the structure → Success!

Welcome to CView! Check out the User Guide to get started.

Loading & Visualization

This section outlines the core workflows for importing structure files, managing the workspace, and controlling the visual representation of crystal structures.

File Operations

Opening Files

To load a structure, navigate to File → Open (Ctrl + O) in the application menu. CView utilizes the native file chooser of your operating system to ensure a familiar experience.

Supported Formats: CView automatically detects the file type based on extension and content. You can open the following formats:

FormatExtensionsDescription
CIF.cifStandard Crystallographic Information Files.
VASPPOSCAR, CONTCAR, .vaspStandard VASP structure inputs and outputs.
VASP runvasprun.xml (any name; recognised by content)Every ionic step of a relaxation or MD run, with its energy and largest force.
Quantum Espresso.in, .out, .pwi, .qeInputs, and every geometry of a relax, vc-relax or MD output (starting with the input structure), with energies and forces.
LAMMPS.dump, .lammpstrj, .dat, any name starting with ITEM: TIMESTEPText dumps: wrapped, scaled or unwrapped positions; orthogonal or triclinic boxes; every frame. Species come from an element or mass column, otherwise atoms are shown as Type n.
SPR-KKR.pot, .pot_new, .sysMunich SPR-KKR potential and system files. Chemical disorder (CPA sites with several occupants) is read as mixed sites and written back as CPA sites. Reading needs nothing extra (.pot, .pot_new, .pot_out). Writing uses CView’s own writer by default; set the environment variable CVIEW_PYTHON to a Python that has ase2sprkkr to write with ase2sprkkr instead — an optional improvement, never a requirement (see Building Structures).
XYZ.xyzCartesian coordinates (Standard and Extended XYZ).
PDB.pdb, .entProtein Data Bank records. Reads the CRYST1 cell, ATOM/HETATM sites, occupancies and formal charges; the first MODEL only. Files without a real cell load as non-periodic molecules.

Note

Why LAMMPS, in a DFT-oriented tool? A LAMMPS dump is, at its core, the same data CView already parses for every other trajectory: a box plus a per-atom coordinate list, one frame after another — structurally the same problem as an Extended XYZ trajectory or a QE vc-relax log, just with LAMMPS’s own column layout. Reading it slots into the trajectory machinery built for vasprun.xml/QE/MD output rather than opening a new area of the code. CView does not run LAMMPS, does not know about force fields, and writes no LAMMPS input — it is a geometry viewer for a dump file someone already produced, exactly as it is for a VASP or QE run.

Trajectories (Relaxation and MD)

Files with several frames — vasprun.xml, Quantum Espresso relax/MD output, LAMMPS dumps — open as one structure in the main view: the first or last frame, set in Preferences → General → Relaxation / MD files open at. All frames are kept.

Structure → Trajectory Player… (Ctrl + Shift + P) plays them in a separate window drawn on the GPU:

  • Play, step and jump with the buttons or Space, , / . (or ← / →), Home / End; set the speed in frames per second.
  • For relaxations, the energy of every step is plotted under the view (click to jump), with the energy, ΔE and largest force of the current step on screen.
  • Show in Main View copies the current frame into the main window for measurements, analysis and vector export; Undo restores the previous structure.
  • Save Image… writes the 3D view as a PNG.

Tab Management

CView uses a tabbed interface to handle multiple structures simultaneously. The application employs a smart loading strategy to keep the workspace clean:

  • Replacement Mode: If the current active tab is empty (labelled “Untitled” with no structure), opening a file will replace this tab.
  • New Tab Mode: If a structure is already loaded, the new file will open in a separate, closable tab.

Note

Upon successfully loading a file, the application logs the event in the Interaction Log and automatically refreshes the Sidebar to display the atom list for the new structure.

Saving & Exporting

Saving Data

To convert a loaded structure into a different format, use File → Save As (Shift+ Ctrl+ S). The output format is determined by the selected file filter in the dialog.

Available Output Formats:
  • CIF (*.cif)
  • VASP POSCAR (POSCAR, *.vasp)
  • SPR-KKR Potential (*.pot)
  • Quantum Espresso Input (*.in)
  • XYZ (*.xyz)
  • PDB (*.pdb)

Visualization Controls

Once a structure is loaded, the View menu provides tools to orient and inspect the crystal lattice.

Standard Views

Quickly align the camera to specific crystallographic axes to inspect symmetry or stacking sequences.

  • View Along A: Aligns camera with the a-axis (y=−90°).
  • View Along B: Aligns camera with the b-axis (x=90°).
  • View Along C: Aligns camera with the c-axis (Standard Plan View).
  • Reset View: Restores the default zoom (1.0) and rotation (0,0).

Rotation Modes

You can customize the pivot point around which the camera rotates, depending on whether you are inspecting the atomic cluster or the lattice boundaries.

ModeDescription
CentroidRotates around the geometric centre of the atoms. Best for inspecting molecules or specific bonding environments.
Unit CellRotates around the centre of the unit cell box. Best for understanding the lattice boundaries relative to the origin.

Exporting Visuals

For publications and presentations, CView offers high-fidelity export options via the File → Export (Ctrl + E) menu.

PNG Image: Renders a high-resolution raster image (default resolution: $2000\times 1500$ pixels). Ideal for slides and quick sharing.

PDF Document: Exports the scene as a vector graphic. This is recommended for academic papers, as it allows for infinite scaling without loss of quality.

SVG Document: Exports an editable vector graphic.


Advanced Appearance Controls

The Sidebar (right panel) is the primary control interface for customizing the visual representation. It contains several collapsible sections:

  1. View Controls: Camera orientation, rotation center
  2. Appearance: Atom size, bond thickness, colors
  3. Bond Valence: BVS-based coloring (see BVS Guide)
  4. Element Colors: Per-element colour, transparency, and polyhedra controls

Color Modes

CView offers two coloring schemes, accessible via the Bond Valence expander’s Color Mode dropdown:

ModeDescriptionUse Case
Element ColorsStandard CPK colours (C=gray, O=red, etc.)General visualization, publication figures
Bond ValenceHeatmap based on the magnitude of BVS deviationIdentifying poorly matched coordination environments

Bond Valence Mode: Colors atoms by the absolute difference between calculated and expected BVS:

  • Green: Good agreement
  • Yellow/orange: Increasing deviation
  • Red: Large deviation

Selecting this mode recalculates BVS and writes a detailed report to the Structure Info panel.

See the Bond Valence Sum Guide for details on the calculation.

Transparency Controls

Each element in the structure has an individual transparency slider in the Atom List section:

  • Use case: Highlight specific atomic species by making others semi-transparent
  • Example: In a LiCoO₂ battery cathode, make Li transparent to see the CoO₂ layers clearly

Tip: Combine transparency with polyhedra (see below) to visualize coordination environments.

Bond Customization

The Bonds section in the sidebar controls:

  • Bond Radius: Thickness of bond cylinders (default: 0.12 Å)
  • Bond Rules…: Which element pairs bond, and over what distance (also View → Bond Rules…)
  • Bond Color: RGB picker for custom bond colors

Bond rules

Bonds are decided per element pair: atoms A and B are bonded when their distance $d$ satisfies $d_{\min}(A,B) < d \leq d_{\max}(A,B)$ (and $d \geq 0.4$ Å; closer atoms are overlapping or split sites). The same rules decide the bonds in the main view, the coordination polyhedra and coordination numbers, and the Trajectory Player.

The defaults are VESTA’s bond list (K. Momma & F. Izumi, J. Appl. Cryst. 44, 1272 (2011)), 914 element pairs, as distributed with pymatgen. So a structure shows the bonds a VESTA user expects: Ti–O (≤ 2.354 Å) and Ba–O (≤ 3.148 Å) in BaTiO₃ but no Ba–Ti, Fe–O in an iron oxide but no Fe–Fe. Pairs VESTA does not list are not bonded, with one exception: VESTA lists no metal–metal pairs and so draws metals and intermetallics without bonds, whereas CView bonds elements that have no listed partner in the structure by covalent radii: $$ d \leq t \times (r_{\text{cov},A} + r_{\text{cov},B}) $$ with tolerance $t$ (default 1.15, set in Preferences and in the Bond Rules window). A Heusler alloy therefore still shows its bonds.

The Bond Rules window lists every element pair in the structure with:

ColumnMeaning
✓Whether the pair bonds
Min, MaxThe distance range (Å)
DefaultWhere the default comes from: VESTA, covalent, — (no default; the length shown is a covalent suggestion) or edited
ShortestThe shortest distance between the two elements in the structure, periodic images included
Bonds/cellHow many bonds the rule draws per cell

So to bond Ba–Ti in BaTiO₃, tick the pair: the shortest Ba–Ti distance (3.471 Å) is below the suggested 3.841 Å, and the table shows the 8 bonds per cell it adds. Edits apply at once and belong to the structure (tab); only the pairs you change are stored, so substituting an element brings in its default rules. Reset to Defaults forgets the changes. The window follows the active tab.


Coordination Polyhedra

CView can visualize coordination polyhedra around cation centers — a feature essential for understanding ionic and metal-oxide structures.

What are Coordination Polyhedra?

A coordination polyhedron is the 3D shape formed by connecting the nearest-neighbor anions around a central cation. Common geometries include:

  • Tetrahedral (CN = 4): SiO₄ in silicates
  • Octahedral (CN = 6): TiO₆ in perovskites
  • Cubic (CN = 8): CsCl structure

Accessing Polyhedra Controls

Location: Sidebar → Appearance → Element Colors

Controls:

  1. Auto-detect Polyhedra button: Automatically enables polyhedra for elements with average coordination number 4–8
  2. Per-element checkboxes: Manually enable/disable polyhedra for specific elements
    • Checkbox labels show the average CN (e.g., “Ti (CN 6)”)
  3. Poly Opacity slider: Adjust polyhedra opacity (5–95%; higher is more opaque). This sets the value for the current structure; the default for new tabs is in Preferences → Polyhedra.
  4. Color by dropdown: what colours the polyhedra
    • Element (the central atom’s colour) or Custom color
    • A computed property: coordination number, mean bond length, Baur distortion Δ, quadratic elongation ⟨λ⟩, bond-angle variance σ², or volume. A colour scale is drawn in the bottom-right of the viewport and in exported images. The scale follows the range of the polyhedra on screen; if they all share one value, the legend states it instead of drawing a gradient. Where a property is undefined for a polyhedron (⟨λ⟩ and σ² need a reference shape for that coordination number), it is drawn grey.
  5. Polyhedra report button: writes a summary to Structure Info: per polyhedron type, the count, mean metrics, and how the polyhedra link (the mean number of other polyhedra each shares one vertex = corner, two = edge, three or more = face). Linkage is computed from the structure’s own periodic images, so polyhedra on the cell boundary are counted correctly.

Inspecting one polyhedron: click the central atom of a polyhedron in the viewport. Besides the usual selection report, Structure Info lists its coordination number, mean and range of bond lengths, Δ, ⟨λ⟩, σ² and volume.

Appearance (Preferences → Polyhedra)

How polyhedra are drawn is a saved preference, separate from what is shown:

  • Edges: None, Subtle (default) or Strong. Only real polyhedron edges are drawn, not the diagonals across flat faces.
  • Default opacity, Back-face opacity (faces turned away from you are drawn fainter, which keeps overlapping polyhedra readable), Shading strength (0 is flat), Mute element colors, and the Colormap used for property colouring.

Changes apply to the current structure immediately and are used for new tabs. Which elements are shown, the colour-by choice and the bond range belong to the structure and are not saved.

How Polyhedra are Computed

Algorithm (implemented in rendering/polyhedra.rs):

  1. Identify cation centers (user-selected or auto-detected)
  2. Find nearest anion neighbors within the bond cutoff distance
  3. Compute the convex hull of the anion positions
  4. Merge coplanar vertices into single flat faces (a square face is one polygon, triangulated once)
  5. Render with proper depth sorting (Polyhedra → Bonds → Atoms)

Critical detail: Polyhedra vertices are restricted to anions only. This prevents chemically meaningless polyhedra (e.g., around O in oxides).

Note

The two-tier ghost system ensures polyhedra are correctly computed across periodic boundaries — ghost atoms used for coordination detection are different from those rendered visually.

Settings

Polyhedra use the configured bond tolerance, a maximum bond-distance cap, and an internal coordination range of 4–12. The sidebar exposes element selection, auto-detection, opacity, colour-by and the bond range; Preferences exposes how polyhedra are drawn. Coordination-number filters are not exposed.

Practical Example: BaTiO₃

In the cubic perovskite BaTiO₃:

  • Ti⁴⁺ is octahedrally coordinated by 6 oxygen atoms → TiO₆ octahedra
  • Ba²⁺ has 12-fold coordination → Cuboctahedral (can be hidden if noisy)

Workflow:

  1. Load BaTiO₃ structure
  2. Click “Auto-Detect” in the sidebar
  3. Ti polyhedra appear as blue octahedra
  4. Adjust transparency to see through to the unit cell

This visualization immediately reveals the corner-sharing connectivity characteristic of perovskites.


Keyboard Shortcuts

ShortcutAction
Ctrl + OOpen file
Shift + Ctrl + SSave structure as…
Ctrl + EExport image (PNG/PDF/SVG)
Ctrl + ,Preferences
Ctrl + WClose tab
Ctrl + ZUndo (e.g. atom deletion)
TToggle Primitive ↔ Conventional cell (canvas focused)
Ctrl + Shift + CMatrix transformation tool
Ctrl + MAdd Miller plane
Ctrl + BToggle bonds
Ctrl + Shift + BToggle full-unit-cell/ghost display
Ctrl + Shift + PTrajectory Player (relaxation / MD files)
Mouse scrollZoom in/out
Left-click dragRotate structure
Shift + clickMulti-select atoms

Performance Notes

The main viewer — structure loading, all analysis, Supercell/Basis/Slab, and PNG/PDF/SVG export — is CPU-based rendering using GTK4/Cairo:

  • Smooth interaction up to ~5000 atoms
  • Real-time rotation and zoom
  • No GPU drivers required (runs on any laptop)

Two optional windows use OpenGL 3.3 instead, because Cairo cannot do what they need: the 3D Isosurface page has to depth-sort and alpha-blend overlapping translucent lobes in real time as you drag a slider, and the Trajectory Player has to redraw every atom at interactive frame rates while scrubbing through hundreds of MD/relaxation steps — both are workloads Cairo’s CPU rasterizer is not built for. Neither window is required for normal use, and the GPU floor is low (OpenGL 3.3, any laptop from the last decade). If you never open them, CView never touches your GPU.

For nanoparticles or proteins with tens of thousands of atoms in the main view, consider specialized GPU-accelerated tools like OVITO or VMD.

Analysis Tools

The Analysis module in CView aggregates tools designed to characterize the geometric, symmetric, and diffraction properties of the loaded crystal structure. Unlike simple visualization, these tools perform computational tasks to extract physical descriptors suitable for comparison with experimental data or preparation for ab initio calculations.

Accessing Analysis Tools

The analysis suite is accessible via the Analysis menu in the main application window. Each menu entry opens the Analysis window (actions_analysis.rs) directly on its own tab, and you can switch between tabs from within the window:

  1. Symmetry (Analysis → Symmetry...): Space group determination and symmetry operation analysis.
  2. XRD (Analysis → Diffraction (XRD)...): X-Ray Diffraction pattern simulation.
  3. Band Path (Analysis → Band Path...): Reciprocal space path generation for band structures.
  4. Void Analysis (Analysis → Void Analysis...): Porosity and intercalation site analysis.

Charge Density is opened separately from Analysis → Charge Density; it is not a tab in the Analysis window.

Slab generation changes the structure, so it is not part of the read-only Analysis window. It has its own window under Structure → Slab…; see Surface Slabs.

Documentation Modules

Detailed physical derivation and algorithmic implementation for each tool are provided below:

  • Symmetry Analysis
    • Engine: Moyo (Rust implementation of Spglib).
    • Output: Space Group symbols, numbers, and crystal systems.
  • XRD Simulation
    • Theory: Kinematic Diffraction Theory.
    • Features: Powder patterns, Cu-K$\alpha$ radiation, Lorentz-Polarization corrections.
  • Void & Intercalation
    • Method: Grid-based geometric insertion.
    • Application: Porosity calculation and battery ion insertion sites.
  • Reciprocal Space (K-Path)
    • Method: High-symmetry path standardization (Setyawan-Curtarolo).
    • Application: Band structure calculation inputs.
  • Surface Slabs
    • Method: Lattice transformation via planar basis searching.

Symmetry Analysis

The Symmetry module identifies the underlying crystallographic space group of the loaded structure. It is essential for reducing computational cost in DFT calculations and validating experimental structures.

Algorithmic Implementation

CView utilizes the Moyo library (a Rust ecosystem equivalent to Spglib) to perform symmetry determination. The analysis pipeline proceeds as follows:

  1. Lattice Standardization: The internal Structure (Cartesian coordinates) is converted into a Moyo::Cell, utilizing the lattice vectors as columns of a $3\times3$ matrix.
  2. Coordinate Transformation: Atomic positions are transformed from Cartesian ($r_{cart}$) to Fractional ($r_{frac}$) coordinates via the inverse lattice matrix: $$r_{frac} = M_{lattice}^{-1} \cdot r_{cart}$$
  3. Symmetry Search: The algorithm searches for symmetry operations (rotations $R$ and translations $t$) that map the crystal onto itself: $$R \cdot r + t \equiv r’ \pmod 1$$ where $r$ and $r’$ are atomic positions of the same species.

Tolerance (SYMPREC)

The code applies a default symmetry precision (SYMPREC) of 1e-4 Å. This tolerance is shared by symmetry analysis, k-path generation, and primitive/conventional-cell conversion.

Outputs

The module returns a SymmetryInfo struct containing:

  • Space Group Number: The International Tables for Crystallography (ITA) number (1–230).
  • International Symbol: The Hermann-Mauguin notation (e.g., $Pm\overline{3}m$, $Fm\overline{3}m$).
  • Crystal System: The classification (Triclinic, Monoclinic, Orthorhombic, Tetragonal, Trigonal, Hexagonal, or Cubic).

Usage Reference

This analysis is performed “read-only” regarding the structure; it calculates descriptors without altering the atomic coordinates of the active tab.

XRD Simulation

The X-Ray Diffraction (XRD) module simulates the powder diffraction pattern for the loaded structure. It utilizes Kinematic Diffraction Theory, assuming ideal interactions without primary extinction or multiple scattering events.

Physical Model

1. Lattice Physics

The simulation first calculates the Reciprocal Lattice vectors ($b_1, b_2, b_3$) from the real space lattice ($a_1, a_2, a_3$): $$b_1 = 2\pi \frac{a_2 \times a_3}{a_1 \cdot (a_2 \times a_3)}$$ (and cyclic permutations for $b_2, b_3$).

2. Bragg Condition

The code iterates through integer Miller indices $(h, k, l)$ to find reciprocal lattice vectors $G_{hkl} = h b_1 + k b_2 + l b_3$. The d-spacing is calculated as: $$d_{hkl} = \frac{2\pi}{|G_{hkl}|}$$ Diffraction peaks are identified where the Bragg condition is met for the source wavelength ($\lambda = 1.5406 Å$, Cu K$\alpha$): $$\lambda = 2d \sin\theta$$

3. Structure Factor ($F_{hkl}$)

The intensity of each reflection is governed by the Structure Factor, calculated by summing over all $N$ atoms in the unit cell: $$F_{hkl} = \sum_{j=1}^{N} f_j(\theta) \exp\left[2\pi i (hx_j + ky_j + lz_j)\right]$$

  • $x_j, y_j, z_j$: Fractional coordinates of atom $j$.
  • $f_j(\theta)$: The atomic scattering factor.

Note

The atomic scattering factor ($f_j(\theta)$) has been calculated using Cromer-Mann coefficient (model/elements.rs)

4. Intensity Correction

The raw squared structure factor $|F_{hkl}|^2$ is corrected to obtain the observed intensity $I$. The primary correction applied in xrd.rs is the Lorentz-Polarization (LP) Factor for unpolarized radiation (standard laboratory diffractometer):

$$ \begin{align} LP(\theta) &= \frac{1 + \cos^2(2\theta)}{\sin^2\theta \cos\theta}\\ I_{calc} &= |F_{hkl}|^2 \times LP(\theta) \end{align}$$

5. Multiplicity and Merging

In powder diffraction, symmetry-equivalent planes (e.g., $(100)$ and $(010)$ in cubic systems) diffract at the same angle. The code algorithmically sorts peaks by $2\theta$ and merges peaks falling within a narrow tolerance ($0.05^\circ$), summing their intensities to account for multiplicity.

6. Match with Experiment

You can load the experimental ascii/xlsx file to compare the xrd using the “Load Experiment” button.

Settings

  • Wavelength: Defaults to Cu K$\alpha_1$ ($1.5406 Å$), but is editable in the XRD tab.
  • Range: Defaults to $10^\circ$ to $90^\circ$ $2\theta$; both limits are editable.
  • Filtering: Peaks with intensity $\leq 10^{-4}$ relative to the maximum are discarded to reduce noise.
  • Additional model terms: The calculation includes an occupancy-weighted Cromer–Mann form factor and one global isotropic Debye–Waller factor. It models K$\alpha_1$ only, without a K$\alpha_2$ doublet or anomalous dispersion.

High symmetry k-points and k-path

Electronic structure calculations (Band Structures) requires sampling the energy eigenvalues along specific high-symmetry lines in the first Brillouin Zone. This module automates the generation of these paths.

Implementation

1. Brillouin Zone Standardization

The code relies on the Moyo library to first determine the Bravais lattice type (e.g., FCC, BCC, HEX). This step is crucial because the definition of “High Symmetry Points” depends entirely on the lattice symmetry.

2. High Symmetry Points

CView implements standard K-point definitions (typically following the Setyawan-Curtarolo convention).

  • Input: Real space structure.
  • Transformation: Converted to Primitive Reciprocal space.
  • Mapping: Standard points (e.g., $\Gamma = [0,0,0]$, $X = [0, 0.5, 0]$) are generated based on the detected space group.

3. Path Generation

The module generates two data sets:

  1. Linear Path: A sequence of k-points (e.g., $\Gamma \rightarrow X \rightarrow W \rightarrow K \rightarrow \Gamma$) for band structure plotting.
  2. Wireframe: A list of Cartesian line segments representing the edges of the first Brillouin Zone, used for 3D visualization in the UI.

Coordinate Systems

The internal logic handles the matrix multiplication to convert between:

  • Fractional Reciprocal Coordinates: Used for DFT inputs (e.g., KPOINTS file).
  • Cartesian Reciprocal Coordinates: Used for the 3D wireframe visualization in CView.

Voids Analysis

This module performs geometric analysis to identify empty space within the crystal lattice. It is critical for research into battery materials (ion intercalation), porous frameworks (MOFs/Zeolites), and defect analysis.

Algorithm: Grid-Based Geometric Insertion

The analysis does not rely on Voronoi decomposition but rather a robust Grid Probe Method.

1. Grid Generation

A regular fractional grid is superimposed over the unit cell. The configured value is a target grid spacing in Å; the engine default is 0.25 Å and the UI initially uses 0.3 Å. The number of divisions along each axis comes from the interplanar spacings ($d_a = V / |b \times c|$, and cyclic), so the configured value is the perpendicular sample spacing whatever the cell shape — for an orthogonal cell $d_a = |a|$. $$P_{grid} = u \cdot a + v \cdot b + w \cdot c \quad \text{where } u,v,w \in [0, 1]$$

2. Distance Field Calculation

For every point on the grid, the algorithm calculates the Euclidean distance to the nearest atomic surface. This accounts for Periodic Boundary Conditions (PBC) by checking nearest neighbor images. $$D_{surf} = \min_{atoms} (||P_{grid} - P_{atom}|| - R_{vdw})$$ Where $R_{vdw}$ is the Van der Waals radius of the atom.

3. Probe Insertion

A geometric probe (representing a gas molecule or ion) with radius $R_{probe}$ is tested at each grid point. A point is considered a “Void” if: $$D_{surf} > R_{probe}$$

The implementation tracks the sampled point with the greatest clearance from every atomic surface, then refines it off the grid with a compass search on the continuous distance function. A pattern search is used rather than a gradient step because several atoms are equidistant at a maximum, so the gradient is discontinuous there. The reported radius is therefore not quantized by the grid spacing — which matters, because at 0.25 Å the quantization error is wide enough to straddle Li$^+$ (0.76 Å) and Mg$^{2+}$ (0.72 Å).

It reports that single global maximum as max_sphere_center; it does not cluster connected void regions into separate cavities.

The largest sphere answers how big is the biggest hole. The site search answers where are all the holes, which is the question that matters before an intercalation study.

Every grid point that is no lower than all 26 of its periodic neighbours is a candidate maximum. Plateaus of equal samples are collapsed to one representative through a union-find over grid adjacency, each representative is refined off the grid as above, and representatives that converge onto the same maximum are merged. What survives is filtered against the Shannon radius of the selected candidate ion.

FCC is the reference case: the search returns exactly twelve sites in two families — four octahedral holes at $a/2$ from the nearest atom, and eight tetrahedral at $a\sqrt{3}/4$.

Sites are drawn in both the analysis preview and the main 3D view (View → Show Interstitial Sites, Ctrl+I) at their fitted radius, so a site that barely admits the ion looks tighter than one with room to spare.

The search reports where a hard sphere fits in the **rigid, as-loaded** framework. It models no electrostatics, no lattice relaxation, and no migration barriers: a site can be geometrically roomy and still be electrostatically impossible, and a real bottleneck opens up under relaxation in ways this does not capture.

Read the output as a screen to run *before* a DFT/NEB calculation, never as a substitute for one.

Performance

Sampling the distance field is the whole cost of the analysis, and both the void numbers and the site list come out of a single sweep rather than two.

Each atom is expanded into its 27 periodic images once, up front, so the minimum-image search disappears from the inner loop, and a uniform cell list reduces that loop to a local neighbourhood scan whose cost does not grow with the number of atoms. On an 18-core machine a 216-atom cell at $0.15,\text{\AA}$ takes about 80 ms whether it is orthogonal or sheared; a 1000-atom cell over 25M grid points takes about 1.1 s.

The sweep runs on a worker thread, so the window stays responsive, and it is cancelled if you start another before it finishes.

Presets and Data

The module includes standard probe definitions for common applications:

  • Gases: He ($1.30 Å$), H$_2$ ($1.45 Å$), H$_2$O ($1.32 Å$), CO$_2$ ($1.65 Å$), N$_2$ ($1.82 Å$), O$_2$ ($1.73 Å$), Ar ($1.70 Å$), Kr ($1.80 Å$), CH$_4$ ($1.90 Å$), and C$_2$H$_6$ ($2.20 Å$).
  • Ions: Li$^+$ ($0.76 Å$), Na$^+$ ($1.02 Å$), Mg$^{2+}$ ($0.72 Å$).

The void fraction is calculated as: $$\phi = \frac{N_{void}}{N_{total}} \times 100%$$

Miller Planes

Miller indices $(hkl)$ are a standard notation for describing crystallographic planes. CView allows you to visualize these planes directly in the viewport and use them as input for slab generation.


Miller Index Notation

A Miller plane $(hkl)$ is defined by its intercepts with the lattice vectors $\mathbf{a}$, $\mathbf{b}$, $\mathbf{c}$:

  • The plane intersects the a-axis at $\mathbf{a}/h$
  • The plane intersects the b-axis at $\mathbf{b}/k$
  • The plane intersects the c-axis at $\mathbf{c}/l$

Special cases:

  • $h = 0$: Plane is parallel to the a-axis (intersects at infinity)
  • Negative indices: Written with a bar, e.g., $(1\bar{1}0)$ for $h=1, k=-1, l=0$

Common Low-Index Planes

PlaneDescriptionExample (Cubic)
$(100)$Perpendicular to a-axisCube face
$(110)$Diagonal through two axesEdge-sharing
$(111)$Diagonal through all three axesClose-packed

In cubic systems, $(100)$, $(010)$, and $(001)$ are equivalent by symmetry. In lower-symmetry systems (e.g., orthorhombic, hexagonal), they are distinct.


Visualizing Miller Planes

Access: View → Miller Indices... (Ctrl + M)

How to Use

  1. Open the Miller Planes dialog
  2. Enter the desired indices $(h, k, l)$
    • Example: 1, 1, 1 for the $(111)$ plane
  3. Click Add

What you see:

  • A semi-transparent plane rendered in the viewport
  • The plane intersects the unit cell edges
  • The plane is clipped to its intersection polygon inside the displayed unit cell

Tip

The viewport polygon is calculated by intersecting the Miller plane with the unit-cell edges. The related integer-basis routine in physics/operations/miller_algo.rs is used for slab construction rather than viewport-plane placement.

Plane Shape

The visible plane is a polygon formed by the intersection of the $(hkl)$ plane with the unit cell boundaries.

Example: In a cubic unit cell:

  • $(100)$ plane → Square (intersects 4 edges)
  • $(110)$ plane → Rectangle
  • $(111)$ plane → Triangle (intersects 3 edges)

The shape reflects the actual crystallographic geometry, not just a generic overlay.


Algorithmic Details

Finding the Plane Basis

CView solves for two in-plane vectors $\mathbf{u}$, $\mathbf{v}$ that:

  1. Lie entirely within the $(hkl)$ plane
  2. Are expressed as integer combinations of $\mathbf{a}$, $\mathbf{b}$, $\mathbf{c}$
  3. Have minimal length (primitive surface cell)

Implementation: find_plane_basis() in miller_algo.rs is used internally for slab generation, where these vectors become the new in-plane lattice vectors. Viewport-plane rendering instead uses direct plane–cell intersection.

Plane Position

The viewport dialog creates the conventional intercept plane $hx + ky + lz = 1$ in fractional coordinates. For slab generation, you can specify:

  • Number of atomic layers to include
  • Vacuum thickness above and below

Connection to Slab Generation

Miller planes are the primary input for creating surface structures:

  1. Select a plane: Use the Miller Planes tool to visualize candidates
  2. Generate slab: Structure → Slab... (uses the same $(hkl)$ indices)
  3. Add vacuum: Specified in Ångströms
  4. Repeat layers: Control slab thickness

See the Slab Generation Guide for details.


Practical Examples

Example 1: TiO₂ Rutile (110) Surface

The $(110)$ plane of rutile TiO₂ is the most stable surface.

Workflow:

  1. Load rutile TiO₂ structure
  2. Open View → Miller Indices...
  3. Enter 1, 1, 0
  4. Observe the plane cutting through rows of oxygen atoms

This helps you understand which atoms will be exposed in a slab calculation.

Example 2: Graphene (0001) Plane

For hexagonal structures like graphite, the $(0001)$ plane (also called the “c-plane”) is perpendicular to the stacking direction.

Indices: Enter 0, 0, 1. CView uses the three-index $(hkl)$ convention.

Note

For hexagonal systems, convert from Miller-Bravais $(hkil)$ to CView’s three-index $(hkl)$ convention before entering indices.


Keyboard Shortcuts

  • Add Plane: Ctrl + M, or View → Miller Indices...
  • Clear Plane: Use Clear All in the dialog. Closing or cancelling the dialog leaves existing planes visible.

Bond Valence Sum (BVS)

The Bond Valence Sum (BVS) module is an empirical analytical tool used to estimate the oxidation states of atoms in a crystal structure and evaluate the physical plausibility of their coordination environments.

Physical Model

The core principle of BVS is that the valence of an atom ($V_i$) is equal to the sum of the individual bond valences ($s_{ij}$) from all its surrounding nearest neighbors: $$BVS_i = \sum_{j} s_{ij}$$

The individual bond valences are calculated using the standard exponential relationship: $$s_{ij} = \exp\left(\frac{R_0 - R_{ij}}{B}\right)$$ Where:

  • $R_{ij}$: The actual measured distance between atom $i$ and atom $j$.
  • $R_0$: The tabulated ideal bond length for the specific atom pair and oxidation state.
  • $B$: An empirical constant, typically $0.37 \text{\AA}$.

Parameter Database

CView does not require you to input $R_0$ parameters manually. The internal engine strictly implements:

  1. Primary Database: The modern IUCr 2020 (bvparm2020.cif) table containing over 1000 oxidation-state-specific element pairs.
  2. Fallback Database: The empirical Brese & O’Keeffe (1991) parameters for untabulated pairs.

Algorithmic Implementation

Unlike basic implementations that use a simple minimum-image convention (which can fail for high-coordination sites like Barium in perovskites where $CN=12$), CView loops over all periodic images within a defined spherical cutoff. This ensures mathematically rigorous summation for complex and tightly packed lattices.

Automatic Valence Matching

Valences are not hardcoded. The algorithm iteratively tests a sequence of plausible valences from the IUCr table (prioritizing the most specific matches first, followed by average sentinel values) to find the best fit for your structure.


Using BVS in CView

Accessing BVS Values

Location: Sidebar → Bond Valence expander

Select Bond Valence from Sidebar → Bond Valence → Color Mode. CView then computes BVS for the loaded structure, applies BVS colours in the viewport, and writes a detailed per-atom report to the Structure Info panel.

Output format (per atom):

Idx   Elem   Ox      BVS   Expect        Δ   CN  Status
0     Fe     +3    2.930    3.000   -0.070    6  ✓ Excel
1     O      -2    1.980    2.000   -0.020    6  ✓ Excel

BVS Color Mode

How to enable: Sidebar → Bond Valence → Color Mode dropdown → Select Bond Valence

Effect: Atoms are coloured by the magnitude of their BVS deviation:

  • Green: Good agreement with the inferred expected valence
  • Yellow/orange: Intermediate deviation
  • Red: Large deviation

The colour does not encode the sign of the deviation, so it does not distinguish under-bonding from over-bonding.

This heatmap is particularly useful for:

  • Identifying structurally strained sites in defective crystals
  • Validating relaxed DFT geometries (all sites should be near-green)
  • Spotting charge transfer in interfaces or heterostructures

Tip

Combine BVS coloring with polyhedra visualization to simultaneously see coordination geometry and electronic state.

Charge Density Visualization

The Charge Density module allows for the visual analysis of 3D volumetric data generated by ab-initio codes, specifically targeting VASP CHGCAR formats. This tool bridges the gap between raw electronic structure outputs and qualitative chemical bonding analysis.

The window has two pages, chosen at the top: Slice (2D) and 3D Isosurface. Both use the files, difference mode and density channel selected on the right; every change applies immediately to both. The sliders you drag to shape the picture sit in a bar under the view and change with the page: slice position (or hkl offset) and number of isolines for the slice; the |ρ| histogram, isovalue and opacity for 3D.

Core Features

2D Slice Extraction

The Slice page uses a high-precision 2D slice extraction technique coupled with a marching squares algorithm for isoline generation.

Slices can be defined in two ways:

  1. Crystallographic Planes: Fast slicing perpendicular to the primary lattice vectors (XY, XZ, YZ planes) at a specific fractional coordinate.
  2. Miller Planes: General slicing along any $(hkl)$ index. The internal engine interpolates the 3D grid data onto the specified arbitrary plane.

Density Channels

For spin-polarized calculations, CView supports extracting specific electronic components:

  • Total Density: Standard $\rho_{up} + \rho_{down}$.
  • Spin-Up / Spin-Down: Isolated individual spin channels.
  • Magnetization: The difference $\rho_{up} - \rho_{down}$. This channel automatically applies a diverging colormap to clearly delineate positive and negative magnetic moments.

Difference Density Maps

A powerful feature of the module is the Difference Mode. You can load two distinct CHGCAR files (e.g., a combined system and an isolated adatom) to compute and visualize charge transfer.

The software calculates $\Delta\rho(r) = \rho_A(r) - \rho_B(r)$ on the fly, allowing you to visually identify regions of electron accumulation and depletion.

Tip

CView utilizes Cairo for high-fidelity 2D rendering. When a slice is drawn, atoms near the slice plane are geometrically projected onto the 2D canvas, using standard CPK colors for easy chemical identification.

Exporting

Slices can be instantly exported as high-resolution png or pdf images directly from the visualization tab, complete with isolines, heatmaps, and atomic projections.

The Export Data (NumPy .npy) action also saves the raw 2D slice as a float64 NumPy array with a JSON sidecar containing the axis extents and labels.

Export Configuration: Settings (font sizes, colorbar tick labels, line thickness) are read live from the Preferences dialog at the moment you click export — not when the window opens. This ensures your exports always match your current preferences.


3D Isosurfaces

The 3D Isosurface page draws isosurfaces of the density together with the atoms and cell, on the GPU (OpenGL 3.3). In this mode the right-hand pane shows the 3D controls.

Surfaces

  • Isovalue in e/ų: the logarithmic slider for exploring, the box for an exact value, or a click on the |ρ| histogram under the view.
  • Set by enclosed charge: choose the fraction of the electrons the surface should enclose (e.g. 50%) and CView finds the isovalue. This compares across systems in a way an absolute isovalue does not.
  • Lobes: +, − or ± (difference and spin densities are detected and shown as ± automatically), with opacity and a colour for each sign.
  • Ambient occlusion darkens crevices and contacts between lobes and atoms, which makes the shape readable in print.
  • Presets set lobes, colours and an enclosed-charge isovalue for total density, bonding/difference maps and spin density.

Surfaces are watertight (no pinholes) and continue seamlessly across cell faces. They are recomputed in the background as you move the slider.

Section plane and cut-away

Section plane draws the density on any $(hkl)$ plane, coloured on a logarithmic scale (or blue–white–red for difference and spin densities) with a contour at the isovalue. Cut away beyond the plane removes surfaces and atoms on one side, so the section becomes the cut face.

Numbers

The view lists the electrons and volume inside each lobe. Report Enclosed Charge writes them, the isovalue and ∫ρ dV over the cell to Structure Info.

Figures for publication

Export Figure… produces a journal-ready image:

  • Pick a journal width (Nature 89/183 mm, Science, ACS) or any size in mm, and 300–1200 dpi (600 dpi is recommended for figures with text). A red frame on the view shows the exported area; Fit to Frame fills it.
  • Fonts and lines are set in points at final size (Nature asks for 5–7 pt); the dialog warns if a Nature figure is taller than 170 mm.
  • PDF / SVG contain the picture at full resolution with the title, isovalue key, colour bar, axes, scale bar and panel letter as vector text, editable in Illustrator or Inkscape. PNG / TIFF carry the dpi, so they open at print size.
  • Transparency is rendered exactly, edges are supersampled, and the background can be transparent for assembling multi-panel figures.
  • A scene file (.cview.json) is saved next to every figure. Load Scene… restores the view, isovalue and all settings, so a requested change is quick to make.

Export Mesh writes the surfaces as OBJ (with colours) or PLY for Blender or ParaView.

Advanced Features

Picture-in-Picture 3D Preview

When viewing a 2D slice, CView displays a 3D miniature of the full crystal structure in the corner of the canvas. This preview shows:

  • The complete unit cell with atoms rendered
  • The orientation of the current slice plane highlighted
  • Real-time updates as you change the slice position or Miller indices

Purpose: Helps maintain spatial context when inspecting arbitrary $(hkl)$ planes — you always know where the slice is cutting through the structure.

Location: Top-right corner of the charge density window (semi-transparent overlay).

HKL Plane Polygon Clipping

For Miller plane slices (non-orthogonal cuts), CView computes the exact intersection polygon:

Example: In a cubic cell, the $(111)$ plane intersects three edges → triangular slice region

Implementation:

  • Computes plane-cell boundary intersections geometrically
  • Clips the heatmap and isolines to the polygon boundary
  • Renders the polygon outline for clarity

This ensures the 2D visualization accurately reflects the crystallographic geometry, not just a rectangular crop.

Visual cue: The slice boundary polygon is drawn in a contrasting color (e.g., white on dark background).

Building Structures

CView provides several tools to manipulate and construct crystal structures. These operations are accessible via the Structure menu and enable you to prepare input geometries for ab-initio calculations.

Supercell, Basis, Atom Instances and Slab are the four tabs of one Structure window. Each menu entry opens the window on its own tab. The first three share a Preview pane: a flat schematic of the cell in the same style as the Slab cutting-plane view (white canvas, element-coloured dots, wireframe cell, the same fixed isometric orientation). It is a preview, not the 3D viewport, so it has no shading or bonds. Highlighted atoms get a dark ring:

  • Supercell previews the structure the current matrix would produce, before you press Transform.
  • Basis highlights the atoms an action would touch: the atoms selected in the main view, and every atom of the element typed into Find.
  • Atom Instances highlights the rows selected in the list.

The window is not modal, so you can keep it open next to the main view.


Building from a Space Group

File → New from Space Group… (Ctrl+N) builds a crystal the way it is tabulated: a space group, the cell parameters and the unique sites (the asymmetric unit). Structure → Space Group & Sites… opens the same window on the current structure, so you can change the cell, swap an element or move a site and apply the result to the tab (Ctrl+Z undoes it).

  • Space group. Type a number or a symbol into Find (225, Fm-3m, P21/c), or pick from the list. Groups with more than one setting (monoclinic unique axis and cell choice, origin choice 1 or 2, hexagonal or rhombohedral axes for R groups) list them under Setting; the ITA standard setting is chosen first.
  • Unit cell. Only the free parameters can be edited: for a cubic group b and c follow a and the angles stay at 90°, for hexagonal axes γ is 120°, and so on.
  • Wyckoff positions. Under the group, every Wyckoff position of the chosen setting is listed with its multiplicity and letter (e.g. 4a), site symmetry and coordinates, from the most special position down to the general one. You don’t need to remember them: click a position to add a site there.
  • Sites. One row per unique site: label, element, Wyckoff position, its free parameters and occupancy. Only the parameters the position leaves free can be typed (x for 24e (x, 0, 0), z for 6c (0, 0, z)); the other coordinates are greyed and show the values the position fixes. Fractions such as 1/3 are accepted. The Site column shows the position the site actually ends up on: if the parameters land it on a more special position (x = 0 on 24e is 4a), it is shown in yellow with an explanation. A site within 0.05 Å of a special position is moved onto it. Sites that land on top of each other are reported under the table.

The preview shows the conventional cell as you type. Create opens it in a new tab; Apply (when editing) replaces the current structure.

When editing, the structure is first standardized: you get its space group in the standard setting, the conventional cell and one site per symmetry orbit, each on its Wyckoff position (Bi₂Se₃ reads as R-3m with Bi on 6c and Se on 3a and 6c). A structure with partially occupied sites, or a molecule, is listed in P1 with every atom as its own site.


Basis Operations

The Basis tab (Structure → Basis...) allows you to perform chemical modifications to your structure.

Element Substitution

Replace an element: replace all instances of one element with another, or only some of them.

Use Cases:

  • Alloying studies (e.g., replacing Ni with Co in Ni₂MnGa)
  • Doping simulations (e.g., substituting Ca with Sr in perovskites)
  • Partial substitution and disordered models (e.g., one O of the three in BaTiO₃ replaced by N, or a random 25% of the O sites in a supercell)
  • Creating hypothetical structures for screening

How to use:

  1. Open Structure → Basis...
  2. In Replace an element, enter the source element in Find and the new element in Replace with. The Atoms to replace count starts at all of them (“of 3” in BaTiO₃).
  3. To replace only some, lower the count. The atoms that will change are ringed in the preview.
    • By default these are the first atoms of that element, in the order of the atom list.
    • Tick Choose at random to draw them at random instead, and Pick again for another draw. A random draw is reproducible within a session (it is not drawn from the system clock), so repeating a step gives the same atoms.
  4. Click Replace. Replacing fewer than all is logged as a partial substitution (for example “1 of 3 O → N”).

For a disordered model you usually want a supercell first (Structure → Supercell...), so that the replaced fraction can be something other than 1/3 or 2/3. To choose specific atoms by hand, select them in the main view and use Selected atoms below.

Note

This operation preserves all atomic positions and lattice parameters — only the element identity changes. The structure’s formula is updated to match.

Mixed Occupancy (Disordered Sites)

For a disordered alloy or solid solution you want each site to hold both elements at fractional occupancies (for example Fe₀.₅Ni₀.₅, or O₀.₆₇N₀.₃₃), not a fixed pattern of swapped atoms.

In the Basis tab

  1. In Replace an element, enter Find and Replace with as usual and choose how many sites to affect (all by default; the count and Choose at random work as above).
  2. Tick Mix in as a partial occupancy, set the Fraction of Replace-with on each site, and click Mix in.

Each chosen site keeps its element at 1 − fraction of its occupancy, and the new element takes fraction, at the same position. For example, mixing N into every O of BaTiO₃ at 0.33 leaves three sites of O 0.67 / N 0.33.

To mix specific sites by hand, select them in the main view and use Mix in under Selected atoms.

What you will see: the main view and the Structure preview draw a mixed site as a sphere split into sectors by occupancy. Structure Info gains an Occ column and the formula carries the fractions (for example BaN0.33O2.67Ti).

What uses the occupancies: XRD and bond-valence sums weight each species by its occupancy (a virtual-crystal approximation). Supercells copy mixed sites unchanged.

Warning

Slab generation and primitive/conventional conversion do not support mixed sites and will refuse with a message rather than return a wrong structure. Build the slab or convert the cell first, then set the mixed occupancies.

Saving mixed sites:

  • SPR-KKR (.pot) is the format built for this: a mixed site is written as a CPA site with several occupants and concentrations (see below).
  • CIF (.cif) writes the occupancy of every atom, with a mixed site as one row per species at the same position (the standard split-site form).
  • POSCAR, Quantum Espresso, XYZ and PDB have no way to hold a mixture here, so a mixed site is written as overlapping atoms and a warning is logged.

Exporting a Disordered Alloy to SPR-KKR

SPR-KKR treats a disordered alloy with the coherent-potential approximation (CPA). Its files describe it as:

  • a site (IQ) is a crystallographic position, listed once;
  • the OCCUPATION section gives each site NOQ occupants, each a type (ITOQ) with a concentration (CONC); the concentrations on a site add up to 1;
  • every (site, element) pair is its own type, with its own potential, so Fe on site 1 and Fe on site 2 are different types.

Reading SPR-KKR potentials needs nothing extra: CView opens .pot, and the files an SCF run writes (.pot_new, .pot_out, any .pot_*), including their CPA sites. Positions and concentrations are read; the potential itself and the SCF results are not.

Writing (Save As → .pot) uses CView’s own writer by default — Python is never required, and a save is identical on every machine. ase2sprkkr is an optional improvement, not a requirement: point CView at a Python that has it and writing switches to the reference implementation, which follows whatever SPR-KKR file format that ase2sprkkr produces.

  1. Install it with pip install ase2sprkkr, then set the CVIEW_PYTHON environment variable to that interpreter (a virtualenv or conda environment works) before starting CView. Without CVIEW_PYTHON, CView never probes for a python3/python on the PATH — saving a .pot touches no interpreter at all unless you asked it to.
  2. CView hands over the cell and the sites with their occupants; atoms that share a position and are partly occupied become one site with several occupants. Each site stays its own site (ase2sprkkr’s symmetry merging is switched off), so Fe₀.₄Cr₀.₃Al₀.₃ on four sites gives NQ 4, NT 12, NOQ 3 on every site, as in a file ase2sprkkr writes for the same alloy.
  3. The log says which writer produced the file (“written by ase2sprkkr 3.5.1”). ase2sprkkr runs with a 60 s timeout; if it hangs or fails, CView falls back to its own writer and logs why.

Without CVIEW_PYTHON (the default), CView writes the file itself and logs that it did, with a reminder of the environment variable that switches to ase2sprkkr — no warning, since this is the expected path for most users. That built-in writer produces a FORMAT 7 start potential. It was checked against an ase2sprkkr file for a four-site Cr/Fe/Al alloy (the global parameters, SCF-INFO, occupation, reference system, magnetisation, mesh and types match) and its Bravais table against xband’s, but it has not been run in SPR-KKR itself. Prefer the ase2sprkkr route for real calculations. In the built-in file:

  • ALAT is in bohr, the vectors and site positions are in units of ALAT, and the cell is rotated to the standard setting (first vector along x, second in the xy plane). This changes no distance or angle.
  • BRAVAIS is detected from the cell (one of SPR-KKR’s 14 lattices).
  • Core and valence electrons (NCORT, NVALT) follow the noble-gas core below each element (Cr 18/6, Fe 18/8, Al 10/3, Cu 18/11). Check them for elements with shallow semicore states (for example Ga 3d, Sn 4d, rare-earth 4f).
  • Everything else is the SPR-KKR default (reference potentials, mesh, a non-magnetic direction). Set SCF options in your SPR-KKR input file.

Both writers: concentrations that do not add to 1 on a site are normalised and a warning is logged; vacancies are not written.

CView also reads these files, including potentials written by an SCF run (ALAT 9.85E+00 style numbers), and shows each CPA site as a pie.

Selection-Based Editing

Selective Modification: Change the element type of specific atoms rather than all instances.

Workflow:

  1. Select atoms in the viewport (click + Shift to multi-select)
  2. Open Structure → Basis...; the Selected atoms card shows how many atoms are selected, and the preview highlights them
  3. Enter the replacement element symbol
  4. Click Change element

Atom Removal: Press Delete after selecting atoms to create vacancies or remove unwanted species.


Cell Type Conversion

Primitive vs. Conventional Cells

Crystallographic structures can be represented in two standard forms:

Cell TypeDescriptionUse Case
PrimitiveMinimum volume unit containing one formula unitElectronic structure calculations (smaller = faster)
ConventionalStandard IUCr representation matching symmetry axesVisualization, publication figures

Example: Face-centered cubic (FCC) structures:

  • Conventional: Cubic cell with atoms at corners + face centers (4 atoms)
  • Primitive: Rhombohedral cell (1 atom)

Toggling Cell Type

Keyboard Shortcut: Press Ctrl + T to toggle between primitive and conventional representations.

Menu Access: Structure → Toggle Primitive/Conventional

What happens:

  • CView uses the moyo library (spglib wrapper) to detect space group symmetry
  • Atomic positions are transformed to the new basis
  • The converted cell replaces the active structure. Conversion is derived from the originally loaded structure, so edits made after loading are not carried through this operation.

Tip

Use primitive cells for DFT calculations to minimize computational cost. Use conventional cells for visualizing crystallographic relationships and comparing to literature structures.

Standardization

The Positions card of the Basis tab provides Standardize positions [0, 1), which wraps atomic fractional coordinates into the unit cell. It does not perform crystallographic IUCr standardization; use primitive/conventional conversion for Moyo-based standard cells.


Atom Instance Management

The Atom Instances tab provides session-only cosmetic overrides for individual atoms. It lets you filter the atom list and apply or reset a display label and colour for selected sites.

Access: Structure → Atom Instances...

Note

These overrides are not written to structure files. Use View → Hide Symmetric Basis or Ctrl + Shift + B to toggle visible periodic images.


For creating larger structures from unit cells, see:

Supercells

A supercell is an integer transformation of the unit cell. Diagonal transformations replicate along lattice vectors; general integer matrices can also shear or swap axes. This is essential for modeling defects, surfaces, interfaces, and finite-size effects in ab-initio calculations.


What is a Supercell?

The supercell transformation multiplies the lattice vectors by integer factors:

$$ \mathbf{a}{super} = N_a \cdot \mathbf{a}, \quad \mathbf{b}{super} = N_b \cdot \mathbf{b}, \quad \mathbf{c}_{super} = N_c \cdot \mathbf{c} $$

All atoms in the original unit cell are replicated at positions: $$ \mathbf{r}{new} = \mathbf{r}{original} + n_a\mathbf{a} + n_b\mathbf{b} + n_c\mathbf{c} $$ where $n_a \in [0, N_a-1]$, $n_b \in [0, N_b-1]$, $n_c \in [0, N_c-1]$.

Result: A structure with $(N_a \times N_b \times N_c)$ times more atoms than the original unit cell.


When to Use Supercells

1. Point Defects

To model vacancies, interstitials, or substitutional dopants, you need sufficient spacing between periodic images to avoid spurious interactions.

Example: A single oxygen vacancy in TiO₂:

  • Unit cell: 6 atoms → Too small (vacancy concentration = 16.7%)
  • 2×2×3 supercell: 72 atoms → Realistic dilute defect (1.4%)

Rule of thumb: Aim for at least 10 Å separation between defects.

2. Surface Calculations

When combined with slab generation, supercells allow you to model surface reconstructions, adsorbates, or step edges without artificial periodicity.

Typical workflow:

  1. Create a 1×1×1 slab (surface + vacuum)
  2. Expand to 2×2×1 or 3×3×1 supercell
  3. Add adsorbate at specific site

3. Alloying & Disorder

To simulate random alloys (e.g., Ni₀.₅Co₀.₅) or partially occupied sites, you need enough atoms to represent the composition statistically.

Example: 50% Ni / 50% Co substitution:

  • 2×2×2 FCC supercell: 32 atoms → 16 Ni + 16 Co

4. Phonons & Finite-Temperature

Phonon calculations (via DFPT or frozen phonons) often require supercells to sample specific q-points or to avoid interactions between atomic displacements.


Using the Supercell Tool

Access: Structure → Supercell... (Ctrl + Shift + C)

Interface

The Supercell tab of the Structure window presents a 3×3 integer matrix, with a live Preview of the resulting structure and its atom count. Past about 4000 atoms the preview is skipped and only the count is shown. Its default is the identity matrix, which leaves the structure unchanged.

  • In the default diagonal mode, use diagonal values such as 2, 2, 3 for a 2×2×3 replication.
  • Enable General Matrix (Shear/Swap) to edit off-diagonal entries for non-diagonal cell transformations.
  • The matrix must be non-singular; with a singular matrix (determinant 0) the Transform button is disabled.
  • After Transform the matrix returns to the identity, so the preview shows the structure as it now is. Reset to as-loaded goes back to the originally loaded cell.

Workflow

  1. Load your structure (e.g., a primitive cell)
  2. Open Structure → Supercell...
  3. Enter the desired diagonal values (for example, 2, 2, 3)
  4. Check the preview, then click Transform
  5. The new structure replaces the current tab

Tip

The supercell is generated instantly for typical dimensions (up to ~5×5×5). For very large expansions, expect a few seconds of computation.

Example: BaTiO₃ 2×2×2 Supercell

  • Original: 5 atoms (Ba, Ti, 3×O) in perovskite unit cell
  • After 2×2×2: 40 atoms
  • Use case: Model a single Ti → Zr substitutional defect

You can now use the Basis Operations to selectively replace one Ti atom with Zr.


Performance Considerations

Memory Limits

CView is optimized for structures up to ~5000 atoms. Beyond this, rendering may slow down:

Supercell SizeAtoms (BaTiO₃)Performance
2×2×240Instant
5×5×5625Smooth
10×10×105000Acceptable
20×20×2040000Not recommended

Caution

The main viewer uses CPU-based (Cairo) rendering, so very large supercells get sluggish past ~5000 atoms. MD trajectories have their own GPU-accelerated Trajectory Player and don’t need a supercell for playback. For nanoparticles with >10,000 atoms, consider specialized tools like OVITO or VMD.

DFT Calculation Cost

Remember that DFT cost scales as $O(N^3)$ with atom count. A 2×2×2 supercell (8× atoms) will be ~500× slower than the primitive cell.

Optimization strategy:

  1. Always use the smallest supercell that captures your physics
  2. For defects: Check convergence of formation energy with supercell size
  3. For surfaces: 2×2 or 3×3 is typically sufficient

Output Formats

After generating a supercell, you can export it via File → Save Structure As:

  • VASP (POSCAR): Commonly used for DFT
  • Quantum Espresso input: Writes the transformed structure
  • CIF: For archival or database submission
  • XYZ: Cartesian-coordinate interchange
  • SPR-KKR: Potential/system-oriented structure export
  • PDB: Molecular-viewer interchange (non-periodic structures write the placeholder 1 1 1 90 90 90 cell)

The transformed structure retains the correct lattice vectors and atomic positions. Output coordinate conventions follow the selected file format.


Surface Slabs (Building)

Creating surface models from bulk crystals is a prerequisite for surface science calculations (catalysis, work function, surface energy). The Slab Builder mathematically transforms the unit cell to expose a specific Miller Index plane $(hkl)$.

Mathematical Formulation

1. Basis Transformation

The core challenge is finding two lattice vectors ($u, v$) that lie perfectly within the plane defined by the normal vector $(hkl)$, and a third vector ($w$) that projects out of the plane.

The algorithm (find_plane_basis in miller_algo) solves the Diophantine equation so integer linear combinations of the original lattice vectors form the new surface basis. It selects short vectors in index space; for strongly anisotropic lattices this is valid but is not guaranteed to minimize the physical surface-cell area.

2. Basis Re-mapping

Once the new basis matrix $M_{surf}$ is found, all atomic positions $r$ are transformed: $$r_{new} = M_{surf}^{-1} \cdot r_{old}$$ Atoms are then wrapped to lie within the boundaries $[0, 1)$ of the new unit cell.

3. Slab Generation

  1. Replication: The unit cell is repeated thickness times along the new $c$-axis (surface normal).
  2. Vacuum: The lattice vector $c$ is elongated by adding vacuum distance (in Ångstroms). $$c_{final} = c_{slab} + c_{vacuum}$$ This isolates the slab in the z-direction, preventing spurious interactions between periodic images in DFT calculations.

Duplicate Removal

The code includes a proximity check (remove_duplicate_atoms with TOLERANCE = 1e-5) to ensure that atoms lying exactly on cell boundaries are not double-counted during the wrapping process.

To Do

Planned features, roughly in priority order. Contributions are welcome — open an issue before starting on one so work isn’t duplicated.

Building and editing structures

  • Build a structure from a space group and its unique atomic sites (asymmetric unit), and edit an existing structure the same way.
  • Add and move atoms interactively, with undo.

Visualization

  • Bond rules per element pair (minimum/maximum distance, boundary handling), shared by bonds, polyhedra and bond valence.
  • Magnetic moments as arrows, read from VASP (MAGMOM, OUTCAR), Quantum Espresso and magnetic CIF.
  • Thermal ellipsoids from anisotropic displacement parameters in CIF.
  • Overlay two structures in one view.

File formats

  • Volumetric data from XSF/AXSF and Gaussian cube, in the existing Charge Density window.
  • Structures from WIEN2k, CASTEP, FHI-aims and ABINIT.

Analysis

  • Measurements on five or more selected atoms (centroid, plane fit) and explicit Distance / Angle / Dihedral buttons.
  • Fermi surfaces from BXSF files.
  • Phonon mode animation.

Automation

  • Command-line conversion, standardization, k-path and figure export without opening the window.
  • Python scripting.