PAOFLOW.gen.paoflow_driver#

Interactive generator for PAOFLOW main.py driver scripts.

Given the output of a Quantum ESPRESSO run (a <prefix>.save directory) and the pseudopotential used for it, this CLI asks a few questions and writes a minimal, clearly-commented main.py that runs PAOFLOW.

Two workflows are supported:

  1. ACBN0 / eACBN0 self-consistent Hubbard U (and intersite V) using the standard basis for the PAO projections.

  2. Full property run from the QE output, where the user picks the properties to compute from a menu. Standard properties use the standard basis; optical properties (dielectric tensor) need the extended basis and the position dipoles in the velocity operator, so they are emitted as a separate PAOFLOW run in the same script.

Two further workflows generate multi-phase driver scripts:

  1. Harmonic phonons (main.phonon.py) – finite-displacement phonons via phonopy (generate supercells -> run pw.x -> analyse forces).

  2. Electron-phonon (paoflow-gen elphon) – writes a system folder in the layout of examples/elphon/<System>: system.py (the only file with values, an ElphonSystem plus per-workflow defaults), qe/ (scf, ph.x with fildvscf, the nscf on the irreducible wedge, run_qe.sh; EPW inputs for the EPW source) and one subfolder per selected workflow (phonons/, coupling/, superconductivity/, optics/, transport/, arpes/) with the drivers of PAOFLOW/gen/elphon_templates (the same thin drivers the examples use, built on PAOFLOW.elphon.workflows). See PAOFLOW.gen.elphon_system.

The generated script is static and heavily commented so it is easy to tweak afterwards.

Attributes#

Functions#

ask(prompt[, default])

Ask for a free-text value with an optional default.

ask_yes_no(prompt[, default])

Ask a yes/no question.

ask_int(prompt, default)

Ask for an integer value with a default.

ask_float(prompt, default)

Ask for a floating-point value with a default.

ask_choice(prompt, choices, default)

Ask the user to pick one item from choices (list of strings).

parse_laser_list(spec)

Parse a laser-wavelength specification into a list of floats (nm).

detect_savedir(workdir)

detect_upfs(workdir[, savedir])

detect_prefix(workdir, savedir)

detect_pw_input(workdir)

A pw.x input in workdir to derive the electron-phonon scf/nscf from.

detect_v_cutoff(workdir)

Read the suggested eACBN0 intersite-V cutoff from a QE input header.

select_properties()

Show the property menu and return the ordered set of chosen keys.

build_run_script(cfg)

Assemble a full property-run main.py from the collected config.

build_acbn0_script(cfg)

Assemble an ACBN0 / eACBN0 main.py from the collected config.

build_phonon_script(cfg)

Assemble a main.phonon.py harmonic-phonon workflow from the config.

build_plot_script(cfg)

Assemble a plot.py that mimics the property selection in cfg.

build_acbn0_plot_script(cfg)

Assemble a plot.acbn0.py that overlays the ACBN0 / eACBN0 band structures.

build_phonon_plot_script(cfg)

Assemble a plot.phonon.py that plots the dispersion, DOS and thermals.

build_raman_script(cfg)

Assemble a main.raman.py non-resonant (Placzek) Raman workflow.

build_raman_plot_script(cfg)

Assemble a plot.raman.py that overlays the broadened Raman spectra.

collect_common(args, workdir)

Prompt for configuration shared by both workflows.

collect_run(common)

Prompt for the full property-run configuration.

collect_phonon(common)

Prompt for the harmonic-phonon (finite-displacement) configuration.

collect_acbn0(common)

Prompt for the ACBN0 / eACBN0 configuration.

main([argv])

Run the interactive generator.

Module Contents#

PAOFLOW.gen.paoflow_driver.ask(prompt, default=None)[source]#

Ask for a free-text value with an optional default.

PAOFLOW.gen.paoflow_driver.ask_yes_no(prompt, default=False)[source]#

Ask a yes/no question.

