# MIT License
#
# Copyright (c) 2024-2026 Inverse Materials Design Group
#
# Author: Ihor Radchenko <yantar92@posteo.net>
#
# This file is a part of MatRiFFlow package
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""mrf sub-command to compare VASP inputs/outputs."""
import argparse
import logging
import math
import os
import shutil
import warnings
from argparse import Namespace
from xml.etree.ElementTree import ParseError
from pymatgen.analysis.structure_matcher import StructureMatcher
from pymatgen.core import Structure
from pymatgen.io.vasp.inputs import Poscar
from rich.console import Console
from rich.text import Text
from termcolor import colored
from matrifflow.common import groupby_cmp, open_progress_bar
from matrifflow.pymatgen.io.vasp.inputs import Incar, INCAR_GROUP_IGNORE_FIELDS
from matrifflow.pymatgen.io.vasp.vaspdir import MRFVaspDir
logger = logging.getLogger(__name__)
[docs]
def structure_add_args(parser: argparse.ArgumentParser) -> None:
"""Setup parser arguments for structure comparison.
Args:
parser: Subparser from argparse.
"""
parser.set_defaults(func_diff=diff_structures)
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument(
"--poscar",
action='store_true',
help="Force comparing POSCARs"
)
group.add_argument(
"--vasprun",
action='store_true',
help="Force comparing VASP outputs"
)
parser.add_argument(
"--copy-to",
dest="copy_to",
help="Copy the unique structures to specified directory",
type=str
)
parser.add_argument(
"--energy-tol",
dest="energy_tol",
help="Energy tolerance when comparing structures"
" (number of digits after dot)",
default=3,
type=int
)
def _read_structures(
dir_list: list[str],
force_poscar: bool = False,
force_vasprun: bool = False) -> list[Structure]:
"""Read structures from DIR_LIST.
``--poscar`` forces reading POSCAR files; ``--vasprun`` forces
reading ``vasprun.xml``. Without either flag, all directories must
agree: if every directory has a ``vasprun.xml`` the final structures
are read from it, otherwise the POSCAR files are used. A mixture is
an error.
With ``--vasprun``, directories without a ``vasprun.xml`` are warned
about and skipped.
Args:
dir_list (list[str]): List of directories to read.
force_poscar (bool): Force reading POSCAR.
force_vasprun (bool): Force reading Vasprun.
Returns: list[Structure]
List of structures. Each structure will have its 'source_dir'
property set to its origin directory.
When a structure is read from vasprun.xml, it will also have
'final_energy' property set to the final structure energy.
"""
def read_vasprun(vaspdir: str) -> Structure:
logger.info("Reading vasprun.xml from %s", vaspdir)
run = MRFVaspDir(vaspdir)['vasprun.xml']
if run is None:
raise ParseError(f"No readable vasprun.xml in {vaspdir}")
res_structure = run.final_structure
res_structure.properties['source_dir'] = vaspdir
res_structure.properties['final_energy'] = run.final_energy
return res_structure
def read_poscar(vaspdir: str) -> Structure:
logger.info("Reading POSCAR from %s", vaspdir)
poscar = Poscar.from_file(os.path.join(vaspdir, "POSCAR"))
res_structure = poscar.structure
res_structure.properties['source_dir'] = vaspdir
return res_structure
has_vasprun = [
'vasprun.xml' in MRFVaspDir(d) for d in dir_list
]
if force_poscar:
source = ["poscar"] * len(dir_list)
elif force_vasprun:
source = ["vasprun" if hv else "skip" for hv in has_vasprun]
elif all(has_vasprun):
source = ["vasprun"] * len(dir_list)
elif not any(has_vasprun):
source = ["poscar"] * len(dir_list)
else:
with_output = [d for d, hv in zip(dir_list, has_vasprun) if hv]
without_output = [d for d, hv in zip(dir_list, has_vasprun) if not hv]
raise ValueError(
"Mixed directories: some have VASP output and some do not.\n"
f"With vasprun.xml: {', '.join(with_output)}\n"
f"Without vasprun.xml: {', '.join(without_output)}\n"
"Re-run with --poscar or --vasprun to choose explicitly."
)
structures: list[Structure] = []
with open_progress_bar(len(dir_list), title='Reading VASP dirs') as abar:
for vaspdir, src in zip(dir_list, source):
abar.text = f'{vaspdir}'
if src == "vasprun":
try:
structures.append(read_vasprun(vaspdir))
except ParseError:
warnings.warn(
f"Failed to read vasprun from {vaspdir}. Skipping"
)
elif src == "poscar":
structures.append(read_poscar(vaspdir))
else: # "skip"
warnings.warn(
f"No vasprun.xml in {vaspdir}. Skipping (--vasprun)."
)
abar()
return structures
def _copy_structures_to(
structures: list[Structure], directory: str) -> None:
"""Copy source directories of structures to a target directory.
Args:
structures: List of structures, each with a ``'source_dir'`` property.
directory: Target directory to copy source directories into.
"""
source_dirs = [s.properties['source_dir'] for s in structures]
subdirs: list[str] = []
print(f"Copying unique structures to '{directory}'...", end='', flush=True)
for idx, source in enumerate(source_dirs):
if os.path.isabs(source):
target_subdir = os.path.basename(source)
else:
target_subdir = source
# Avoid directories with the same name
if target_subdir in subdirs:
target_subdir = target_subdir + f".{idx + 1}"
subdirs.append(target_subdir)
shutil.copytree(source, os.path.join(directory, target_subdir))
print(f"\rCopying unique structures to '{directory}'...",
colored('done', 'green'))
[docs]
def diff_structures(args: Namespace) -> None:
"""Compare structures.
Args:
args: Parsed command-line arguments from argparse.
"""
args.dirs = [d for d in args.dirs if os.path.isdir(d)]
structures = _read_structures(sorted(args.dirs), args.poscar, args.vasprun)
matcher = StructureMatcher(attempt_supercell=True, scale=False)
def _structures_eq(str1: Structure, str2: Structure) -> bool:
"""Compare structures STR1 and STR2 for equality.
Return True when they are equal.
"""
str1_energy = str1.properties.get('final_energy', None)
if str1_energy is not None:
# Err if energy is available in one structure, but not
# another.
str2_energy = str2.properties['final_energy']
if not math.isclose(
str1_energy, str2_energy,
abs_tol=math.pow(10, -args.energy_tol)):
return False
if matcher.fit(str1, str2):
return True
return False
def _structure_name(struct: Structure) -> str:
"""Get directory."""
return struct.properties['source_dir']
groups = groupby_cmp(structures, _structures_eq, _structure_name)
print(colored(
"List of structures grouped by similarity",
'magenta', attrs=['bold']))
# Sort groups by energy
groups = sorted(
groups,
key=lambda group: group[0].properties.get(
'final_energy', 0))
prev_energy = None
for idx, group in enumerate(groups):
print(colored(f"Group {idx + 1}: ", attrs=['bold']), end='')
if 'final_energy' in group[0].properties:
final_energy = round(
group[0].properties['final_energy'],
args.energy_tol)
energy_diff = (final_energy - prev_energy)\
if prev_energy is not None else 0
prev_energy = final_energy
print(f"Energy={final_energy}eV ({energy_diff:+.3f}) ", end='')
else:
print("Energy=N/A ", end='')
for s in group:
print(s.properties['source_dir'], ' ', end='')
print()
if args.copy_to is not None:
_copy_structures_to([group[0] for group in groups], args.copy_to)
[docs]
def incar_add_args(parser: argparse.ArgumentParser) -> None:
"""Setup parser arguments for incar comparison.
Args:
parser: Subparser from argparse.
"""
parser.set_defaults(func_diff=diff_incar)
def _ignored_params_summary(groups: list[list[Incar]]) -> list[str]:
"""Collect distinct values of grouping-ignored INCAR tags.
Args:
groups: List of groups, each a list of Incar instances.
Returns:
list[str]: ``"TAG:VAL"`` or ``"TAG:VAL1,VAL2,..."`` entries for
every ignored tag (except ``SYSTEM``) present in any group, in
first-seen order.
"""
ignored = [f for f in INCAR_GROUP_IGNORE_FIELDS if f != 'SYSTEM']
seen: dict[str, list[object]] = {}
for group in groups:
for incar in group:
for field in ignored:
if field not in incar:
continue
vals = seen.setdefault(field, [])
if incar[field] not in vals:
vals.append(incar[field])
return [
f"{field}:{','.join(str(v) for v in vals)}"
for field, vals in seen.items()]
[docs]
def print_incar_groups(
common_incar: Incar,
groups: list[list[Incar]],
console: Console | None = None,
max_names: int | None = None) -> None:
"""Print common INCAR parameters (condensed) and per-group differences.
Args:
common_incar: Incar with parameters shared by every group.
groups: List of groups, each a list of Incar instances carrying
a ``SYSTEM`` entry with the source directory name.
console: rich Console to print to (defaults to a new one).
max_names: Cap the number of directory names shown per group;
remaining names are collapsed into ``...``. ``None`` shows
every name.
"""
if console is None:
console = Console()
common_params = " ".join(
f"{key}:{val}" for key, val in common_incar.items())
console.print(Text.assemble(
("Common parameters: ", "bold"), (common_params, "")))
ignored_params = _ignored_params_summary(groups)
if ignored_params:
console.print(Text.assemble(
("Ignored parameters: ", "bold"),
(" ".join(ignored_params), "")))
for idx, group in enumerate(groups):
names = [incar['SYSTEM'] for incar in group]
if max_names is not None and len(names) > max_names:
shown = " ".join(names[:max_names]) + " ..."
else:
shown = " ".join(names)
diff_keys = [
key for key in group[0]
if key not in common_incar
and key != "SYSTEM"
and key not in INCAR_GROUP_IGNORE_FIELDS]
# diff_incar = Incar({key: group[0][key] for key in diff_keys})
if diff_keys:
diff_string = " ".join(f"{key}:{group[0][key]}" for key in diff_keys)
# console.print(Text(f"Group {idx + 1} params:", style="bold"))
# console.print(diff_incar.get_str(pretty=True))
else:
diff_string = ""
console.print(Text.assemble(
(f"Group {idx + 1}: ", "bold"), (diff_string, "")))
console.print(Text(shown, style=""))
[docs]
def diff_incar(args: Namespace) -> int:
"""Handle diff commands.
Args:
args: Args from command.
"""
args.dirs = [d for d in args.dirs if os.path.isdir(d)]
incars: list[Incar] = []
with open_progress_bar(len(args.dirs), title='Reading INCARs') as abar:
for vaspdir in args.dirs:
abar.text = f'{vaspdir}'
try:
incar = Incar.from_file(os.path.join(vaspdir, "INCAR"))
# Abuse unused SYSTEM parameter to store directory name.
incar['SYSTEM'] = vaspdir
incars.append(incar)
except FileNotFoundError:
warnings.warn(
f"No INCAR found in {vaspdir}"
)
abar()
common_incar, groups = Incar.group_incars(incars)
assert common_incar is not None
print_incar_groups(common_incar, groups)
return 0
[docs]
def add_args(parser: argparse.ArgumentParser) -> None:
"""Register subcommand arguments.
Args:
parser: Sub-parser from argparse.
"""
subparsers = parser.add_subparsers(required=True)
parser_structure = subparsers.add_parser(
"structure",
help="Group structures by symmetry and energy",
description="""\
Group VASP structures by symmetry and energy across directories.
Reads structures from VASP outputs (vasprun.xml) or POSCAR files,
matches them by symmetry, and reports groups of identical
configurations sorted by energy. Optionally copies unique structures
to a target directory.""")
parser_structure.add_argument(
"dirs",
help="VASP directories to compare",
nargs="+",
type=str
)
structure_add_args(parser_structure)
parser_incar = subparsers.add_parser(
"incar",
help="Compare INCAR files across directories",
description="""\
Compare INCAR files across VASP directories.
Groups directories by their INCAR parameters and reports common
settings and per-group differences.""")
parser_incar.add_argument(
"dirs",
help="VASP directories to compare",
nargs="+",
type=str
)
incar_add_args(parser_incar)
[docs]
def diff(args: Namespace) -> int:
"""Run the diff subcommand.
Args:
args: Parsed command-line arguments from argparse.
Returns:
int: Exit code (0 on success).
"""
args.func_diff(args)
return 0