PAOFLOW.gen.paoflow_driver.ask_int(prompt, default)[source]#

Ask for an integer value with a default.

PAOFLOW.gen.paoflow_driver.ask_float(prompt, default)[source]#

Ask for a floating-point value with a default.

PAOFLOW.gen.paoflow_driver.ask_choice(prompt, choices, default)[source]#

Ask the user to pick one item from choices (list of strings).

PAOFLOW.gen.paoflow_driver.parse_laser_list(spec)[source]#

Parse a laser-wavelength specification into a list of floats (nm).

Accepts a comma- or space-separated list ('488, 514.5, 532') or a restricted Python expression that evaluates to an iterable of numbers, e.g. '[n for n in range(450, 650, 5)]'. The expression is evaluated with no builtins and only range exposed, so it cannot import modules or call arbitrary functions.

PAOFLOW.gen.paoflow_driver.detect_savedir(workdir)[source]#
PAOFLOW.gen.paoflow_driver.detect_upfs(workdir, savedir=None)[source]#
PAOFLOW.gen.paoflow_driver.detect_prefix(workdir, savedir)[source]#
PAOFLOW.gen.paoflow_driver.detect_pw_input(workdir)[source]#

A pw.x input in workdir to derive the electron-phonon scf/nscf from.

PAOFLOW.gen.paoflow_driver.detect_v_cutoff(workdir)[source]#

Read the suggested eACBN0 intersite-V cutoff from a QE input header.

paoflow-gen-qe writes ! Suggested eACBN0 intersite V cutoff: <x> Angstrom into the header of the <compound>.scf.in it generates. Returns that cutoff (in Angstrom) from the first matching input file, or None if no input file or comment is found.

PAOFLOW.gen.paoflow_driver.HEADER = Multiline-String[source]#
Show Value
"""#!/usr/bin/env python3
"""PAOFLOW driver script (generated by paoflow_gen.py).

Edit the constants below and the property calls in the run function(s) to
customize the calculation.  Run with:

    python main.py
    # or, in parallel:
    mpirun -np <N> python main.py
"""

import os
import sys

from PAOFLOW import PAOFLOW
from PAOFLOW.basis_gen import generate_basis_for_pseudo
from PAOFLOW.basis_gen.driver import _default_shells
from PAOFLOW.inputs.read_upf import UPF as _UPFParser

try:
    from mpi4py import MPI

    RANK = MPI.COMM_WORLD.Get_rank()
except ImportError:
    RANK = 0
"""
PAOFLOW.gen.paoflow_driver.BASIS_GEN_BLOCK = Multiline-String[source]#
Show Value
"""
def ensure_basis(preset="extended"):
    """Generate the pseudo-atom basis under BASISPATH for every species.

    The 'extended' preset is a superset of 'standard' and 'minimal', so
    generating it once is enough for every configuration used below.
    """
    if RANK != 0:
        return
    for upf_path in UPFS:
        upf = _UPFParser(upf_path)
        element = upf.element.strip()
        elem_dir = os.path.join(BASISPATH, element)
        expected = _default_shells(upf, preset=preset)
        missing = [
            s for s in expected
            if not os.path.exists(os.path.join(elem_dir, "{}.dat".format(s)))
        ]
        if missing:
            print("Generating pseudo-atom basis for {} under {} ...".format(
                element, BASISPATH))
            generate_basis_for_pseudo(
                upf_path, BASISPATH.rstrip(os.sep), preset=preset, verbose=True
            )
        else:
            print("Using existing pseudo-atom basis for {} under {}".format(
                element, BASISPATH))
"""
PAOFLOW.gen.paoflow_driver.PROJWFC_TEMPLATE_BLOCK = Multiline-String[source]#
Show Value
"""
def ensure_projwfc_template():
    """Write <PREFIX>.projwfc.in for the projwfc.x projector path if missing.

    The ACBN0/eACBN0 driver runs projwfc.x from this template each SCF
    iteration; lwrite_overlaps=.true. is required so the true non-orthogonal
    atomic overlap S(k) is written (mandatory for intersite V).
    """
    if RANK != 0:
        return
    fname = "{}.projwfc.in".format(PREFIX)
    if os.path.exists(fname):
        return
    with open(fname, "w") as fh:
        fh.write("\n".join([
            "&projwfc",
            "   prefix='{}'".format(PREFIX),
            "   outdir='./'",
            "   lwrite_overlaps = .true.",
            "   lbinary_data = .false.",
            "/",
            "",
        ]))
    print("Wrote {}".format(fname))
"""
PAOFLOW.gen.paoflow_driver.ENERGY_RANGE_BLOCK = Multiline-String[source]#
Show Value
"""
def suggest_energy_window(p):
    """Print the full PAO band range (eV, rel. to E_F) as a suggested window.

    Must be called after p.pao_eigh().  The eigenvalues ('E_k') are distributed
    across MPI ranks, so the local extrema are reduced to give every process the
    same global range.  This only prints a hint; the calculation uses the
    user-defined EMIN / EMAX / NE constants above.
    """
    import numpy as np

    E_k = p.data_controller.data_arrays['E_k']
    emin = float(np.amin(E_k))
    emax = float(np.amax(E_k))
    if "MPI" in globals():
        comm = MPI.COMM_WORLD
        emin = comm.allreduce(emin, op=MPI.MIN)
        emax = comm.allreduce(emax, op=MPI.MAX)
    if RANK == 0:
        print('Suggested energy window from PAO bands: '
              'EMIN={:.4f}, EMAX={:.4f} eV'.format(emin, emax))
        print('  (currently using EMIN={}, EMAX={}, NE={})'.format(EMIN, EMAX, NE))
    return emin, emax
"""
PAOFLOW.gen.paoflow_driver.PROPERTY_MENU = [('bands', 'Band structure'), ('dos', 'DOS / projected DOS'), ('transport', 'Boltzmann transport...[source]#
PAOFLOW.gen.paoflow_driver.SPIN_PROPERTIES[source]#
PAOFLOW.gen.paoflow_driver.ENERGY_WINDOW_PROPERTIES[source]#
PAOFLOW.gen.paoflow_driver.select_properties()[source]#

Show the property menu and return the ordered set of chosen keys.

PAOFLOW.gen.paoflow_driver.build_run_script(cfg)[source]#

Assemble a full property-run main.py from the collected config.

PAOFLOW.gen.paoflow_driver.build_acbn0_script(cfg)[source]#

Assemble an ACBN0 / eACBN0 main.py from the collected config.

PAOFLOW.gen.paoflow_driver.build_phonon_script(cfg)[source]#

Assemble a main.phonon.py harmonic-phonon workflow from the config.

The generated script drives the finite-displacement phonon workflow in three phases (generate displaced supercells -> run pw.x -> analyse forces), which can be run together or one at a time (handy on HPC schedulers).

PAOFLOW.gen.paoflow_driver.PLOT_HEADER = Multiline-String[source]#
Show Value
"""#!/usr/bin/env python3
"""Plotting helper for the PAOFLOW run (generated by paoflow_gen.py).

This script mirrors the property selection made when the PAOFLOW driver was
generated.  Run it after the PAOFLOW calculation has produced its output files
and pick what to plot from the menu:

    python plot.py

The energy window and property y-axis limits can be set on the command line:

    python plot.py --emin -5 --emax 5 --ymin 0 --ymax 100

Pass ``--all`` to plot every available quantity without any prompting (the
menu and axis-limit prompts are skipped and the generated defaults are used):

    python plot.py --all

and are also asked for interactively when the script runs (press Enter to keep
the default / command-line value).  EMIN/EMAX set the energy axis (vertical for
band plots, horizontal for the energy-resolved property plots) and default to
the window identified when the driver was generated.  YMIN/YMAX set the property
y-axis and default to automatic scaling.  Optical spectra always start at 0 on
the energy axis.

The plots use the helpers in PAOFLOW.GPAO.
"""

import argparse
import glob
import os
import sys

from PAOFLOW import GPAO


HERE = os.path.dirname(os.path.abspath(__file__))
OUTPUTDIR = os.path.join(HERE, __OUTPUTDIR__)

pplt = GPAO.GPAO()

# Default energy window (eV, relative to E_F) identified when the driver was
# generated.  Overridable on the command line via --emin/--emax.  YMIN/YMAX
# default to None (automatic axis limits) and can be set via --ymin/--ymax.
EMIN = __EMIN__
EMAX = __EMAX__
YMIN = None
YMAX = None


def _ewin():
    """Energy-axis window (EMIN, EMAX) used for band / energy-resolved plots."""
    return (EMIN, EMAX)


def _ewin_optical():
    """Energy-axis window for optical spectra (always starts at 0)."""
    return (0.0, EMAX)


def _ylim():
    """Property-axis limits (YMIN, YMAX), or None for automatic scaling."""
    if YMIN is None and YMAX is None:
        return None
    return (YMIN, YMAX)


def _dos_mag_lim(fnames):
    """Magnitude-axis limits for DOS/PDOS plots.

    When the user sets YMIN/YMAX those win.  Otherwise the magnitude axis is
    rescaled to the data that falls inside the chosen energy window [EMIN, EMAX]
    so that limiting the energy range actually zooms the curve (important for
    metals, whose largest DOS peaks may sit far outside the window).
    """
    if YMIN is not None or YMAX is not None:
        return _ylim()
    if isinstance(fnames, str):
        fnames = [fnames]
    import numpy as np

    peak = 0.0
    for fn in fnames:
        if not fn:
            continue
        try:
            data = np.loadtxt(fn)
        except (OSError, ValueError):
            continue
        if data.ndim != 2 or data.shape[1] < 2:
            continue
        es = data[:, 0]
        mag = data[:, 1:]
        mask = (es >= EMIN) & (es <= EMAX)
        if not mask.any():
            continue
        peak = max(peak, float(np.nanmax(np.abs(mag[mask]))))
    if peak <= 0.0:
        return None
    return (0.0, 1.1 * peak)


def _ask_float(prompt, default):
    """Prompt for a float, accepting Enter to keep *default* (may be None)."""
    shown = 'auto' if default is None else default
    try:
        raw = input('{} [{}]: '.format(prompt, shown)).strip()
    except EOFError:
        return default
    if raw == '':
        return default
    if raw.lower() in ('auto', 'none'):
        return None
    try:
        return float(raw)
    except ValueError:
        print('  (invalid number, keeping {})'.format(shown))
        return default


def _one(pattern):
    """Return the first OUTPUTDIR file matching *pattern* (or None).

    Patterns are written with an optional '<prefix>.' in front (e.g.
    '*.bands_0.dat').  PAOFLOW may write the files either with that prefix
    ('Si.bands_0.dat') or without it ('bands_0.dat'), so a '*.' pattern
    falls back to the prefix-less form.
    """
    hits = sorted(glob.glob(os.path.join(OUTPUTDIR, pattern)))
    if not hits and pattern.startswith('*.'):
        hits = sorted(glob.glob(os.path.join(OUTPUTDIR, pattern[2:])))
    return hits[0] if hits else None


def _many(pattern):
    """Return all OUTPUTDIR files matching *pattern* (sorted).

    As with _one, a '*.' pattern also matches prefix-less files.
    """
    hits = sorted(glob.glob(os.path.join(OUTPUTDIR, pattern)))
    if not hits and pattern.startswith('*.'):
        hits = sorted(glob.glob(os.path.join(OUTPUTDIR, pattern[2:])))
    return hits


def _missing(*names):
    """Warn about missing output files; return True if anything is missing."""
    gone = [n for n in names if n is None]
    if gone:
        print("  (output file(s) not found in {}; run PAOFLOW first)".format(OUTPUTDIR))
        return True
    return False


def _file_energy_range(fname):
    """Return (min, max) of the energy column of *fname*, or None."""
    if not fname:
        return None
    import numpy as np

    try:
        data = np.loadtxt(fname)
    except (OSError, ValueError):
        return None
    if data.ndim != 2 or data.shape[0] == 0:
        return None
    es = data[:, 0]
    return (float(np.nanmin(es)), float(np.nanmax(es)))


def _default_energy_window():
    """Default energy window for the prompts.

    When a DOS file is present its energy grid is used so that the DOS fills
    the side-by-side panel (the DOS is usually computed on a narrower grid than
    the bands).  Otherwise the window identified when the driver was generated
    is kept.
    """
    return _file_energy_range(_one('*.dosdk_0.dat'))


_SPIN_COLORS = ['tab:blue', 'tab:red', 'tab:green', 'tab:orange']


def _spin_channels(pattern):
    """Return ([files], [labels]) for the spin channels of *pattern*.

    The generated patterns target the first spin channel through a '_0' tag.
    A spin-polarized (nspin=2) run also writes the '_1' channel; when present
    both files are returned so the two channels can be overlaid in one figure.
    """
    f0 = _one(pattern)
    if f0 is None:
        return [], []
    files, labels = [f0], ['spin up']
    f1 = _one(pattern.replace('_0.', '_1.'))
    if f1 is not None:
        files.append(f1)
        labels.append('spin down')
    return files, labels


def _overlay_transport(files, labels, title, y_label, scale=1.0, min_zero=False):
    """Overlay the diagonal-averaged transport tensor of several files.

    Used for spin-polarized conductivity / Seebeck output, where each spin
    channel is written to its own file: both channels are drawn on a single
    figure (one line per spin and temperature).
    """
    import numpy as np
    import matplotlib.pyplot as plt
    from PAOFLOW.inputs.read_pao_output import read_transport_PAO

    fig = plt.figure()
    fig.suptitle(title)
    ax = fig.add_subplot(111)
    ic = 0
    ymax = 0.0
    for fn, base in zip(files, labels):
        enes, temps, tensors = read_transport_PAO(fn)
        for it, temp in enumerate(temps):
            trace = scale * np.einsum('eii->e', tensors[it]) / 3.0
            lbl = base if len(temps) == 1 else '{}, T={:g}'.format(base, temp)
            ax.plot(enes, trace, color=_SPIN_COLORS[ic % len(_SPIN_COLORS)], label=lbl)
            ymax = max(ymax, float(np.nanmax(np.abs(trace))))
            ic += 1
    ax.set_xlim(*_ewin())
    yl = _ylim()
    if yl is not None:
        ax.set_ylim(*yl)
    elif min_zero and ymax > 0.0:
        ax.set_ylim(0.0, 1.1 * ymax)
    ax.set_xlabel('Energy (eV)')
    ax.set_ylabel(y_label)
    ax.legend()
    plt.show()


def _overlay_bands_dos(band_files, dos_files, labels, sym_file, title):
    """Bands beside DOS with both spin channels overlaid on one figure.

    Reproduces plot_dos_beside_bands but loops over the spin channels so
    that the two channels share a single bands panel and a single DOS panel.
    """
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import gridspec
    from PAOFLOW.inputs.read_pao_output import (
        read_bands_PAO,
        read_dos_PAO,
        read_band_path_PAO,
    )

    sym_points = read_band_path_PAO(sym_file) if sym_file else None
    y_lim = _ewin()

    fig = plt.figure()
    spec = gridspec.GridSpec(ncols=2, nrows=1, width_ratios=[5, 1])
    fig.suptitle(title)
    ax_b = fig.add_subplot(spec[0])
    ax_d = fig.add_subplot(spec[1])

    nk = 1
    dos_peak = 0.0
    for i, (fb, fd, lbl) in enumerate(zip(band_files, dos_files, labels)):
        col = _SPIN_COLORS[i % len(_SPIN_COLORS)]
        bands = read_bands_PAO(fb)
        nk = bands.shape[1]
        for j, b in enumerate(bands):
            ax_b.plot(b, color=col, label=lbl if j == 0 else None)
        es, dos = read_dos_PAO(fd)
        ax_d.plot(dos, es, color=col, label=lbl)
        mask = (es >= y_lim[0]) & (es <= y_lim[1])
        if mask.any():
            dos_peak = max(dos_peak, float(np.nanmax(np.abs(dos[mask]))))

    ax_b.set_xlim(0, nk - 1)
    ax_b.set_ylim(*y_lim)
    if sym_points is None:
        ax_b.xaxis.set_visible(False)
    else:
        ax_b.set_xticks(sym_points[0])
        ax_b.set_xticklabels(sym_points[1])
        ax_b.vlines(sym_points[0], y_lim[0], y_lim[1], color='gray')
    ax_b.set_ylabel(r'$\epsilon$($\mathbf{k}$) (eV)', fontsize=12)
    ax_b.legend()

    xl = _ylim()
    if xl is not None:
        ax_d.set_xlim(*xl)
    elif dos_peak > 0.0:
        ax_d.set_xlim(0.0, 1.1 * dos_peak)
    ax_d.set_ylim(*y_lim)
    ax_d.yaxis.set_visible(False)
    ax_d.set_xlabel('DOS')

    plt.tight_layout()
    plt.show()
"""
PAOFLOW.gen.paoflow_driver.build_plot_script(cfg)[source]#

Assemble a plot.py that mimics the property selection in cfg.

PAOFLOW.gen.paoflow_driver.build_acbn0_plot_script(cfg)[source]#

Assemble a plot.acbn0.py that overlays the ACBN0 / eACBN0 band structures.

The ACBN0 driver writes one band-structure file per converged case (bands_U for the on-site-U solution and, for eACBN0, bands_UV for the joint U+V solution). This script overlays whichever of those cases are present so they can be compared directly on a single figure.

PAOFLOW.gen.paoflow_driver.build_phonon_plot_script(cfg)[source]#

Assemble a plot.phonon.py that plots the dispersion, DOS and thermals.

Reads the phonon_band.dat / phonon_dos.dat / phonon_band.labels / phonon_thermal.dat files written by main.phonon.py and renders them through PAOFLOW.GPAO.GPAO.

PAOFLOW.gen.paoflow_driver.build_raman_script(cfg)[source]#

Assemble a main.raman.py non-resonant (Placzek) Raman workflow.

The generated script displaces the primitive cell by +/-delta along every optical zone-centre eigenvector (read from the harmonic-phonon FORCE_SETS), writes an SCF-only QE input per displacement, and – in the analyse phase – runs the PAOFLOW internal-projection optical pipeline on each displaced cell to finite-difference the Raman tensor.

PAOFLOW.gen.paoflow_driver.build_raman_plot_script(cfg)[source]#

Assemble a plot.raman.py that overlays the broadened Raman spectra.

PAOFLOW.gen.paoflow_driver.collect_common(args, workdir)[source]#

Prompt for configuration shared by both workflows.

PAOFLOW.gen.paoflow_driver.collect_run(common)[source]#

Prompt for the full property-run configuration.

PAOFLOW.gen.paoflow_driver.collect_phonon(common)[source]#

Prompt for the harmonic-phonon (finite-displacement) configuration.

PAOFLOW.gen.paoflow_driver.collect_acbn0(common)[source]#

Prompt for the ACBN0 / eACBN0 configuration.

PAOFLOW.gen.paoflow_driver.main(argv=None)[source]#

Run the interactive generator.

Parameters:

argv (list of str, optional) – Command-line arguments; sys.argv[1:] by default.

Returns:

Exit status (0 on success). Writes the selected driver and its companion scripts; the electron-phonon workflow writes a system folder instead (PAOFLOW.gen.elphon_system.main_elphon()).

Return type:

int